PackageManagerService.java revision 161bd9aae46088cb62e78af428ef9f2b1172c0dc
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
883    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
884    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
885
886    // backup/restore of preferred activity state
887    private static final String TAG_PREFERRED_BACKUP = "pa";
888
889    private final String mRequiredVerifierPackage;
890
891    private final PackageUsage mPackageUsage = new PackageUsage();
892
893    private class PackageUsage {
894        private static final int WRITE_INTERVAL
895            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
896
897        private final Object mFileLock = new Object();
898        private final AtomicLong mLastWritten = new AtomicLong(0);
899        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
900
901        private boolean mIsHistoricalPackageUsageAvailable = true;
902
903        boolean isHistoricalPackageUsageAvailable() {
904            return mIsHistoricalPackageUsageAvailable;
905        }
906
907        void write(boolean force) {
908            if (force) {
909                writeInternal();
910                return;
911            }
912            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
913                && !DEBUG_DEXOPT) {
914                return;
915            }
916            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
917                new Thread("PackageUsage_DiskWriter") {
918                    @Override
919                    public void run() {
920                        try {
921                            writeInternal();
922                        } finally {
923                            mBackgroundWriteRunning.set(false);
924                        }
925                    }
926                }.start();
927            }
928        }
929
930        private void writeInternal() {
931            synchronized (mPackages) {
932                synchronized (mFileLock) {
933                    AtomicFile file = getFile();
934                    FileOutputStream f = null;
935                    try {
936                        f = file.startWrite();
937                        BufferedOutputStream out = new BufferedOutputStream(f);
938                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
939                        StringBuilder sb = new StringBuilder();
940                        for (PackageParser.Package pkg : mPackages.values()) {
941                            if (pkg.mLastPackageUsageTimeInMills == 0) {
942                                continue;
943                            }
944                            sb.setLength(0);
945                            sb.append(pkg.packageName);
946                            sb.append(' ');
947                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
948                            sb.append('\n');
949                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
950                        }
951                        out.flush();
952                        file.finishWrite(f);
953                    } catch (IOException e) {
954                        if (f != null) {
955                            file.failWrite(f);
956                        }
957                        Log.e(TAG, "Failed to write package usage times", e);
958                    }
959                }
960            }
961            mLastWritten.set(SystemClock.elapsedRealtime());
962        }
963
964        void readLP() {
965            synchronized (mFileLock) {
966                AtomicFile file = getFile();
967                BufferedInputStream in = null;
968                try {
969                    in = new BufferedInputStream(file.openRead());
970                    StringBuffer sb = new StringBuffer();
971                    while (true) {
972                        String packageName = readToken(in, sb, ' ');
973                        if (packageName == null) {
974                            break;
975                        }
976                        String timeInMillisString = readToken(in, sb, '\n');
977                        if (timeInMillisString == null) {
978                            throw new IOException("Failed to find last usage time for package "
979                                                  + packageName);
980                        }
981                        PackageParser.Package pkg = mPackages.get(packageName);
982                        if (pkg == null) {
983                            continue;
984                        }
985                        long timeInMillis;
986                        try {
987                            timeInMillis = Long.parseLong(timeInMillisString.toString());
988                        } catch (NumberFormatException e) {
989                            throw new IOException("Failed to parse " + timeInMillisString
990                                                  + " as a long.", e);
991                        }
992                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
993                    }
994                } catch (FileNotFoundException expected) {
995                    mIsHistoricalPackageUsageAvailable = false;
996                } catch (IOException e) {
997                    Log.w(TAG, "Failed to read package usage times", e);
998                } finally {
999                    IoUtils.closeQuietly(in);
1000                }
1001            }
1002            mLastWritten.set(SystemClock.elapsedRealtime());
1003        }
1004
1005        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1006                throws IOException {
1007            sb.setLength(0);
1008            while (true) {
1009                int ch = in.read();
1010                if (ch == -1) {
1011                    if (sb.length() == 0) {
1012                        return null;
1013                    }
1014                    throw new IOException("Unexpected EOF");
1015                }
1016                if (ch == endOfToken) {
1017                    return sb.toString();
1018                }
1019                sb.append((char)ch);
1020            }
1021        }
1022
1023        private AtomicFile getFile() {
1024            File dataDir = Environment.getDataDirectory();
1025            File systemDir = new File(dataDir, "system");
1026            File fname = new File(systemDir, "package-usage.list");
1027            return new AtomicFile(fname);
1028        }
1029    }
1030
1031    class PackageHandler extends Handler {
1032        private boolean mBound = false;
1033        final ArrayList<HandlerParams> mPendingInstalls =
1034            new ArrayList<HandlerParams>();
1035
1036        private boolean connectToService() {
1037            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1038                    " DefaultContainerService");
1039            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1040            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1041            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1042                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1043                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1044                mBound = true;
1045                return true;
1046            }
1047            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1048            return false;
1049        }
1050
1051        private void disconnectService() {
1052            mContainerService = null;
1053            mBound = false;
1054            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1055            mContext.unbindService(mDefContainerConn);
1056            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1057        }
1058
1059        PackageHandler(Looper looper) {
1060            super(looper);
1061        }
1062
1063        public void handleMessage(Message msg) {
1064            try {
1065                doHandleMessage(msg);
1066            } finally {
1067                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1068            }
1069        }
1070
1071        void doHandleMessage(Message msg) {
1072            switch (msg.what) {
1073                case INIT_COPY: {
1074                    HandlerParams params = (HandlerParams) msg.obj;
1075                    int idx = mPendingInstalls.size();
1076                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1077                    // If a bind was already initiated we dont really
1078                    // need to do anything. The pending install
1079                    // will be processed later on.
1080                    if (!mBound) {
1081                        // If this is the only one pending we might
1082                        // have to bind to the service again.
1083                        if (!connectToService()) {
1084                            Slog.e(TAG, "Failed to bind to media container service");
1085                            params.serviceError();
1086                            return;
1087                        } else {
1088                            // Once we bind to the service, the first
1089                            // pending request will be processed.
1090                            mPendingInstalls.add(idx, params);
1091                        }
1092                    } else {
1093                        mPendingInstalls.add(idx, params);
1094                        // Already bound to the service. Just make
1095                        // sure we trigger off processing the first request.
1096                        if (idx == 0) {
1097                            mHandler.sendEmptyMessage(MCS_BOUND);
1098                        }
1099                    }
1100                    break;
1101                }
1102                case MCS_BOUND: {
1103                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1104                    if (msg.obj != null) {
1105                        mContainerService = (IMediaContainerService) msg.obj;
1106                    }
1107                    if (mContainerService == null) {
1108                        if (!mBound) {
1109                            // Something seriously wrong since we are not bound and we are not
1110                            // waiting for connection. Bail out.
1111                            Slog.e(TAG, "Cannot bind to media container service");
1112                            for (HandlerParams params : mPendingInstalls) {
1113                                // Indicate service bind error
1114                                params.serviceError();
1115                            }
1116                            mPendingInstalls.clear();
1117                        } else {
1118                            Slog.w(TAG, "Waiting to connect to media container service");
1119                        }
1120                    } else if (mPendingInstalls.size() > 0) {
1121                        HandlerParams params = mPendingInstalls.get(0);
1122                        if (params != null) {
1123                            if (params.startCopy()) {
1124                                // We are done...  look for more work or to
1125                                // go idle.
1126                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1127                                        "Checking for more work or unbind...");
1128                                // Delete pending install
1129                                if (mPendingInstalls.size() > 0) {
1130                                    mPendingInstalls.remove(0);
1131                                }
1132                                if (mPendingInstalls.size() == 0) {
1133                                    if (mBound) {
1134                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1135                                                "Posting delayed MCS_UNBIND");
1136                                        removeMessages(MCS_UNBIND);
1137                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1138                                        // Unbind after a little delay, to avoid
1139                                        // continual thrashing.
1140                                        sendMessageDelayed(ubmsg, 10000);
1141                                    }
1142                                } else {
1143                                    // There are more pending requests in queue.
1144                                    // Just post MCS_BOUND message to trigger processing
1145                                    // of next pending install.
1146                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1147                                            "Posting MCS_BOUND for next work");
1148                                    mHandler.sendEmptyMessage(MCS_BOUND);
1149                                }
1150                            }
1151                        }
1152                    } else {
1153                        // Should never happen ideally.
1154                        Slog.w(TAG, "Empty queue");
1155                    }
1156                    break;
1157                }
1158                case MCS_RECONNECT: {
1159                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1160                    if (mPendingInstalls.size() > 0) {
1161                        if (mBound) {
1162                            disconnectService();
1163                        }
1164                        if (!connectToService()) {
1165                            Slog.e(TAG, "Failed to bind to media container service");
1166                            for (HandlerParams params : mPendingInstalls) {
1167                                // Indicate service bind error
1168                                params.serviceError();
1169                            }
1170                            mPendingInstalls.clear();
1171                        }
1172                    }
1173                    break;
1174                }
1175                case MCS_UNBIND: {
1176                    // If there is no actual work left, then time to unbind.
1177                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1178
1179                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1180                        if (mBound) {
1181                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1182
1183                            disconnectService();
1184                        }
1185                    } else if (mPendingInstalls.size() > 0) {
1186                        // There are more pending requests in queue.
1187                        // Just post MCS_BOUND message to trigger processing
1188                        // of next pending install.
1189                        mHandler.sendEmptyMessage(MCS_BOUND);
1190                    }
1191
1192                    break;
1193                }
1194                case MCS_GIVE_UP: {
1195                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1196                    mPendingInstalls.remove(0);
1197                    break;
1198                }
1199                case SEND_PENDING_BROADCAST: {
1200                    String packages[];
1201                    ArrayList<String> components[];
1202                    int size = 0;
1203                    int uids[];
1204                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1205                    synchronized (mPackages) {
1206                        if (mPendingBroadcasts == null) {
1207                            return;
1208                        }
1209                        size = mPendingBroadcasts.size();
1210                        if (size <= 0) {
1211                            // Nothing to be done. Just return
1212                            return;
1213                        }
1214                        packages = new String[size];
1215                        components = new ArrayList[size];
1216                        uids = new int[size];
1217                        int i = 0;  // filling out the above arrays
1218
1219                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1220                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1221                            Iterator<Map.Entry<String, ArrayList<String>>> it
1222                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1223                                            .entrySet().iterator();
1224                            while (it.hasNext() && i < size) {
1225                                Map.Entry<String, ArrayList<String>> ent = it.next();
1226                                packages[i] = ent.getKey();
1227                                components[i] = ent.getValue();
1228                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1229                                uids[i] = (ps != null)
1230                                        ? UserHandle.getUid(packageUserId, ps.appId)
1231                                        : -1;
1232                                i++;
1233                            }
1234                        }
1235                        size = i;
1236                        mPendingBroadcasts.clear();
1237                    }
1238                    // Send broadcasts
1239                    for (int i = 0; i < size; i++) {
1240                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1241                    }
1242                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1243                    break;
1244                }
1245                case START_CLEANING_PACKAGE: {
1246                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1247                    final String packageName = (String)msg.obj;
1248                    final int userId = msg.arg1;
1249                    final boolean andCode = msg.arg2 != 0;
1250                    synchronized (mPackages) {
1251                        if (userId == UserHandle.USER_ALL) {
1252                            int[] users = sUserManager.getUserIds();
1253                            for (int user : users) {
1254                                mSettings.addPackageToCleanLPw(
1255                                        new PackageCleanItem(user, packageName, andCode));
1256                            }
1257                        } else {
1258                            mSettings.addPackageToCleanLPw(
1259                                    new PackageCleanItem(userId, packageName, andCode));
1260                        }
1261                    }
1262                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1263                    startCleaningPackages();
1264                } break;
1265                case POST_INSTALL: {
1266                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1267                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1268                    mRunningInstalls.delete(msg.arg1);
1269                    boolean deleteOld = false;
1270
1271                    if (data != null) {
1272                        InstallArgs args = data.args;
1273                        PackageInstalledInfo res = data.res;
1274
1275                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1276                            res.removedInfo.sendBroadcast(false, true, false);
1277                            Bundle extras = new Bundle(1);
1278                            extras.putInt(Intent.EXTRA_UID, res.uid);
1279
1280                            // Now that we successfully installed the package, grant runtime
1281                            // permissions if requested before broadcasting the install.
1282                            if ((args.installFlags
1283                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1284                                grantRequestedRuntimePermissions(res.pkg,
1285                                        args.user.getIdentifier());
1286                            }
1287
1288                            // Determine the set of users who are adding this
1289                            // package for the first time vs. those who are seeing
1290                            // an update.
1291                            int[] firstUsers;
1292                            int[] updateUsers = new int[0];
1293                            if (res.origUsers == null || res.origUsers.length == 0) {
1294                                firstUsers = res.newUsers;
1295                            } else {
1296                                firstUsers = new int[0];
1297                                for (int i=0; i<res.newUsers.length; i++) {
1298                                    int user = res.newUsers[i];
1299                                    boolean isNew = true;
1300                                    for (int j=0; j<res.origUsers.length; j++) {
1301                                        if (res.origUsers[j] == user) {
1302                                            isNew = false;
1303                                            break;
1304                                        }
1305                                    }
1306                                    if (isNew) {
1307                                        int[] newFirst = new int[firstUsers.length+1];
1308                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1309                                                firstUsers.length);
1310                                        newFirst[firstUsers.length] = user;
1311                                        firstUsers = newFirst;
1312                                    } else {
1313                                        int[] newUpdate = new int[updateUsers.length+1];
1314                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1315                                                updateUsers.length);
1316                                        newUpdate[updateUsers.length] = user;
1317                                        updateUsers = newUpdate;
1318                                    }
1319                                }
1320                            }
1321                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1322                                    res.pkg.applicationInfo.packageName,
1323                                    extras, null, null, firstUsers);
1324                            final boolean update = res.removedInfo.removedPackage != null;
1325                            if (update) {
1326                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1327                            }
1328                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1329                                    res.pkg.applicationInfo.packageName,
1330                                    extras, null, null, updateUsers);
1331                            if (update) {
1332                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1333                                        res.pkg.applicationInfo.packageName,
1334                                        extras, null, null, updateUsers);
1335                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1336                                        null, null,
1337                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1338
1339                                // treat asec-hosted packages like removable media on upgrade
1340                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1341                                    if (DEBUG_INSTALL) {
1342                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1343                                                + " is ASEC-hosted -> AVAILABLE");
1344                                    }
1345                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1346                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1347                                    pkgList.add(res.pkg.applicationInfo.packageName);
1348                                    sendResourcesChangedBroadcast(true, true,
1349                                            pkgList,uidArray, null);
1350                                }
1351                            }
1352                            if (res.removedInfo.args != null) {
1353                                // Remove the replaced package's older resources safely now
1354                                deleteOld = true;
1355                            }
1356
1357                            // Log current value of "unknown sources" setting
1358                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1359                                getUnknownSourcesSettings());
1360                        }
1361                        // Force a gc to clear up things
1362                        Runtime.getRuntime().gc();
1363                        // We delete after a gc for applications  on sdcard.
1364                        if (deleteOld) {
1365                            synchronized (mInstallLock) {
1366                                res.removedInfo.args.doPostDeleteLI(true);
1367                            }
1368                        }
1369                        if (args.observer != null) {
1370                            try {
1371                                Bundle extras = extrasForInstallResult(res);
1372                                args.observer.onPackageInstalled(res.name, res.returnCode,
1373                                        res.returnMsg, extras);
1374                            } catch (RemoteException e) {
1375                                Slog.i(TAG, "Observer no longer exists.");
1376                            }
1377                        }
1378                    } else {
1379                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1380                    }
1381                } break;
1382                case UPDATED_MEDIA_STATUS: {
1383                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1384                    boolean reportStatus = msg.arg1 == 1;
1385                    boolean doGc = msg.arg2 == 1;
1386                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1387                    if (doGc) {
1388                        // Force a gc to clear up stale containers.
1389                        Runtime.getRuntime().gc();
1390                    }
1391                    if (msg.obj != null) {
1392                        @SuppressWarnings("unchecked")
1393                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1394                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1395                        // Unload containers
1396                        unloadAllContainers(args);
1397                    }
1398                    if (reportStatus) {
1399                        try {
1400                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1401                            PackageHelper.getMountService().finishMediaUpdate();
1402                        } catch (RemoteException e) {
1403                            Log.e(TAG, "MountService not running?");
1404                        }
1405                    }
1406                } break;
1407                case WRITE_SETTINGS: {
1408                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1409                    synchronized (mPackages) {
1410                        removeMessages(WRITE_SETTINGS);
1411                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1412                        mSettings.writeLPr();
1413                        mDirtyUsers.clear();
1414                    }
1415                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1416                } break;
1417                case WRITE_PACKAGE_RESTRICTIONS: {
1418                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1419                    synchronized (mPackages) {
1420                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1421                        for (int userId : mDirtyUsers) {
1422                            mSettings.writePackageRestrictionsLPr(userId);
1423                        }
1424                        mDirtyUsers.clear();
1425                    }
1426                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1427                } break;
1428                case CHECK_PENDING_VERIFICATION: {
1429                    final int verificationId = msg.arg1;
1430                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1431
1432                    if ((state != null) && !state.timeoutExtended()) {
1433                        final InstallArgs args = state.getInstallArgs();
1434                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1435
1436                        Slog.i(TAG, "Verification timed out for " + originUri);
1437                        mPendingVerification.remove(verificationId);
1438
1439                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1440
1441                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1442                            Slog.i(TAG, "Continuing with installation of " + originUri);
1443                            state.setVerifierResponse(Binder.getCallingUid(),
1444                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1445                            broadcastPackageVerified(verificationId, originUri,
1446                                    PackageManager.VERIFICATION_ALLOW,
1447                                    state.getInstallArgs().getUser());
1448                            try {
1449                                ret = args.copyApk(mContainerService, true);
1450                            } catch (RemoteException e) {
1451                                Slog.e(TAG, "Could not contact the ContainerService");
1452                            }
1453                        } else {
1454                            broadcastPackageVerified(verificationId, originUri,
1455                                    PackageManager.VERIFICATION_REJECT,
1456                                    state.getInstallArgs().getUser());
1457                        }
1458
1459                        processPendingInstall(args, ret);
1460                        mHandler.sendEmptyMessage(MCS_UNBIND);
1461                    }
1462                    break;
1463                }
1464                case PACKAGE_VERIFIED: {
1465                    final int verificationId = msg.arg1;
1466
1467                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1468                    if (state == null) {
1469                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1470                        break;
1471                    }
1472
1473                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1474
1475                    state.setVerifierResponse(response.callerUid, response.code);
1476
1477                    if (state.isVerificationComplete()) {
1478                        mPendingVerification.remove(verificationId);
1479
1480                        final InstallArgs args = state.getInstallArgs();
1481                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1482
1483                        int ret;
1484                        if (state.isInstallAllowed()) {
1485                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1486                            broadcastPackageVerified(verificationId, originUri,
1487                                    response.code, state.getInstallArgs().getUser());
1488                            try {
1489                                ret = args.copyApk(mContainerService, true);
1490                            } catch (RemoteException e) {
1491                                Slog.e(TAG, "Could not contact the ContainerService");
1492                            }
1493                        } else {
1494                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1495                        }
1496
1497                        processPendingInstall(args, ret);
1498
1499                        mHandler.sendEmptyMessage(MCS_UNBIND);
1500                    }
1501
1502                    break;
1503                }
1504                case START_INTENT_FILTER_VERIFICATIONS: {
1505                    int userId = msg.arg1;
1506                    int verifierUid = msg.arg2;
1507                    PackageParser.Package pkg = (PackageParser.Package)msg.obj;
1508
1509                    verifyIntentFiltersIfNeeded(userId, verifierUid, pkg);
1510                    break;
1511                }
1512                case INTENT_FILTER_VERIFIED: {
1513                    final int verificationId = msg.arg1;
1514
1515                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1516                            verificationId);
1517                    if (state == null) {
1518                        Slog.w(TAG, "Invalid IntentFilter verification token "
1519                                + verificationId + " received");
1520                        break;
1521                    }
1522
1523                    final int userId = state.getUserId();
1524
1525                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1526                            "Processing IntentFilter verification with token:"
1527                            + verificationId + " and userId:" + userId);
1528
1529                    final IntentFilterVerificationResponse response =
1530                            (IntentFilterVerificationResponse) msg.obj;
1531
1532                    state.setVerifierResponse(response.callerUid, response.code);
1533
1534                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1535                            "IntentFilter verification with token:" + verificationId
1536                            + " and userId:" + userId
1537                            + " is settings verifier response with response code:"
1538                            + response.code);
1539
1540                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1541                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1542                                + response.getFailedDomainsString());
1543                    }
1544
1545                    if (state.isVerificationComplete()) {
1546                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1547                    } else {
1548                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1549                                "IntentFilter verification with token:" + verificationId
1550                                + " was not said to be complete");
1551                    }
1552
1553                    break;
1554                }
1555            }
1556        }
1557    }
1558
1559    private StorageEventListener mStorageListener = new StorageEventListener() {
1560        @Override
1561        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1562            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1563                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1564                    // TODO: ensure that private directories exist for all active users
1565                    // TODO: remove user data whose serial number doesn't match
1566                    loadPrivatePackages(vol);
1567                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1568                    unloadPrivatePackages(vol);
1569                }
1570            }
1571
1572            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1573                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1574                    updateExternalMediaStatus(true, false);
1575                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1576                    updateExternalMediaStatus(false, false);
1577                }
1578            }
1579        }
1580
1581        @Override
1582        public void onVolumeForgotten(String fsUuid) {
1583            // TODO: remove all packages hosted on this uuid
1584        }
1585    };
1586
1587    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1588        if (userId >= UserHandle.USER_OWNER) {
1589            grantRequestedRuntimePermissionsForUser(pkg, userId);
1590        } else if (userId == UserHandle.USER_ALL) {
1591            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1592                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1593            }
1594        }
1595    }
1596
1597    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1598        SettingBase sb = (SettingBase) pkg.mExtras;
1599        if (sb == null) {
1600            return;
1601        }
1602
1603        PermissionsState permissionsState = sb.getPermissionsState();
1604
1605        for (String permission : pkg.requestedPermissions) {
1606            BasePermission bp = mSettings.mPermissions.get(permission);
1607            if (bp != null && bp.isRuntime()) {
1608                permissionsState.grantRuntimePermission(bp, userId);
1609            }
1610        }
1611    }
1612
1613    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1614        Bundle extras = null;
1615        switch (res.returnCode) {
1616            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1617                extras = new Bundle();
1618                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1619                        res.origPermission);
1620                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1621                        res.origPackage);
1622                break;
1623            }
1624            case PackageManager.INSTALL_SUCCEEDED: {
1625                extras = new Bundle();
1626                extras.putBoolean(Intent.EXTRA_REPLACING,
1627                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1628                break;
1629            }
1630        }
1631        return extras;
1632    }
1633
1634    void scheduleWriteSettingsLocked() {
1635        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1636            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1637        }
1638    }
1639
1640    void scheduleWritePackageRestrictionsLocked(int userId) {
1641        if (!sUserManager.exists(userId)) return;
1642        mDirtyUsers.add(userId);
1643        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1644            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1645        }
1646    }
1647
1648    public static PackageManagerService main(Context context, Installer installer,
1649            boolean factoryTest, boolean onlyCore) {
1650        PackageManagerService m = new PackageManagerService(context, installer,
1651                factoryTest, onlyCore);
1652        ServiceManager.addService("package", m);
1653        return m;
1654    }
1655
1656    static String[] splitString(String str, char sep) {
1657        int count = 1;
1658        int i = 0;
1659        while ((i=str.indexOf(sep, i)) >= 0) {
1660            count++;
1661            i++;
1662        }
1663
1664        String[] res = new String[count];
1665        i=0;
1666        count = 0;
1667        int lastI=0;
1668        while ((i=str.indexOf(sep, i)) >= 0) {
1669            res[count] = str.substring(lastI, i);
1670            count++;
1671            i++;
1672            lastI = i;
1673        }
1674        res[count] = str.substring(lastI, str.length());
1675        return res;
1676    }
1677
1678    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1679        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1680                Context.DISPLAY_SERVICE);
1681        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1682    }
1683
1684    public PackageManagerService(Context context, Installer installer,
1685            boolean factoryTest, boolean onlyCore) {
1686        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1687                SystemClock.uptimeMillis());
1688
1689        if (mSdkVersion <= 0) {
1690            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1691        }
1692
1693        mContext = context;
1694        mFactoryTest = factoryTest;
1695        mOnlyCore = onlyCore;
1696        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1697        mMetrics = new DisplayMetrics();
1698        mSettings = new Settings(mPackages);
1699        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1700                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1701        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1702                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1703        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1704                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1705        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1706                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1707        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1708                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1709        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1710                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1711
1712        // TODO: add a property to control this?
1713        long dexOptLRUThresholdInMinutes;
1714        if (mLazyDexOpt) {
1715            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1716        } else {
1717            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1718        }
1719        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1720
1721        String separateProcesses = SystemProperties.get("debug.separate_processes");
1722        if (separateProcesses != null && separateProcesses.length() > 0) {
1723            if ("*".equals(separateProcesses)) {
1724                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1725                mSeparateProcesses = null;
1726                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1727            } else {
1728                mDefParseFlags = 0;
1729                mSeparateProcesses = separateProcesses.split(",");
1730                Slog.w(TAG, "Running with debug.separate_processes: "
1731                        + separateProcesses);
1732            }
1733        } else {
1734            mDefParseFlags = 0;
1735            mSeparateProcesses = null;
1736        }
1737
1738        mInstaller = installer;
1739        mPackageDexOptimizer = new PackageDexOptimizer(this);
1740        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1741
1742        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1743                FgThread.get().getLooper());
1744
1745        getDefaultDisplayMetrics(context, mMetrics);
1746
1747        SystemConfig systemConfig = SystemConfig.getInstance();
1748        mGlobalGids = systemConfig.getGlobalGids();
1749        mSystemPermissions = systemConfig.getSystemPermissions();
1750        mAvailableFeatures = systemConfig.getAvailableFeatures();
1751
1752        synchronized (mInstallLock) {
1753        // writer
1754        synchronized (mPackages) {
1755            mHandlerThread = new ServiceThread(TAG,
1756                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1757            mHandlerThread.start();
1758            mHandler = new PackageHandler(mHandlerThread.getLooper());
1759            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1760
1761            File dataDir = Environment.getDataDirectory();
1762            mAppDataDir = new File(dataDir, "data");
1763            mAppInstallDir = new File(dataDir, "app");
1764            mAppLib32InstallDir = new File(dataDir, "app-lib");
1765            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1766            mUserAppDataDir = new File(dataDir, "user");
1767            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1768
1769            sUserManager = new UserManagerService(context, this,
1770                    mInstallLock, mPackages);
1771
1772            // Propagate permission configuration in to package manager.
1773            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1774                    = systemConfig.getPermissions();
1775            for (int i=0; i<permConfig.size(); i++) {
1776                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1777                BasePermission bp = mSettings.mPermissions.get(perm.name);
1778                if (bp == null) {
1779                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1780                    mSettings.mPermissions.put(perm.name, bp);
1781                }
1782                if (perm.gids != null) {
1783                    bp.setGids(perm.gids, perm.perUser);
1784                }
1785            }
1786
1787            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1788            for (int i=0; i<libConfig.size(); i++) {
1789                mSharedLibraries.put(libConfig.keyAt(i),
1790                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1791            }
1792
1793            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1794
1795            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1796                    mSdkVersion, mOnlyCore);
1797
1798            String customResolverActivity = Resources.getSystem().getString(
1799                    R.string.config_customResolverActivity);
1800            if (TextUtils.isEmpty(customResolverActivity)) {
1801                customResolverActivity = null;
1802            } else {
1803                mCustomResolverComponentName = ComponentName.unflattenFromString(
1804                        customResolverActivity);
1805            }
1806
1807            long startTime = SystemClock.uptimeMillis();
1808
1809            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1810                    startTime);
1811
1812            // Set flag to monitor and not change apk file paths when
1813            // scanning install directories.
1814            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1815
1816            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1817
1818            /**
1819             * Add everything in the in the boot class path to the
1820             * list of process files because dexopt will have been run
1821             * if necessary during zygote startup.
1822             */
1823            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1824            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1825
1826            if (bootClassPath != null) {
1827                String[] bootClassPathElements = splitString(bootClassPath, ':');
1828                for (String element : bootClassPathElements) {
1829                    alreadyDexOpted.add(element);
1830                }
1831            } else {
1832                Slog.w(TAG, "No BOOTCLASSPATH found!");
1833            }
1834
1835            if (systemServerClassPath != null) {
1836                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1837                for (String element : systemServerClassPathElements) {
1838                    alreadyDexOpted.add(element);
1839                }
1840            } else {
1841                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1842            }
1843
1844            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1845            final String[] dexCodeInstructionSets =
1846                    getDexCodeInstructionSets(
1847                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1848
1849            /**
1850             * Ensure all external libraries have had dexopt run on them.
1851             */
1852            if (mSharedLibraries.size() > 0) {
1853                // NOTE: For now, we're compiling these system "shared libraries"
1854                // (and framework jars) into all available architectures. It's possible
1855                // to compile them only when we come across an app that uses them (there's
1856                // already logic for that in scanPackageLI) but that adds some complexity.
1857                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1858                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1859                        final String lib = libEntry.path;
1860                        if (lib == null) {
1861                            continue;
1862                        }
1863
1864                        try {
1865                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1866                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1867                                alreadyDexOpted.add(lib);
1868                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1869                            }
1870                        } catch (FileNotFoundException e) {
1871                            Slog.w(TAG, "Library not found: " + lib);
1872                        } catch (IOException e) {
1873                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1874                                    + e.getMessage());
1875                        }
1876                    }
1877                }
1878            }
1879
1880            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1881
1882            // Gross hack for now: we know this file doesn't contain any
1883            // code, so don't dexopt it to avoid the resulting log spew.
1884            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1885
1886            // Gross hack for now: we know this file is only part of
1887            // the boot class path for art, so don't dexopt it to
1888            // avoid the resulting log spew.
1889            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1890
1891            /**
1892             * There are a number of commands implemented in Java, which
1893             * we currently need to do the dexopt on so that they can be
1894             * run from a non-root shell.
1895             */
1896            String[] frameworkFiles = frameworkDir.list();
1897            if (frameworkFiles != null) {
1898                // TODO: We could compile these only for the most preferred ABI. We should
1899                // first double check that the dex files for these commands are not referenced
1900                // by other system apps.
1901                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1902                    for (int i=0; i<frameworkFiles.length; i++) {
1903                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1904                        String path = libPath.getPath();
1905                        // Skip the file if we already did it.
1906                        if (alreadyDexOpted.contains(path)) {
1907                            continue;
1908                        }
1909                        // Skip the file if it is not a type we want to dexopt.
1910                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1911                            continue;
1912                        }
1913                        try {
1914                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1915                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1916                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1917                            }
1918                        } catch (FileNotFoundException e) {
1919                            Slog.w(TAG, "Jar not found: " + path);
1920                        } catch (IOException e) {
1921                            Slog.w(TAG, "Exception reading jar: " + path, e);
1922                        }
1923                    }
1924                }
1925            }
1926
1927            // Collect vendor overlay packages.
1928            // (Do this before scanning any apps.)
1929            // For security and version matching reason, only consider
1930            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1931            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1932            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1933                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1934
1935            // Find base frameworks (resource packages without code).
1936            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1937                    | PackageParser.PARSE_IS_SYSTEM_DIR
1938                    | PackageParser.PARSE_IS_PRIVILEGED,
1939                    scanFlags | SCAN_NO_DEX, 0);
1940
1941            // Collected privileged system packages.
1942            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1943            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1944                    | PackageParser.PARSE_IS_SYSTEM_DIR
1945                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1946
1947            // Collect ordinary system packages.
1948            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1949            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1950                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1951
1952            // Collect all vendor packages.
1953            File vendorAppDir = new File("/vendor/app");
1954            try {
1955                vendorAppDir = vendorAppDir.getCanonicalFile();
1956            } catch (IOException e) {
1957                // failed to look up canonical path, continue with original one
1958            }
1959            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1960                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1961
1962            // Collect all OEM packages.
1963            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1964            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1965                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1966
1967            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1968            mInstaller.moveFiles();
1969
1970            // Prune any system packages that no longer exist.
1971            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1972            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1973            if (!mOnlyCore) {
1974                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1975                while (psit.hasNext()) {
1976                    PackageSetting ps = psit.next();
1977
1978                    /*
1979                     * If this is not a system app, it can't be a
1980                     * disable system app.
1981                     */
1982                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1983                        continue;
1984                    }
1985
1986                    /*
1987                     * If the package is scanned, it's not erased.
1988                     */
1989                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1990                    if (scannedPkg != null) {
1991                        /*
1992                         * If the system app is both scanned and in the
1993                         * disabled packages list, then it must have been
1994                         * added via OTA. Remove it from the currently
1995                         * scanned package so the previously user-installed
1996                         * application can be scanned.
1997                         */
1998                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1999                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2000                                    + ps.name + "; removing system app.  Last known codePath="
2001                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2002                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2003                                    + scannedPkg.mVersionCode);
2004                            removePackageLI(ps, true);
2005                            expectingBetter.put(ps.name, ps.codePath);
2006                        }
2007
2008                        continue;
2009                    }
2010
2011                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2012                        psit.remove();
2013                        logCriticalInfo(Log.WARN, "System package " + ps.name
2014                                + " no longer exists; wiping its data");
2015                        removeDataDirsLI(null, ps.name);
2016                    } else {
2017                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2018                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2019                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2020                        }
2021                    }
2022                }
2023            }
2024
2025            //look for any incomplete package installations
2026            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2027            //clean up list
2028            for(int i = 0; i < deletePkgsList.size(); i++) {
2029                //clean up here
2030                cleanupInstallFailedPackage(deletePkgsList.get(i));
2031            }
2032            //delete tmp files
2033            deleteTempPackageFiles();
2034
2035            // Remove any shared userIDs that have no associated packages
2036            mSettings.pruneSharedUsersLPw();
2037
2038            if (!mOnlyCore) {
2039                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2040                        SystemClock.uptimeMillis());
2041                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2042
2043                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2044                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2045
2046                /**
2047                 * Remove disable package settings for any updated system
2048                 * apps that were removed via an OTA. If they're not a
2049                 * previously-updated app, remove them completely.
2050                 * Otherwise, just revoke their system-level permissions.
2051                 */
2052                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2053                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2054                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2055
2056                    String msg;
2057                    if (deletedPkg == null) {
2058                        msg = "Updated system package " + deletedAppName
2059                                + " no longer exists; wiping its data";
2060                        removeDataDirsLI(null, deletedAppName);
2061                    } else {
2062                        msg = "Updated system app + " + deletedAppName
2063                                + " no longer present; removing system privileges for "
2064                                + deletedAppName;
2065
2066                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2067
2068                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2069                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2070                    }
2071                    logCriticalInfo(Log.WARN, msg);
2072                }
2073
2074                /**
2075                 * Make sure all system apps that we expected to appear on
2076                 * the userdata partition actually showed up. If they never
2077                 * appeared, crawl back and revive the system version.
2078                 */
2079                for (int i = 0; i < expectingBetter.size(); i++) {
2080                    final String packageName = expectingBetter.keyAt(i);
2081                    if (!mPackages.containsKey(packageName)) {
2082                        final File scanFile = expectingBetter.valueAt(i);
2083
2084                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2085                                + " but never showed up; reverting to system");
2086
2087                        final int reparseFlags;
2088                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2089                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2090                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2091                                    | PackageParser.PARSE_IS_PRIVILEGED;
2092                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2093                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2094                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2095                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2096                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2097                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2098                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2099                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2100                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2101                        } else {
2102                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2103                            continue;
2104                        }
2105
2106                        mSettings.enableSystemPackageLPw(packageName);
2107
2108                        try {
2109                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2110                        } catch (PackageManagerException e) {
2111                            Slog.e(TAG, "Failed to parse original system package: "
2112                                    + e.getMessage());
2113                        }
2114                    }
2115                }
2116            }
2117
2118            // Now that we know all of the shared libraries, update all clients to have
2119            // the correct library paths.
2120            updateAllSharedLibrariesLPw();
2121
2122            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2123                // NOTE: We ignore potential failures here during a system scan (like
2124                // the rest of the commands above) because there's precious little we
2125                // can do about it. A settings error is reported, though.
2126                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2127                        false /* force dexopt */, false /* defer dexopt */);
2128            }
2129
2130            // Now that we know all the packages we are keeping,
2131            // read and update their last usage times.
2132            mPackageUsage.readLP();
2133
2134            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2135                    SystemClock.uptimeMillis());
2136            Slog.i(TAG, "Time to scan packages: "
2137                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2138                    + " seconds");
2139
2140            // If the platform SDK has changed since the last time we booted,
2141            // we need to re-grant app permission to catch any new ones that
2142            // appear.  This is really a hack, and means that apps can in some
2143            // cases get permissions that the user didn't initially explicitly
2144            // allow...  it would be nice to have some better way to handle
2145            // this situation.
2146            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2147                    != mSdkVersion;
2148            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2149                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2150                    + "; regranting permissions for internal storage");
2151            mSettings.mInternalSdkPlatform = mSdkVersion;
2152
2153            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2154                    | (regrantPermissions
2155                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2156                            : 0));
2157
2158            // If this is the first boot, and it is a normal boot, then
2159            // we need to initialize the default preferred apps.
2160            if (!mRestoredSettings && !onlyCore) {
2161                mSettings.readDefaultPreferredAppsLPw(this, 0);
2162            }
2163
2164            // If this is first boot after an OTA, and a normal boot, then
2165            // we need to clear code cache directories.
2166            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2167            if (mIsUpgrade && !onlyCore) {
2168                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2169                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2170                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2171                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2172                }
2173                mSettings.mFingerprint = Build.FINGERPRINT;
2174            }
2175
2176            primeDomainVerificationsLPw();
2177            checkDefaultBrowser();
2178
2179            // All the changes are done during package scanning.
2180            mSettings.updateInternalDatabaseVersion();
2181
2182            // can downgrade to reader
2183            mSettings.writeLPr();
2184
2185            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2186                    SystemClock.uptimeMillis());
2187
2188            mRequiredVerifierPackage = getRequiredVerifierLPr();
2189
2190            mInstallerService = new PackageInstallerService(context, this);
2191
2192            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2193            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2194                    mIntentFilterVerifierComponent);
2195
2196        } // synchronized (mPackages)
2197        } // synchronized (mInstallLock)
2198
2199        // Now after opening every single application zip, make sure they
2200        // are all flushed.  Not really needed, but keeps things nice and
2201        // tidy.
2202        Runtime.getRuntime().gc();
2203    }
2204
2205    @Override
2206    public boolean isFirstBoot() {
2207        return !mRestoredSettings;
2208    }
2209
2210    @Override
2211    public boolean isOnlyCoreApps() {
2212        return mOnlyCore;
2213    }
2214
2215    @Override
2216    public boolean isUpgrade() {
2217        return mIsUpgrade;
2218    }
2219
2220    private String getRequiredVerifierLPr() {
2221        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2222        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2223                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2224
2225        String requiredVerifier = null;
2226
2227        final int N = receivers.size();
2228        for (int i = 0; i < N; i++) {
2229            final ResolveInfo info = receivers.get(i);
2230
2231            if (info.activityInfo == null) {
2232                continue;
2233            }
2234
2235            final String packageName = info.activityInfo.packageName;
2236
2237            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2238                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2239                continue;
2240            }
2241
2242            if (requiredVerifier != null) {
2243                throw new RuntimeException("There can be only one required verifier");
2244            }
2245
2246            requiredVerifier = packageName;
2247        }
2248
2249        return requiredVerifier;
2250    }
2251
2252    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2253        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2254        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2255                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2256
2257        ComponentName verifierComponentName = null;
2258
2259        int priority = -1000;
2260        final int N = receivers.size();
2261        for (int i = 0; i < N; i++) {
2262            final ResolveInfo info = receivers.get(i);
2263
2264            if (info.activityInfo == null) {
2265                continue;
2266            }
2267
2268            final String packageName = info.activityInfo.packageName;
2269
2270            final PackageSetting ps = mSettings.mPackages.get(packageName);
2271            if (ps == null) {
2272                continue;
2273            }
2274
2275            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2276                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2277                continue;
2278            }
2279
2280            // Select the IntentFilterVerifier with the highest priority
2281            if (priority < info.priority) {
2282                priority = info.priority;
2283                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2284                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2285                        + verifierComponentName + " with priority: " + info.priority);
2286            }
2287        }
2288
2289        return verifierComponentName;
2290    }
2291
2292    private void primeDomainVerificationsLPw() {
2293        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2294        boolean updated = false;
2295        ArraySet<String> allHostsSet = new ArraySet<>();
2296        for (PackageParser.Package pkg : mPackages.values()) {
2297            final String packageName = pkg.packageName;
2298            if (!hasDomainURLs(pkg)) {
2299                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2300                            "package with no domain URLs: " + packageName);
2301                continue;
2302            }
2303            if (!pkg.isSystemApp()) {
2304                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2305                        "No priming domain verifications for a non system package : " +
2306                                packageName);
2307                continue;
2308            }
2309            for (PackageParser.Activity a : pkg.activities) {
2310                for (ActivityIntentInfo filter : a.intents) {
2311                    if (hasValidDomains(filter)) {
2312                        allHostsSet.addAll(filter.getHostsList());
2313                    }
2314                }
2315            }
2316            if (allHostsSet.size() == 0) {
2317                allHostsSet.add("*");
2318            }
2319            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2320            IntentFilterVerificationInfo ivi =
2321                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2322            if (ivi != null) {
2323                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2324                        "Priming domain verifications for package: " + packageName +
2325                        " with hosts:" + ivi.getDomainsString());
2326                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2327                updated = true;
2328            }
2329            else {
2330                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2331                        "No priming domain verifications for package: " + packageName);
2332            }
2333            allHostsSet.clear();
2334        }
2335        if (updated) {
2336            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2337                    "Will need to write primed domain verifications");
2338        }
2339        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2340    }
2341
2342    private void checkDefaultBrowser() {
2343        final int myUserId = UserHandle.myUserId();
2344        final String packageName = getDefaultBrowserPackageName(myUserId);
2345        PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2346        if (info == null) {
2347            Slog.w(TAG, "Clearing default Browser as its package is no more installed: " +
2348                    packageName);
2349            setDefaultBrowserPackageName(null, myUserId);
2350        }
2351    }
2352
2353    @Override
2354    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2355            throws RemoteException {
2356        try {
2357            return super.onTransact(code, data, reply, flags);
2358        } catch (RuntimeException e) {
2359            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2360                Slog.wtf(TAG, "Package Manager Crash", e);
2361            }
2362            throw e;
2363        }
2364    }
2365
2366    void cleanupInstallFailedPackage(PackageSetting ps) {
2367        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2368
2369        removeDataDirsLI(ps.volumeUuid, ps.name);
2370        if (ps.codePath != null) {
2371            if (ps.codePath.isDirectory()) {
2372                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2373            } else {
2374                ps.codePath.delete();
2375            }
2376        }
2377        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2378            if (ps.resourcePath.isDirectory()) {
2379                FileUtils.deleteContents(ps.resourcePath);
2380            }
2381            ps.resourcePath.delete();
2382        }
2383        mSettings.removePackageLPw(ps.name);
2384    }
2385
2386    static int[] appendInts(int[] cur, int[] add) {
2387        if (add == null) return cur;
2388        if (cur == null) return add;
2389        final int N = add.length;
2390        for (int i=0; i<N; i++) {
2391            cur = appendInt(cur, add[i]);
2392        }
2393        return cur;
2394    }
2395
2396    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2397        if (!sUserManager.exists(userId)) return null;
2398        final PackageSetting ps = (PackageSetting) p.mExtras;
2399        if (ps == null) {
2400            return null;
2401        }
2402
2403        final PermissionsState permissionsState = ps.getPermissionsState();
2404
2405        final int[] gids = permissionsState.computeGids(userId);
2406        final Set<String> permissions = permissionsState.getPermissions(userId);
2407        final PackageUserState state = ps.readUserState(userId);
2408
2409        return PackageParser.generatePackageInfo(p, gids, flags,
2410                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2411    }
2412
2413    @Override
2414    public boolean isPackageFrozen(String packageName) {
2415        synchronized (mPackages) {
2416            final PackageSetting ps = mSettings.mPackages.get(packageName);
2417            if (ps != null) {
2418                return ps.frozen;
2419            }
2420        }
2421        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2422        return true;
2423    }
2424
2425    @Override
2426    public boolean isPackageAvailable(String packageName, int userId) {
2427        if (!sUserManager.exists(userId)) return false;
2428        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2429        synchronized (mPackages) {
2430            PackageParser.Package p = mPackages.get(packageName);
2431            if (p != null) {
2432                final PackageSetting ps = (PackageSetting) p.mExtras;
2433                if (ps != null) {
2434                    final PackageUserState state = ps.readUserState(userId);
2435                    if (state != null) {
2436                        return PackageParser.isAvailable(state);
2437                    }
2438                }
2439            }
2440        }
2441        return false;
2442    }
2443
2444    @Override
2445    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2446        if (!sUserManager.exists(userId)) return null;
2447        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2448        // reader
2449        synchronized (mPackages) {
2450            PackageParser.Package p = mPackages.get(packageName);
2451            if (DEBUG_PACKAGE_INFO)
2452                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2453            if (p != null) {
2454                return generatePackageInfo(p, flags, userId);
2455            }
2456            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2457                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2458            }
2459        }
2460        return null;
2461    }
2462
2463    @Override
2464    public String[] currentToCanonicalPackageNames(String[] names) {
2465        String[] out = new String[names.length];
2466        // reader
2467        synchronized (mPackages) {
2468            for (int i=names.length-1; i>=0; i--) {
2469                PackageSetting ps = mSettings.mPackages.get(names[i]);
2470                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2471            }
2472        }
2473        return out;
2474    }
2475
2476    @Override
2477    public String[] canonicalToCurrentPackageNames(String[] names) {
2478        String[] out = new String[names.length];
2479        // reader
2480        synchronized (mPackages) {
2481            for (int i=names.length-1; i>=0; i--) {
2482                String cur = mSettings.mRenamedPackages.get(names[i]);
2483                out[i] = cur != null ? cur : names[i];
2484            }
2485        }
2486        return out;
2487    }
2488
2489    @Override
2490    public int getPackageUid(String packageName, int userId) {
2491        if (!sUserManager.exists(userId)) return -1;
2492        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2493
2494        // reader
2495        synchronized (mPackages) {
2496            PackageParser.Package p = mPackages.get(packageName);
2497            if(p != null) {
2498                return UserHandle.getUid(userId, p.applicationInfo.uid);
2499            }
2500            PackageSetting ps = mSettings.mPackages.get(packageName);
2501            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2502                return -1;
2503            }
2504            p = ps.pkg;
2505            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2506        }
2507    }
2508
2509    @Override
2510    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2511        if (!sUserManager.exists(userId)) {
2512            return null;
2513        }
2514
2515        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2516                "getPackageGids");
2517
2518        // reader
2519        synchronized (mPackages) {
2520            PackageParser.Package p = mPackages.get(packageName);
2521            if (DEBUG_PACKAGE_INFO) {
2522                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2523            }
2524            if (p != null) {
2525                PackageSetting ps = (PackageSetting) p.mExtras;
2526                return ps.getPermissionsState().computeGids(userId);
2527            }
2528        }
2529
2530        return null;
2531    }
2532
2533    static PermissionInfo generatePermissionInfo(
2534            BasePermission bp, int flags) {
2535        if (bp.perm != null) {
2536            return PackageParser.generatePermissionInfo(bp.perm, flags);
2537        }
2538        PermissionInfo pi = new PermissionInfo();
2539        pi.name = bp.name;
2540        pi.packageName = bp.sourcePackage;
2541        pi.nonLocalizedLabel = bp.name;
2542        pi.protectionLevel = bp.protectionLevel;
2543        return pi;
2544    }
2545
2546    @Override
2547    public PermissionInfo getPermissionInfo(String name, int flags) {
2548        // reader
2549        synchronized (mPackages) {
2550            final BasePermission p = mSettings.mPermissions.get(name);
2551            if (p != null) {
2552                return generatePermissionInfo(p, flags);
2553            }
2554            return null;
2555        }
2556    }
2557
2558    @Override
2559    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2560        // reader
2561        synchronized (mPackages) {
2562            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2563            for (BasePermission p : mSettings.mPermissions.values()) {
2564                if (group == null) {
2565                    if (p.perm == null || p.perm.info.group == null) {
2566                        out.add(generatePermissionInfo(p, flags));
2567                    }
2568                } else {
2569                    if (p.perm != null && group.equals(p.perm.info.group)) {
2570                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2571                    }
2572                }
2573            }
2574
2575            if (out.size() > 0) {
2576                return out;
2577            }
2578            return mPermissionGroups.containsKey(group) ? out : null;
2579        }
2580    }
2581
2582    @Override
2583    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2584        // reader
2585        synchronized (mPackages) {
2586            return PackageParser.generatePermissionGroupInfo(
2587                    mPermissionGroups.get(name), flags);
2588        }
2589    }
2590
2591    @Override
2592    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2593        // reader
2594        synchronized (mPackages) {
2595            final int N = mPermissionGroups.size();
2596            ArrayList<PermissionGroupInfo> out
2597                    = new ArrayList<PermissionGroupInfo>(N);
2598            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2599                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2600            }
2601            return out;
2602        }
2603    }
2604
2605    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2606            int userId) {
2607        if (!sUserManager.exists(userId)) return null;
2608        PackageSetting ps = mSettings.mPackages.get(packageName);
2609        if (ps != null) {
2610            if (ps.pkg == null) {
2611                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2612                        flags, userId);
2613                if (pInfo != null) {
2614                    return pInfo.applicationInfo;
2615                }
2616                return null;
2617            }
2618            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2619                    ps.readUserState(userId), userId);
2620        }
2621        return null;
2622    }
2623
2624    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2625            int userId) {
2626        if (!sUserManager.exists(userId)) return null;
2627        PackageSetting ps = mSettings.mPackages.get(packageName);
2628        if (ps != null) {
2629            PackageParser.Package pkg = ps.pkg;
2630            if (pkg == null) {
2631                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2632                    return null;
2633                }
2634                // Only data remains, so we aren't worried about code paths
2635                pkg = new PackageParser.Package(packageName);
2636                pkg.applicationInfo.packageName = packageName;
2637                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2638                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2639                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2640                        packageName, userId).getAbsolutePath();
2641                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2642                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2643            }
2644            return generatePackageInfo(pkg, flags, userId);
2645        }
2646        return null;
2647    }
2648
2649    @Override
2650    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2651        if (!sUserManager.exists(userId)) return null;
2652        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2653        // writer
2654        synchronized (mPackages) {
2655            PackageParser.Package p = mPackages.get(packageName);
2656            if (DEBUG_PACKAGE_INFO) Log.v(
2657                    TAG, "getApplicationInfo " + packageName
2658                    + ": " + p);
2659            if (p != null) {
2660                PackageSetting ps = mSettings.mPackages.get(packageName);
2661                if (ps == null) return null;
2662                // Note: isEnabledLP() does not apply here - always return info
2663                return PackageParser.generateApplicationInfo(
2664                        p, flags, ps.readUserState(userId), userId);
2665            }
2666            if ("android".equals(packageName)||"system".equals(packageName)) {
2667                return mAndroidApplication;
2668            }
2669            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2670                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2671            }
2672        }
2673        return null;
2674    }
2675
2676    @Override
2677    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2678            final IPackageDataObserver observer) {
2679        mContext.enforceCallingOrSelfPermission(
2680                android.Manifest.permission.CLEAR_APP_CACHE, null);
2681        // Queue up an async operation since clearing cache may take a little while.
2682        mHandler.post(new Runnable() {
2683            public void run() {
2684                mHandler.removeCallbacks(this);
2685                int retCode = -1;
2686                synchronized (mInstallLock) {
2687                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2688                    if (retCode < 0) {
2689                        Slog.w(TAG, "Couldn't clear application caches");
2690                    }
2691                }
2692                if (observer != null) {
2693                    try {
2694                        observer.onRemoveCompleted(null, (retCode >= 0));
2695                    } catch (RemoteException e) {
2696                        Slog.w(TAG, "RemoveException when invoking call back");
2697                    }
2698                }
2699            }
2700        });
2701    }
2702
2703    @Override
2704    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2705            final IntentSender pi) {
2706        mContext.enforceCallingOrSelfPermission(
2707                android.Manifest.permission.CLEAR_APP_CACHE, null);
2708        // Queue up an async operation since clearing cache may take a little while.
2709        mHandler.post(new Runnable() {
2710            public void run() {
2711                mHandler.removeCallbacks(this);
2712                int retCode = -1;
2713                synchronized (mInstallLock) {
2714                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2715                    if (retCode < 0) {
2716                        Slog.w(TAG, "Couldn't clear application caches");
2717                    }
2718                }
2719                if(pi != null) {
2720                    try {
2721                        // Callback via pending intent
2722                        int code = (retCode >= 0) ? 1 : 0;
2723                        pi.sendIntent(null, code, null,
2724                                null, null);
2725                    } catch (SendIntentException e1) {
2726                        Slog.i(TAG, "Failed to send pending intent");
2727                    }
2728                }
2729            }
2730        });
2731    }
2732
2733    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2734        synchronized (mInstallLock) {
2735            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2736                throw new IOException("Failed to free enough space");
2737            }
2738        }
2739    }
2740
2741    @Override
2742    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2743        if (!sUserManager.exists(userId)) return null;
2744        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2745        synchronized (mPackages) {
2746            PackageParser.Activity a = mActivities.mActivities.get(component);
2747
2748            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2749            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2750                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2751                if (ps == null) return null;
2752                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2753                        userId);
2754            }
2755            if (mResolveComponentName.equals(component)) {
2756                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2757                        new PackageUserState(), userId);
2758            }
2759        }
2760        return null;
2761    }
2762
2763    @Override
2764    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2765            String resolvedType) {
2766        synchronized (mPackages) {
2767            PackageParser.Activity a = mActivities.mActivities.get(component);
2768            if (a == null) {
2769                return false;
2770            }
2771            for (int i=0; i<a.intents.size(); i++) {
2772                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2773                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2774                    return true;
2775                }
2776            }
2777            return false;
2778        }
2779    }
2780
2781    @Override
2782    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2783        if (!sUserManager.exists(userId)) return null;
2784        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2785        synchronized (mPackages) {
2786            PackageParser.Activity a = mReceivers.mActivities.get(component);
2787            if (DEBUG_PACKAGE_INFO) Log.v(
2788                TAG, "getReceiverInfo " + component + ": " + a);
2789            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2790                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2791                if (ps == null) return null;
2792                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2793                        userId);
2794            }
2795        }
2796        return null;
2797    }
2798
2799    @Override
2800    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2801        if (!sUserManager.exists(userId)) return null;
2802        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2803        synchronized (mPackages) {
2804            PackageParser.Service s = mServices.mServices.get(component);
2805            if (DEBUG_PACKAGE_INFO) Log.v(
2806                TAG, "getServiceInfo " + component + ": " + s);
2807            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2808                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2809                if (ps == null) return null;
2810                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2811                        userId);
2812            }
2813        }
2814        return null;
2815    }
2816
2817    @Override
2818    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2819        if (!sUserManager.exists(userId)) return null;
2820        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2821        synchronized (mPackages) {
2822            PackageParser.Provider p = mProviders.mProviders.get(component);
2823            if (DEBUG_PACKAGE_INFO) Log.v(
2824                TAG, "getProviderInfo " + component + ": " + p);
2825            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2826                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2827                if (ps == null) return null;
2828                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2829                        userId);
2830            }
2831        }
2832        return null;
2833    }
2834
2835    @Override
2836    public String[] getSystemSharedLibraryNames() {
2837        Set<String> libSet;
2838        synchronized (mPackages) {
2839            libSet = mSharedLibraries.keySet();
2840            int size = libSet.size();
2841            if (size > 0) {
2842                String[] libs = new String[size];
2843                libSet.toArray(libs);
2844                return libs;
2845            }
2846        }
2847        return null;
2848    }
2849
2850    /**
2851     * @hide
2852     */
2853    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2854        synchronized (mPackages) {
2855            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2856            if (lib != null && lib.apk != null) {
2857                return mPackages.get(lib.apk);
2858            }
2859        }
2860        return null;
2861    }
2862
2863    @Override
2864    public FeatureInfo[] getSystemAvailableFeatures() {
2865        Collection<FeatureInfo> featSet;
2866        synchronized (mPackages) {
2867            featSet = mAvailableFeatures.values();
2868            int size = featSet.size();
2869            if (size > 0) {
2870                FeatureInfo[] features = new FeatureInfo[size+1];
2871                featSet.toArray(features);
2872                FeatureInfo fi = new FeatureInfo();
2873                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2874                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2875                features[size] = fi;
2876                return features;
2877            }
2878        }
2879        return null;
2880    }
2881
2882    @Override
2883    public boolean hasSystemFeature(String name) {
2884        synchronized (mPackages) {
2885            return mAvailableFeatures.containsKey(name);
2886        }
2887    }
2888
2889    private void checkValidCaller(int uid, int userId) {
2890        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2891            return;
2892
2893        throw new SecurityException("Caller uid=" + uid
2894                + " is not privileged to communicate with user=" + userId);
2895    }
2896
2897    @Override
2898    public int checkPermission(String permName, String pkgName, int userId) {
2899        if (!sUserManager.exists(userId)) {
2900            return PackageManager.PERMISSION_DENIED;
2901        }
2902
2903        synchronized (mPackages) {
2904            final PackageParser.Package p = mPackages.get(pkgName);
2905            if (p != null && p.mExtras != null) {
2906                final PackageSetting ps = (PackageSetting) p.mExtras;
2907                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2908                    return PackageManager.PERMISSION_GRANTED;
2909                }
2910            }
2911        }
2912
2913        return PackageManager.PERMISSION_DENIED;
2914    }
2915
2916    @Override
2917    public int checkUidPermission(String permName, int uid) {
2918        final int userId = UserHandle.getUserId(uid);
2919
2920        if (!sUserManager.exists(userId)) {
2921            return PackageManager.PERMISSION_DENIED;
2922        }
2923
2924        synchronized (mPackages) {
2925            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2926            if (obj != null) {
2927                final SettingBase ps = (SettingBase) obj;
2928                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2929                    return PackageManager.PERMISSION_GRANTED;
2930                }
2931            } else {
2932                ArraySet<String> perms = mSystemPermissions.get(uid);
2933                if (perms != null && perms.contains(permName)) {
2934                    return PackageManager.PERMISSION_GRANTED;
2935                }
2936            }
2937        }
2938
2939        return PackageManager.PERMISSION_DENIED;
2940    }
2941
2942    /**
2943     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2944     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2945     * @param checkShell TODO(yamasani):
2946     * @param message the message to log on security exception
2947     */
2948    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2949            boolean checkShell, String message) {
2950        if (userId < 0) {
2951            throw new IllegalArgumentException("Invalid userId " + userId);
2952        }
2953        if (checkShell) {
2954            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2955        }
2956        if (userId == UserHandle.getUserId(callingUid)) return;
2957        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2958            if (requireFullPermission) {
2959                mContext.enforceCallingOrSelfPermission(
2960                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2961            } else {
2962                try {
2963                    mContext.enforceCallingOrSelfPermission(
2964                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2965                } catch (SecurityException se) {
2966                    mContext.enforceCallingOrSelfPermission(
2967                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2968                }
2969            }
2970        }
2971    }
2972
2973    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2974        if (callingUid == Process.SHELL_UID) {
2975            if (userHandle >= 0
2976                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2977                throw new SecurityException("Shell does not have permission to access user "
2978                        + userHandle);
2979            } else if (userHandle < 0) {
2980                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2981                        + Debug.getCallers(3));
2982            }
2983        }
2984    }
2985
2986    private BasePermission findPermissionTreeLP(String permName) {
2987        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2988            if (permName.startsWith(bp.name) &&
2989                    permName.length() > bp.name.length() &&
2990                    permName.charAt(bp.name.length()) == '.') {
2991                return bp;
2992            }
2993        }
2994        return null;
2995    }
2996
2997    private BasePermission checkPermissionTreeLP(String permName) {
2998        if (permName != null) {
2999            BasePermission bp = findPermissionTreeLP(permName);
3000            if (bp != null) {
3001                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3002                    return bp;
3003                }
3004                throw new SecurityException("Calling uid "
3005                        + Binder.getCallingUid()
3006                        + " is not allowed to add to permission tree "
3007                        + bp.name + " owned by uid " + bp.uid);
3008            }
3009        }
3010        throw new SecurityException("No permission tree found for " + permName);
3011    }
3012
3013    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3014        if (s1 == null) {
3015            return s2 == null;
3016        }
3017        if (s2 == null) {
3018            return false;
3019        }
3020        if (s1.getClass() != s2.getClass()) {
3021            return false;
3022        }
3023        return s1.equals(s2);
3024    }
3025
3026    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3027        if (pi1.icon != pi2.icon) return false;
3028        if (pi1.logo != pi2.logo) return false;
3029        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3030        if (!compareStrings(pi1.name, pi2.name)) return false;
3031        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3032        // We'll take care of setting this one.
3033        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3034        // These are not currently stored in settings.
3035        //if (!compareStrings(pi1.group, pi2.group)) return false;
3036        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3037        //if (pi1.labelRes != pi2.labelRes) return false;
3038        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3039        return true;
3040    }
3041
3042    int permissionInfoFootprint(PermissionInfo info) {
3043        int size = info.name.length();
3044        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3045        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3046        return size;
3047    }
3048
3049    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3050        int size = 0;
3051        for (BasePermission perm : mSettings.mPermissions.values()) {
3052            if (perm.uid == tree.uid) {
3053                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3054            }
3055        }
3056        return size;
3057    }
3058
3059    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3060        // We calculate the max size of permissions defined by this uid and throw
3061        // if that plus the size of 'info' would exceed our stated maximum.
3062        if (tree.uid != Process.SYSTEM_UID) {
3063            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3064            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3065                throw new SecurityException("Permission tree size cap exceeded");
3066            }
3067        }
3068    }
3069
3070    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3071        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3072            throw new SecurityException("Label must be specified in permission");
3073        }
3074        BasePermission tree = checkPermissionTreeLP(info.name);
3075        BasePermission bp = mSettings.mPermissions.get(info.name);
3076        boolean added = bp == null;
3077        boolean changed = true;
3078        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3079        if (added) {
3080            enforcePermissionCapLocked(info, tree);
3081            bp = new BasePermission(info.name, tree.sourcePackage,
3082                    BasePermission.TYPE_DYNAMIC);
3083        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3084            throw new SecurityException(
3085                    "Not allowed to modify non-dynamic permission "
3086                    + info.name);
3087        } else {
3088            if (bp.protectionLevel == fixedLevel
3089                    && bp.perm.owner.equals(tree.perm.owner)
3090                    && bp.uid == tree.uid
3091                    && comparePermissionInfos(bp.perm.info, info)) {
3092                changed = false;
3093            }
3094        }
3095        bp.protectionLevel = fixedLevel;
3096        info = new PermissionInfo(info);
3097        info.protectionLevel = fixedLevel;
3098        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3099        bp.perm.info.packageName = tree.perm.info.packageName;
3100        bp.uid = tree.uid;
3101        if (added) {
3102            mSettings.mPermissions.put(info.name, bp);
3103        }
3104        if (changed) {
3105            if (!async) {
3106                mSettings.writeLPr();
3107            } else {
3108                scheduleWriteSettingsLocked();
3109            }
3110        }
3111        return added;
3112    }
3113
3114    @Override
3115    public boolean addPermission(PermissionInfo info) {
3116        synchronized (mPackages) {
3117            return addPermissionLocked(info, false);
3118        }
3119    }
3120
3121    @Override
3122    public boolean addPermissionAsync(PermissionInfo info) {
3123        synchronized (mPackages) {
3124            return addPermissionLocked(info, true);
3125        }
3126    }
3127
3128    @Override
3129    public void removePermission(String name) {
3130        synchronized (mPackages) {
3131            checkPermissionTreeLP(name);
3132            BasePermission bp = mSettings.mPermissions.get(name);
3133            if (bp != null) {
3134                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3135                    throw new SecurityException(
3136                            "Not allowed to modify non-dynamic permission "
3137                            + name);
3138                }
3139                mSettings.mPermissions.remove(name);
3140                mSettings.writeLPr();
3141            }
3142        }
3143    }
3144
3145    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3146            BasePermission bp) {
3147        int index = pkg.requestedPermissions.indexOf(bp.name);
3148        if (index == -1) {
3149            throw new SecurityException("Package " + pkg.packageName
3150                    + " has not requested permission " + bp.name);
3151        }
3152        if (!bp.isRuntime()) {
3153            throw new SecurityException("Permission " + bp.name
3154                    + " is not a changeable permission type");
3155        }
3156    }
3157
3158    @Override
3159    public void grantRuntimePermission(String packageName, String name, int userId) {
3160        if (!sUserManager.exists(userId)) {
3161            Log.e(TAG, "No such user:" + userId);
3162            return;
3163        }
3164
3165        mContext.enforceCallingOrSelfPermission(
3166                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3167                "grantRuntimePermission");
3168
3169        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3170                "grantRuntimePermission");
3171
3172        boolean gidsChanged = false;
3173        final SettingBase sb;
3174
3175        synchronized (mPackages) {
3176            final PackageParser.Package pkg = mPackages.get(packageName);
3177            if (pkg == null) {
3178                throw new IllegalArgumentException("Unknown package: " + packageName);
3179            }
3180
3181            final BasePermission bp = mSettings.mPermissions.get(name);
3182            if (bp == null) {
3183                throw new IllegalArgumentException("Unknown permission: " + name);
3184            }
3185
3186            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3187
3188            sb = (SettingBase) pkg.mExtras;
3189            if (sb == null) {
3190                throw new IllegalArgumentException("Unknown package: " + packageName);
3191            }
3192
3193            final PermissionsState permissionsState = sb.getPermissionsState();
3194
3195            final int flags = permissionsState.getPermissionFlags(name, userId);
3196            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3197                throw new SecurityException("Cannot grant system fixed permission: "
3198                        + name + " for package: " + packageName);
3199            }
3200
3201            final int result = permissionsState.grantRuntimePermission(bp, userId);
3202            switch (result) {
3203                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3204                    return;
3205                }
3206
3207                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3208                    gidsChanged = true;
3209                } break;
3210            }
3211
3212            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3213
3214            // Not critical if that is lost - app has to request again.
3215            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3216        }
3217
3218        if (gidsChanged) {
3219            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3220        }
3221    }
3222
3223    @Override
3224    public void revokeRuntimePermission(String packageName, String name, int userId) {
3225        if (!sUserManager.exists(userId)) {
3226            Log.e(TAG, "No such user:" + userId);
3227            return;
3228        }
3229
3230        mContext.enforceCallingOrSelfPermission(
3231                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3232                "revokeRuntimePermission");
3233
3234        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3235                "revokeRuntimePermission");
3236
3237        final SettingBase sb;
3238
3239        synchronized (mPackages) {
3240            final PackageParser.Package pkg = mPackages.get(packageName);
3241            if (pkg == null) {
3242                throw new IllegalArgumentException("Unknown package: " + packageName);
3243            }
3244
3245            final BasePermission bp = mSettings.mPermissions.get(name);
3246            if (bp == null) {
3247                throw new IllegalArgumentException("Unknown permission: " + name);
3248            }
3249
3250            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3251
3252            sb = (SettingBase) pkg.mExtras;
3253            if (sb == null) {
3254                throw new IllegalArgumentException("Unknown package: " + packageName);
3255            }
3256
3257            final PermissionsState permissionsState = sb.getPermissionsState();
3258
3259            final int flags = permissionsState.getPermissionFlags(name, userId);
3260            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3261                throw new SecurityException("Cannot revoke system fixed permission: "
3262                        + name + " for package: " + packageName);
3263            }
3264
3265            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3266                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3267                return;
3268            }
3269
3270            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3271
3272            // Critical, after this call app should never have the permission.
3273            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3274        }
3275
3276        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3277    }
3278
3279    @Override
3280    public int getPermissionFlags(String name, String packageName, int userId) {
3281        if (!sUserManager.exists(userId)) {
3282            return 0;
3283        }
3284
3285        mContext.enforceCallingOrSelfPermission(
3286                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3287                "getPermissionFlags");
3288
3289        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3290                "getPermissionFlags");
3291
3292        synchronized (mPackages) {
3293            final PackageParser.Package pkg = mPackages.get(packageName);
3294            if (pkg == null) {
3295                throw new IllegalArgumentException("Unknown package: " + packageName);
3296            }
3297
3298            final BasePermission bp = mSettings.mPermissions.get(name);
3299            if (bp == null) {
3300                throw new IllegalArgumentException("Unknown permission: " + name);
3301            }
3302
3303            SettingBase sb = (SettingBase) pkg.mExtras;
3304            if (sb == null) {
3305                throw new IllegalArgumentException("Unknown package: " + packageName);
3306            }
3307
3308            PermissionsState permissionsState = sb.getPermissionsState();
3309            return permissionsState.getPermissionFlags(name, userId);
3310        }
3311    }
3312
3313    @Override
3314    public void updatePermissionFlags(String name, String packageName, int flagMask,
3315            int flagValues, int userId) {
3316        if (!sUserManager.exists(userId)) {
3317            return;
3318        }
3319
3320        mContext.enforceCallingOrSelfPermission(
3321                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3322                "updatePermissionFlags");
3323
3324        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3325                "updatePermissionFlags");
3326
3327        // Only the system can change policy flags.
3328        if (getCallingUid() != Process.SYSTEM_UID) {
3329            flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3330            flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3331        }
3332
3333        // Only the package manager can change system flags.
3334        flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3335        flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3336
3337        synchronized (mPackages) {
3338            final PackageParser.Package pkg = mPackages.get(packageName);
3339            if (pkg == null) {
3340                throw new IllegalArgumentException("Unknown package: " + packageName);
3341            }
3342
3343            final BasePermission bp = mSettings.mPermissions.get(name);
3344            if (bp == null) {
3345                throw new IllegalArgumentException("Unknown permission: " + name);
3346            }
3347
3348            SettingBase sb = (SettingBase) pkg.mExtras;
3349            if (sb == null) {
3350                throw new IllegalArgumentException("Unknown package: " + packageName);
3351            }
3352
3353            PermissionsState permissionsState = sb.getPermissionsState();
3354
3355            // Only the package manager can change flags for system component permissions.
3356            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3357            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3358                return;
3359            }
3360
3361            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3362                // Install and runtime permissions are stored in different places,
3363                // so figure out what permission changed and persist the change.
3364                if (permissionsState.getInstallPermissionState(name) != null) {
3365                    scheduleWriteSettingsLocked();
3366                } else if (permissionsState.getRuntimePermissionState(name, userId) != null) {
3367                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3368                }
3369            }
3370        }
3371    }
3372
3373    @Override
3374    public boolean shouldShowRequestPermissionRationale(String permissionName,
3375            String packageName, int userId) {
3376        if (UserHandle.getCallingUserId() != userId) {
3377            mContext.enforceCallingPermission(
3378                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3379                    "canShowRequestPermissionRationale for user " + userId);
3380        }
3381
3382        final int uid = getPackageUid(packageName, userId);
3383        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3384            return false;
3385        }
3386
3387        if (checkPermission(permissionName, packageName, userId)
3388                == PackageManager.PERMISSION_GRANTED) {
3389            return false;
3390        }
3391
3392        final int flags;
3393
3394        final long identity = Binder.clearCallingIdentity();
3395        try {
3396            flags = getPermissionFlags(permissionName,
3397                    packageName, userId);
3398        } finally {
3399            Binder.restoreCallingIdentity(identity);
3400        }
3401
3402        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3403                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3404                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3405
3406        if ((flags & fixedFlags) != 0) {
3407            return false;
3408        }
3409
3410        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3411    }
3412
3413    @Override
3414    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3415        mContext.enforceCallingOrSelfPermission(
3416                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3417                "addOnPermissionsChangeListener");
3418
3419        synchronized (mPackages) {
3420            mOnPermissionChangeListeners.addListenerLocked(listener);
3421        }
3422    }
3423
3424    @Override
3425    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3426        synchronized (mPackages) {
3427            mOnPermissionChangeListeners.removeListenerLocked(listener);
3428        }
3429    }
3430
3431    @Override
3432    public boolean isProtectedBroadcast(String actionName) {
3433        synchronized (mPackages) {
3434            return mProtectedBroadcasts.contains(actionName);
3435        }
3436    }
3437
3438    @Override
3439    public int checkSignatures(String pkg1, String pkg2) {
3440        synchronized (mPackages) {
3441            final PackageParser.Package p1 = mPackages.get(pkg1);
3442            final PackageParser.Package p2 = mPackages.get(pkg2);
3443            if (p1 == null || p1.mExtras == null
3444                    || p2 == null || p2.mExtras == null) {
3445                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3446            }
3447            return compareSignatures(p1.mSignatures, p2.mSignatures);
3448        }
3449    }
3450
3451    @Override
3452    public int checkUidSignatures(int uid1, int uid2) {
3453        // Map to base uids.
3454        uid1 = UserHandle.getAppId(uid1);
3455        uid2 = UserHandle.getAppId(uid2);
3456        // reader
3457        synchronized (mPackages) {
3458            Signature[] s1;
3459            Signature[] s2;
3460            Object obj = mSettings.getUserIdLPr(uid1);
3461            if (obj != null) {
3462                if (obj instanceof SharedUserSetting) {
3463                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3464                } else if (obj instanceof PackageSetting) {
3465                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3466                } else {
3467                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3468                }
3469            } else {
3470                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3471            }
3472            obj = mSettings.getUserIdLPr(uid2);
3473            if (obj != null) {
3474                if (obj instanceof SharedUserSetting) {
3475                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3476                } else if (obj instanceof PackageSetting) {
3477                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3478                } else {
3479                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3480                }
3481            } else {
3482                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3483            }
3484            return compareSignatures(s1, s2);
3485        }
3486    }
3487
3488    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3489        final long identity = Binder.clearCallingIdentity();
3490        try {
3491            if (sb instanceof SharedUserSetting) {
3492                SharedUserSetting sus = (SharedUserSetting) sb;
3493                final int packageCount = sus.packages.size();
3494                for (int i = 0; i < packageCount; i++) {
3495                    PackageSetting susPs = sus.packages.valueAt(i);
3496                    if (userId == UserHandle.USER_ALL) {
3497                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3498                    } else {
3499                        final int uid = UserHandle.getUid(userId, susPs.appId);
3500                        killUid(uid, reason);
3501                    }
3502                }
3503            } else if (sb instanceof PackageSetting) {
3504                PackageSetting ps = (PackageSetting) sb;
3505                if (userId == UserHandle.USER_ALL) {
3506                    killApplication(ps.pkg.packageName, ps.appId, reason);
3507                } else {
3508                    final int uid = UserHandle.getUid(userId, ps.appId);
3509                    killUid(uid, reason);
3510                }
3511            }
3512        } finally {
3513            Binder.restoreCallingIdentity(identity);
3514        }
3515    }
3516
3517    private static void killUid(int uid, String reason) {
3518        IActivityManager am = ActivityManagerNative.getDefault();
3519        if (am != null) {
3520            try {
3521                am.killUid(uid, reason);
3522            } catch (RemoteException e) {
3523                /* ignore - same process */
3524            }
3525        }
3526    }
3527
3528    /**
3529     * Compares two sets of signatures. Returns:
3530     * <br />
3531     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3532     * <br />
3533     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3534     * <br />
3535     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3536     * <br />
3537     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3538     * <br />
3539     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3540     */
3541    static int compareSignatures(Signature[] s1, Signature[] s2) {
3542        if (s1 == null) {
3543            return s2 == null
3544                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3545                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3546        }
3547
3548        if (s2 == null) {
3549            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3550        }
3551
3552        if (s1.length != s2.length) {
3553            return PackageManager.SIGNATURE_NO_MATCH;
3554        }
3555
3556        // Since both signature sets are of size 1, we can compare without HashSets.
3557        if (s1.length == 1) {
3558            return s1[0].equals(s2[0]) ?
3559                    PackageManager.SIGNATURE_MATCH :
3560                    PackageManager.SIGNATURE_NO_MATCH;
3561        }
3562
3563        ArraySet<Signature> set1 = new ArraySet<Signature>();
3564        for (Signature sig : s1) {
3565            set1.add(sig);
3566        }
3567        ArraySet<Signature> set2 = new ArraySet<Signature>();
3568        for (Signature sig : s2) {
3569            set2.add(sig);
3570        }
3571        // Make sure s2 contains all signatures in s1.
3572        if (set1.equals(set2)) {
3573            return PackageManager.SIGNATURE_MATCH;
3574        }
3575        return PackageManager.SIGNATURE_NO_MATCH;
3576    }
3577
3578    /**
3579     * If the database version for this type of package (internal storage or
3580     * external storage) is less than the version where package signatures
3581     * were updated, return true.
3582     */
3583    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3584        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3585                DatabaseVersion.SIGNATURE_END_ENTITY))
3586                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3587                        DatabaseVersion.SIGNATURE_END_ENTITY));
3588    }
3589
3590    /**
3591     * Used for backward compatibility to make sure any packages with
3592     * certificate chains get upgraded to the new style. {@code existingSigs}
3593     * will be in the old format (since they were stored on disk from before the
3594     * system upgrade) and {@code scannedSigs} will be in the newer format.
3595     */
3596    private int compareSignaturesCompat(PackageSignatures existingSigs,
3597            PackageParser.Package scannedPkg) {
3598        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3599            return PackageManager.SIGNATURE_NO_MATCH;
3600        }
3601
3602        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3603        for (Signature sig : existingSigs.mSignatures) {
3604            existingSet.add(sig);
3605        }
3606        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3607        for (Signature sig : scannedPkg.mSignatures) {
3608            try {
3609                Signature[] chainSignatures = sig.getChainSignatures();
3610                for (Signature chainSig : chainSignatures) {
3611                    scannedCompatSet.add(chainSig);
3612                }
3613            } catch (CertificateEncodingException e) {
3614                scannedCompatSet.add(sig);
3615            }
3616        }
3617        /*
3618         * Make sure the expanded scanned set contains all signatures in the
3619         * existing one.
3620         */
3621        if (scannedCompatSet.equals(existingSet)) {
3622            // Migrate the old signatures to the new scheme.
3623            existingSigs.assignSignatures(scannedPkg.mSignatures);
3624            // The new KeySets will be re-added later in the scanning process.
3625            synchronized (mPackages) {
3626                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3627            }
3628            return PackageManager.SIGNATURE_MATCH;
3629        }
3630        return PackageManager.SIGNATURE_NO_MATCH;
3631    }
3632
3633    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3634        if (isExternal(scannedPkg)) {
3635            return mSettings.isExternalDatabaseVersionOlderThan(
3636                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3637        } else {
3638            return mSettings.isInternalDatabaseVersionOlderThan(
3639                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3640        }
3641    }
3642
3643    private int compareSignaturesRecover(PackageSignatures existingSigs,
3644            PackageParser.Package scannedPkg) {
3645        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3646            return PackageManager.SIGNATURE_NO_MATCH;
3647        }
3648
3649        String msg = null;
3650        try {
3651            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3652                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3653                        + scannedPkg.packageName);
3654                return PackageManager.SIGNATURE_MATCH;
3655            }
3656        } catch (CertificateException e) {
3657            msg = e.getMessage();
3658        }
3659
3660        logCriticalInfo(Log.INFO,
3661                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3662        return PackageManager.SIGNATURE_NO_MATCH;
3663    }
3664
3665    @Override
3666    public String[] getPackagesForUid(int uid) {
3667        uid = UserHandle.getAppId(uid);
3668        // reader
3669        synchronized (mPackages) {
3670            Object obj = mSettings.getUserIdLPr(uid);
3671            if (obj instanceof SharedUserSetting) {
3672                final SharedUserSetting sus = (SharedUserSetting) obj;
3673                final int N = sus.packages.size();
3674                final String[] res = new String[N];
3675                final Iterator<PackageSetting> it = sus.packages.iterator();
3676                int i = 0;
3677                while (it.hasNext()) {
3678                    res[i++] = it.next().name;
3679                }
3680                return res;
3681            } else if (obj instanceof PackageSetting) {
3682                final PackageSetting ps = (PackageSetting) obj;
3683                return new String[] { ps.name };
3684            }
3685        }
3686        return null;
3687    }
3688
3689    @Override
3690    public String getNameForUid(int uid) {
3691        // reader
3692        synchronized (mPackages) {
3693            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3694            if (obj instanceof SharedUserSetting) {
3695                final SharedUserSetting sus = (SharedUserSetting) obj;
3696                return sus.name + ":" + sus.userId;
3697            } else if (obj instanceof PackageSetting) {
3698                final PackageSetting ps = (PackageSetting) obj;
3699                return ps.name;
3700            }
3701        }
3702        return null;
3703    }
3704
3705    @Override
3706    public int getUidForSharedUser(String sharedUserName) {
3707        if(sharedUserName == null) {
3708            return -1;
3709        }
3710        // reader
3711        synchronized (mPackages) {
3712            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3713            if (suid == null) {
3714                return -1;
3715            }
3716            return suid.userId;
3717        }
3718    }
3719
3720    @Override
3721    public int getFlagsForUid(int uid) {
3722        synchronized (mPackages) {
3723            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3724            if (obj instanceof SharedUserSetting) {
3725                final SharedUserSetting sus = (SharedUserSetting) obj;
3726                return sus.pkgFlags;
3727            } else if (obj instanceof PackageSetting) {
3728                final PackageSetting ps = (PackageSetting) obj;
3729                return ps.pkgFlags;
3730            }
3731        }
3732        return 0;
3733    }
3734
3735    @Override
3736    public int getPrivateFlagsForUid(int uid) {
3737        synchronized (mPackages) {
3738            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3739            if (obj instanceof SharedUserSetting) {
3740                final SharedUserSetting sus = (SharedUserSetting) obj;
3741                return sus.pkgPrivateFlags;
3742            } else if (obj instanceof PackageSetting) {
3743                final PackageSetting ps = (PackageSetting) obj;
3744                return ps.pkgPrivateFlags;
3745            }
3746        }
3747        return 0;
3748    }
3749
3750    @Override
3751    public boolean isUidPrivileged(int uid) {
3752        uid = UserHandle.getAppId(uid);
3753        // reader
3754        synchronized (mPackages) {
3755            Object obj = mSettings.getUserIdLPr(uid);
3756            if (obj instanceof SharedUserSetting) {
3757                final SharedUserSetting sus = (SharedUserSetting) obj;
3758                final Iterator<PackageSetting> it = sus.packages.iterator();
3759                while (it.hasNext()) {
3760                    if (it.next().isPrivileged()) {
3761                        return true;
3762                    }
3763                }
3764            } else if (obj instanceof PackageSetting) {
3765                final PackageSetting ps = (PackageSetting) obj;
3766                return ps.isPrivileged();
3767            }
3768        }
3769        return false;
3770    }
3771
3772    @Override
3773    public String[] getAppOpPermissionPackages(String permissionName) {
3774        synchronized (mPackages) {
3775            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3776            if (pkgs == null) {
3777                return null;
3778            }
3779            return pkgs.toArray(new String[pkgs.size()]);
3780        }
3781    }
3782
3783    @Override
3784    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3785            int flags, int userId) {
3786        if (!sUserManager.exists(userId)) return null;
3787        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3788        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3789        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3790    }
3791
3792    @Override
3793    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3794            IntentFilter filter, int match, ComponentName activity) {
3795        final int userId = UserHandle.getCallingUserId();
3796        if (DEBUG_PREFERRED) {
3797            Log.v(TAG, "setLastChosenActivity intent=" + intent
3798                + " resolvedType=" + resolvedType
3799                + " flags=" + flags
3800                + " filter=" + filter
3801                + " match=" + match
3802                + " activity=" + activity);
3803            filter.dump(new PrintStreamPrinter(System.out), "    ");
3804        }
3805        intent.setComponent(null);
3806        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3807        // Find any earlier preferred or last chosen entries and nuke them
3808        findPreferredActivity(intent, resolvedType,
3809                flags, query, 0, false, true, false, userId);
3810        // Add the new activity as the last chosen for this filter
3811        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3812                "Setting last chosen");
3813    }
3814
3815    @Override
3816    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3817        final int userId = UserHandle.getCallingUserId();
3818        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3819        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3820        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3821                false, false, false, userId);
3822    }
3823
3824    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3825            int flags, List<ResolveInfo> query, int userId) {
3826        if (query != null) {
3827            final int N = query.size();
3828            if (N == 1) {
3829                return query.get(0);
3830            } else if (N > 1) {
3831                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3832                // If there is more than one activity with the same priority,
3833                // then let the user decide between them.
3834                ResolveInfo r0 = query.get(0);
3835                ResolveInfo r1 = query.get(1);
3836                if (DEBUG_INTENT_MATCHING || debug) {
3837                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3838                            + r1.activityInfo.name + "=" + r1.priority);
3839                }
3840                // If the first activity has a higher priority, or a different
3841                // default, then it is always desireable to pick it.
3842                if (r0.priority != r1.priority
3843                        || r0.preferredOrder != r1.preferredOrder
3844                        || r0.isDefault != r1.isDefault) {
3845                    return query.get(0);
3846                }
3847                // If we have saved a preference for a preferred activity for
3848                // this Intent, use that.
3849                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3850                        flags, query, r0.priority, true, false, debug, userId);
3851                if (ri != null) {
3852                    return ri;
3853                }
3854                if (userId != 0) {
3855                    ri = new ResolveInfo(mResolveInfo);
3856                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3857                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3858                            ri.activityInfo.applicationInfo);
3859                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3860                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3861                    return ri;
3862                }
3863                return mResolveInfo;
3864            }
3865        }
3866        return null;
3867    }
3868
3869    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3870            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3871        final int N = query.size();
3872        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3873                .get(userId);
3874        // Get the list of persistent preferred activities that handle the intent
3875        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3876        List<PersistentPreferredActivity> pprefs = ppir != null
3877                ? ppir.queryIntent(intent, resolvedType,
3878                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3879                : null;
3880        if (pprefs != null && pprefs.size() > 0) {
3881            final int M = pprefs.size();
3882            for (int i=0; i<M; i++) {
3883                final PersistentPreferredActivity ppa = pprefs.get(i);
3884                if (DEBUG_PREFERRED || debug) {
3885                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3886                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3887                            + "\n  component=" + ppa.mComponent);
3888                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3889                }
3890                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3891                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3892                if (DEBUG_PREFERRED || debug) {
3893                    Slog.v(TAG, "Found persistent preferred activity:");
3894                    if (ai != null) {
3895                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3896                    } else {
3897                        Slog.v(TAG, "  null");
3898                    }
3899                }
3900                if (ai == null) {
3901                    // This previously registered persistent preferred activity
3902                    // component is no longer known. Ignore it and do NOT remove it.
3903                    continue;
3904                }
3905                for (int j=0; j<N; j++) {
3906                    final ResolveInfo ri = query.get(j);
3907                    if (!ri.activityInfo.applicationInfo.packageName
3908                            .equals(ai.applicationInfo.packageName)) {
3909                        continue;
3910                    }
3911                    if (!ri.activityInfo.name.equals(ai.name)) {
3912                        continue;
3913                    }
3914                    //  Found a persistent preference that can handle the intent.
3915                    if (DEBUG_PREFERRED || debug) {
3916                        Slog.v(TAG, "Returning persistent preferred activity: " +
3917                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3918                    }
3919                    return ri;
3920                }
3921            }
3922        }
3923        return null;
3924    }
3925
3926    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3927            List<ResolveInfo> query, int priority, boolean always,
3928            boolean removeMatches, boolean debug, int userId) {
3929        if (!sUserManager.exists(userId)) return null;
3930        // writer
3931        synchronized (mPackages) {
3932            if (intent.getSelector() != null) {
3933                intent = intent.getSelector();
3934            }
3935            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3936
3937            // Try to find a matching persistent preferred activity.
3938            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3939                    debug, userId);
3940
3941            // If a persistent preferred activity matched, use it.
3942            if (pri != null) {
3943                return pri;
3944            }
3945
3946            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3947            // Get the list of preferred activities that handle the intent
3948            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3949            List<PreferredActivity> prefs = pir != null
3950                    ? pir.queryIntent(intent, resolvedType,
3951                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3952                    : null;
3953            if (prefs != null && prefs.size() > 0) {
3954                boolean changed = false;
3955                try {
3956                    // First figure out how good the original match set is.
3957                    // We will only allow preferred activities that came
3958                    // from the same match quality.
3959                    int match = 0;
3960
3961                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3962
3963                    final int N = query.size();
3964                    for (int j=0; j<N; j++) {
3965                        final ResolveInfo ri = query.get(j);
3966                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3967                                + ": 0x" + Integer.toHexString(match));
3968                        if (ri.match > match) {
3969                            match = ri.match;
3970                        }
3971                    }
3972
3973                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3974                            + Integer.toHexString(match));
3975
3976                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3977                    final int M = prefs.size();
3978                    for (int i=0; i<M; i++) {
3979                        final PreferredActivity pa = prefs.get(i);
3980                        if (DEBUG_PREFERRED || debug) {
3981                            Slog.v(TAG, "Checking PreferredActivity ds="
3982                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3983                                    + "\n  component=" + pa.mPref.mComponent);
3984                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3985                        }
3986                        if (pa.mPref.mMatch != match) {
3987                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3988                                    + Integer.toHexString(pa.mPref.mMatch));
3989                            continue;
3990                        }
3991                        // If it's not an "always" type preferred activity and that's what we're
3992                        // looking for, skip it.
3993                        if (always && !pa.mPref.mAlways) {
3994                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3995                            continue;
3996                        }
3997                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3998                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3999                        if (DEBUG_PREFERRED || debug) {
4000                            Slog.v(TAG, "Found preferred activity:");
4001                            if (ai != null) {
4002                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4003                            } else {
4004                                Slog.v(TAG, "  null");
4005                            }
4006                        }
4007                        if (ai == null) {
4008                            // This previously registered preferred activity
4009                            // component is no longer known.  Most likely an update
4010                            // to the app was installed and in the new version this
4011                            // component no longer exists.  Clean it up by removing
4012                            // it from the preferred activities list, and skip it.
4013                            Slog.w(TAG, "Removing dangling preferred activity: "
4014                                    + pa.mPref.mComponent);
4015                            pir.removeFilter(pa);
4016                            changed = true;
4017                            continue;
4018                        }
4019                        for (int j=0; j<N; j++) {
4020                            final ResolveInfo ri = query.get(j);
4021                            if (!ri.activityInfo.applicationInfo.packageName
4022                                    .equals(ai.applicationInfo.packageName)) {
4023                                continue;
4024                            }
4025                            if (!ri.activityInfo.name.equals(ai.name)) {
4026                                continue;
4027                            }
4028
4029                            if (removeMatches) {
4030                                pir.removeFilter(pa);
4031                                changed = true;
4032                                if (DEBUG_PREFERRED) {
4033                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4034                                }
4035                                break;
4036                            }
4037
4038                            // Okay we found a previously set preferred or last chosen app.
4039                            // If the result set is different from when this
4040                            // was created, we need to clear it and re-ask the
4041                            // user their preference, if we're looking for an "always" type entry.
4042                            if (always && !pa.mPref.sameSet(query)) {
4043                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4044                                        + intent + " type " + resolvedType);
4045                                if (DEBUG_PREFERRED) {
4046                                    Slog.v(TAG, "Removing preferred activity since set changed "
4047                                            + pa.mPref.mComponent);
4048                                }
4049                                pir.removeFilter(pa);
4050                                // Re-add the filter as a "last chosen" entry (!always)
4051                                PreferredActivity lastChosen = new PreferredActivity(
4052                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4053                                pir.addFilter(lastChosen);
4054                                changed = true;
4055                                return null;
4056                            }
4057
4058                            // Yay! Either the set matched or we're looking for the last chosen
4059                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4060                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4061                            return ri;
4062                        }
4063                    }
4064                } finally {
4065                    if (changed) {
4066                        if (DEBUG_PREFERRED) {
4067                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4068                        }
4069                        scheduleWritePackageRestrictionsLocked(userId);
4070                    }
4071                }
4072            }
4073        }
4074        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4075        return null;
4076    }
4077
4078    /*
4079     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4080     */
4081    @Override
4082    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4083            int targetUserId) {
4084        mContext.enforceCallingOrSelfPermission(
4085                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4086        List<CrossProfileIntentFilter> matches =
4087                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4088        if (matches != null) {
4089            int size = matches.size();
4090            for (int i = 0; i < size; i++) {
4091                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4092            }
4093        }
4094        return false;
4095    }
4096
4097    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4098            String resolvedType, int userId) {
4099        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4100        if (resolver != null) {
4101            return resolver.queryIntent(intent, resolvedType, false, userId);
4102        }
4103        return null;
4104    }
4105
4106    @Override
4107    public List<ResolveInfo> queryIntentActivities(Intent intent,
4108            String resolvedType, int flags, int userId) {
4109        if (!sUserManager.exists(userId)) return Collections.emptyList();
4110        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4111        ComponentName comp = intent.getComponent();
4112        if (comp == null) {
4113            if (intent.getSelector() != null) {
4114                intent = intent.getSelector();
4115                comp = intent.getComponent();
4116            }
4117        }
4118
4119        if (comp != null) {
4120            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4121            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4122            if (ai != null) {
4123                final ResolveInfo ri = new ResolveInfo();
4124                ri.activityInfo = ai;
4125                list.add(ri);
4126            }
4127            return list;
4128        }
4129
4130        // reader
4131        synchronized (mPackages) {
4132            final String pkgName = intent.getPackage();
4133            if (pkgName == null) {
4134                List<CrossProfileIntentFilter> matchingFilters =
4135                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4136                // Check for results that need to skip the current profile.
4137                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4138                        resolvedType, flags, userId);
4139                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4140                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4141                    result.add(resolveInfo);
4142                    return filterIfNotPrimaryUser(result, userId);
4143                }
4144
4145                // Check for results in the current profile.
4146                List<ResolveInfo> result = mActivities.queryIntent(
4147                        intent, resolvedType, flags, userId);
4148
4149                // Check for cross profile results.
4150                resolveInfo = queryCrossProfileIntents(
4151                        matchingFilters, intent, resolvedType, flags, userId);
4152                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4153                    result.add(resolveInfo);
4154                    Collections.sort(result, mResolvePrioritySorter);
4155                }
4156                result = filterIfNotPrimaryUser(result, userId);
4157                if (result.size() > 1 && hasWebURI(intent)) {
4158                    return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result);
4159                }
4160                return result;
4161            }
4162            final PackageParser.Package pkg = mPackages.get(pkgName);
4163            if (pkg != null) {
4164                return filterIfNotPrimaryUser(
4165                        mActivities.queryIntentForPackage(
4166                                intent, resolvedType, flags, pkg.activities, userId),
4167                        userId);
4168            }
4169            return new ArrayList<ResolveInfo>();
4170        }
4171    }
4172
4173    private boolean isUserEnabled(int userId) {
4174        long callingId = Binder.clearCallingIdentity();
4175        try {
4176            UserInfo userInfo = sUserManager.getUserInfo(userId);
4177            return userInfo != null && userInfo.isEnabled();
4178        } finally {
4179            Binder.restoreCallingIdentity(callingId);
4180        }
4181    }
4182
4183    /**
4184     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4185     *
4186     * @return filtered list
4187     */
4188    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4189        if (userId == UserHandle.USER_OWNER) {
4190            return resolveInfos;
4191        }
4192        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4193            ResolveInfo info = resolveInfos.get(i);
4194            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4195                resolveInfos.remove(i);
4196            }
4197        }
4198        return resolveInfos;
4199    }
4200
4201    private static boolean hasWebURI(Intent intent) {
4202        if (intent.getData() == null) {
4203            return false;
4204        }
4205        final String scheme = intent.getScheme();
4206        if (TextUtils.isEmpty(scheme)) {
4207            return false;
4208        }
4209        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4210    }
4211
4212    private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr(
4213            int flags, List<ResolveInfo> candidates) {
4214        if (DEBUG_PREFERRED) {
4215            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4216                    candidates.size());
4217        }
4218
4219        final int userId = UserHandle.getCallingUserId();
4220        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4221        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4222        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4223        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4224        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4225
4226        synchronized (mPackages) {
4227            final int count = candidates.size();
4228            // First, try to use the domain prefered App. Partition the candidates into four lists:
4229            // one for the final results, one for the "do not use ever", one for "undefined status"
4230            // and finally one for "Browser App type".
4231            for (int n=0; n<count; n++) {
4232                ResolveInfo info = candidates.get(n);
4233                String packageName = info.activityInfo.packageName;
4234                PackageSetting ps = mSettings.mPackages.get(packageName);
4235                if (ps != null) {
4236                    // Add to the special match all list (Browser use case)
4237                    if (info.handleAllWebDataURI) {
4238                        matchAllList.add(info);
4239                        continue;
4240                    }
4241                    // Try to get the status from User settings first
4242                    int status = getDomainVerificationStatusLPr(ps, userId);
4243                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4244                        alwaysList.add(info);
4245                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4246                        neverList.add(info);
4247                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4248                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4249                        undefinedList.add(info);
4250                    }
4251                }
4252            }
4253            // First try to add the "always" if there is any
4254            if (alwaysList.size() > 0) {
4255                result.addAll(alwaysList);
4256            } else {
4257                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4258                result.addAll(undefinedList);
4259                // Also add Browsers (all of them or only the default one)
4260                if ((flags & MATCH_ALL) != 0) {
4261                    result.addAll(matchAllList);
4262                } else {
4263                    // Try to add the Default Browser if we can
4264                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4265                            UserHandle.myUserId());
4266                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4267                        boolean defaultBrowserFound = false;
4268                        final int browserCount = matchAllList.size();
4269                        for (int n=0; n<browserCount; n++) {
4270                            ResolveInfo browser = matchAllList.get(n);
4271                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4272                                result.add(browser);
4273                                defaultBrowserFound = true;
4274                                break;
4275                            }
4276                        }
4277                        if (!defaultBrowserFound) {
4278                            result.addAll(matchAllList);
4279                        }
4280                    } else {
4281                        result.addAll(matchAllList);
4282                    }
4283                }
4284
4285                // If there is nothing selected, add all candidates and remove the ones that the User
4286                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4287                if (result.size() == 0) {
4288                    result.addAll(candidates);
4289                    result.removeAll(neverList);
4290                }
4291            }
4292        }
4293        if (DEBUG_PREFERRED) {
4294            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4295                    result.size());
4296        }
4297        return result;
4298    }
4299
4300    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4301        int status = ps.getDomainVerificationStatusForUser(userId);
4302        // if none available, get the master status
4303        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4304            if (ps.getIntentFilterVerificationInfo() != null) {
4305                status = ps.getIntentFilterVerificationInfo().getStatus();
4306            }
4307        }
4308        return status;
4309    }
4310
4311    private ResolveInfo querySkipCurrentProfileIntents(
4312            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4313            int flags, int sourceUserId) {
4314        if (matchingFilters != null) {
4315            int size = matchingFilters.size();
4316            for (int i = 0; i < size; i ++) {
4317                CrossProfileIntentFilter filter = matchingFilters.get(i);
4318                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4319                    // Checking if there are activities in the target user that can handle the
4320                    // intent.
4321                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4322                            flags, sourceUserId);
4323                    if (resolveInfo != null) {
4324                        return resolveInfo;
4325                    }
4326                }
4327            }
4328        }
4329        return null;
4330    }
4331
4332    // Return matching ResolveInfo if any for skip current profile intent filters.
4333    private ResolveInfo queryCrossProfileIntents(
4334            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4335            int flags, int sourceUserId) {
4336        if (matchingFilters != null) {
4337            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4338            // match the same intent. For performance reasons, it is better not to
4339            // run queryIntent twice for the same userId
4340            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4341            int size = matchingFilters.size();
4342            for (int i = 0; i < size; i++) {
4343                CrossProfileIntentFilter filter = matchingFilters.get(i);
4344                int targetUserId = filter.getTargetUserId();
4345                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4346                        && !alreadyTriedUserIds.get(targetUserId)) {
4347                    // Checking if there are activities in the target user that can handle the
4348                    // intent.
4349                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4350                            flags, sourceUserId);
4351                    if (resolveInfo != null) return resolveInfo;
4352                    alreadyTriedUserIds.put(targetUserId, true);
4353                }
4354            }
4355        }
4356        return null;
4357    }
4358
4359    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4360            String resolvedType, int flags, int sourceUserId) {
4361        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4362                resolvedType, flags, filter.getTargetUserId());
4363        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4364            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4365        }
4366        return null;
4367    }
4368
4369    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4370            int sourceUserId, int targetUserId) {
4371        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4372        String className;
4373        if (targetUserId == UserHandle.USER_OWNER) {
4374            className = FORWARD_INTENT_TO_USER_OWNER;
4375        } else {
4376            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4377        }
4378        ComponentName forwardingActivityComponentName = new ComponentName(
4379                mAndroidApplication.packageName, className);
4380        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4381                sourceUserId);
4382        if (targetUserId == UserHandle.USER_OWNER) {
4383            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4384            forwardingResolveInfo.noResourceId = true;
4385        }
4386        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4387        forwardingResolveInfo.priority = 0;
4388        forwardingResolveInfo.preferredOrder = 0;
4389        forwardingResolveInfo.match = 0;
4390        forwardingResolveInfo.isDefault = true;
4391        forwardingResolveInfo.filter = filter;
4392        forwardingResolveInfo.targetUserId = targetUserId;
4393        return forwardingResolveInfo;
4394    }
4395
4396    @Override
4397    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4398            Intent[] specifics, String[] specificTypes, Intent intent,
4399            String resolvedType, int flags, int userId) {
4400        if (!sUserManager.exists(userId)) return Collections.emptyList();
4401        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4402                false, "query intent activity options");
4403        final String resultsAction = intent.getAction();
4404
4405        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4406                | PackageManager.GET_RESOLVED_FILTER, userId);
4407
4408        if (DEBUG_INTENT_MATCHING) {
4409            Log.v(TAG, "Query " + intent + ": " + results);
4410        }
4411
4412        int specificsPos = 0;
4413        int N;
4414
4415        // todo: note that the algorithm used here is O(N^2).  This
4416        // isn't a problem in our current environment, but if we start running
4417        // into situations where we have more than 5 or 10 matches then this
4418        // should probably be changed to something smarter...
4419
4420        // First we go through and resolve each of the specific items
4421        // that were supplied, taking care of removing any corresponding
4422        // duplicate items in the generic resolve list.
4423        if (specifics != null) {
4424            for (int i=0; i<specifics.length; i++) {
4425                final Intent sintent = specifics[i];
4426                if (sintent == null) {
4427                    continue;
4428                }
4429
4430                if (DEBUG_INTENT_MATCHING) {
4431                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4432                }
4433
4434                String action = sintent.getAction();
4435                if (resultsAction != null && resultsAction.equals(action)) {
4436                    // If this action was explicitly requested, then don't
4437                    // remove things that have it.
4438                    action = null;
4439                }
4440
4441                ResolveInfo ri = null;
4442                ActivityInfo ai = null;
4443
4444                ComponentName comp = sintent.getComponent();
4445                if (comp == null) {
4446                    ri = resolveIntent(
4447                        sintent,
4448                        specificTypes != null ? specificTypes[i] : null,
4449                            flags, userId);
4450                    if (ri == null) {
4451                        continue;
4452                    }
4453                    if (ri == mResolveInfo) {
4454                        // ACK!  Must do something better with this.
4455                    }
4456                    ai = ri.activityInfo;
4457                    comp = new ComponentName(ai.applicationInfo.packageName,
4458                            ai.name);
4459                } else {
4460                    ai = getActivityInfo(comp, flags, userId);
4461                    if (ai == null) {
4462                        continue;
4463                    }
4464                }
4465
4466                // Look for any generic query activities that are duplicates
4467                // of this specific one, and remove them from the results.
4468                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4469                N = results.size();
4470                int j;
4471                for (j=specificsPos; j<N; j++) {
4472                    ResolveInfo sri = results.get(j);
4473                    if ((sri.activityInfo.name.equals(comp.getClassName())
4474                            && sri.activityInfo.applicationInfo.packageName.equals(
4475                                    comp.getPackageName()))
4476                        || (action != null && sri.filter.matchAction(action))) {
4477                        results.remove(j);
4478                        if (DEBUG_INTENT_MATCHING) Log.v(
4479                            TAG, "Removing duplicate item from " + j
4480                            + " due to specific " + specificsPos);
4481                        if (ri == null) {
4482                            ri = sri;
4483                        }
4484                        j--;
4485                        N--;
4486                    }
4487                }
4488
4489                // Add this specific item to its proper place.
4490                if (ri == null) {
4491                    ri = new ResolveInfo();
4492                    ri.activityInfo = ai;
4493                }
4494                results.add(specificsPos, ri);
4495                ri.specificIndex = i;
4496                specificsPos++;
4497            }
4498        }
4499
4500        // Now we go through the remaining generic results and remove any
4501        // duplicate actions that are found here.
4502        N = results.size();
4503        for (int i=specificsPos; i<N-1; i++) {
4504            final ResolveInfo rii = results.get(i);
4505            if (rii.filter == null) {
4506                continue;
4507            }
4508
4509            // Iterate over all of the actions of this result's intent
4510            // filter...  typically this should be just one.
4511            final Iterator<String> it = rii.filter.actionsIterator();
4512            if (it == null) {
4513                continue;
4514            }
4515            while (it.hasNext()) {
4516                final String action = it.next();
4517                if (resultsAction != null && resultsAction.equals(action)) {
4518                    // If this action was explicitly requested, then don't
4519                    // remove things that have it.
4520                    continue;
4521                }
4522                for (int j=i+1; j<N; j++) {
4523                    final ResolveInfo rij = results.get(j);
4524                    if (rij.filter != null && rij.filter.hasAction(action)) {
4525                        results.remove(j);
4526                        if (DEBUG_INTENT_MATCHING) Log.v(
4527                            TAG, "Removing duplicate item from " + j
4528                            + " due to action " + action + " at " + i);
4529                        j--;
4530                        N--;
4531                    }
4532                }
4533            }
4534
4535            // If the caller didn't request filter information, drop it now
4536            // so we don't have to marshall/unmarshall it.
4537            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4538                rii.filter = null;
4539            }
4540        }
4541
4542        // Filter out the caller activity if so requested.
4543        if (caller != null) {
4544            N = results.size();
4545            for (int i=0; i<N; i++) {
4546                ActivityInfo ainfo = results.get(i).activityInfo;
4547                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4548                        && caller.getClassName().equals(ainfo.name)) {
4549                    results.remove(i);
4550                    break;
4551                }
4552            }
4553        }
4554
4555        // If the caller didn't request filter information,
4556        // drop them now so we don't have to
4557        // marshall/unmarshall it.
4558        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4559            N = results.size();
4560            for (int i=0; i<N; i++) {
4561                results.get(i).filter = null;
4562            }
4563        }
4564
4565        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4566        return results;
4567    }
4568
4569    @Override
4570    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4571            int userId) {
4572        if (!sUserManager.exists(userId)) return Collections.emptyList();
4573        ComponentName comp = intent.getComponent();
4574        if (comp == null) {
4575            if (intent.getSelector() != null) {
4576                intent = intent.getSelector();
4577                comp = intent.getComponent();
4578            }
4579        }
4580        if (comp != null) {
4581            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4582            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4583            if (ai != null) {
4584                ResolveInfo ri = new ResolveInfo();
4585                ri.activityInfo = ai;
4586                list.add(ri);
4587            }
4588            return list;
4589        }
4590
4591        // reader
4592        synchronized (mPackages) {
4593            String pkgName = intent.getPackage();
4594            if (pkgName == null) {
4595                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4596            }
4597            final PackageParser.Package pkg = mPackages.get(pkgName);
4598            if (pkg != null) {
4599                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4600                        userId);
4601            }
4602            return null;
4603        }
4604    }
4605
4606    @Override
4607    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4608        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4609        if (!sUserManager.exists(userId)) return null;
4610        if (query != null) {
4611            if (query.size() >= 1) {
4612                // If there is more than one service with the same priority,
4613                // just arbitrarily pick the first one.
4614                return query.get(0);
4615            }
4616        }
4617        return null;
4618    }
4619
4620    @Override
4621    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4622            int userId) {
4623        if (!sUserManager.exists(userId)) return Collections.emptyList();
4624        ComponentName comp = intent.getComponent();
4625        if (comp == null) {
4626            if (intent.getSelector() != null) {
4627                intent = intent.getSelector();
4628                comp = intent.getComponent();
4629            }
4630        }
4631        if (comp != null) {
4632            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4633            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4634            if (si != null) {
4635                final ResolveInfo ri = new ResolveInfo();
4636                ri.serviceInfo = si;
4637                list.add(ri);
4638            }
4639            return list;
4640        }
4641
4642        // reader
4643        synchronized (mPackages) {
4644            String pkgName = intent.getPackage();
4645            if (pkgName == null) {
4646                return mServices.queryIntent(intent, resolvedType, flags, userId);
4647            }
4648            final PackageParser.Package pkg = mPackages.get(pkgName);
4649            if (pkg != null) {
4650                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4651                        userId);
4652            }
4653            return null;
4654        }
4655    }
4656
4657    @Override
4658    public List<ResolveInfo> queryIntentContentProviders(
4659            Intent intent, String resolvedType, int flags, int userId) {
4660        if (!sUserManager.exists(userId)) return Collections.emptyList();
4661        ComponentName comp = intent.getComponent();
4662        if (comp == null) {
4663            if (intent.getSelector() != null) {
4664                intent = intent.getSelector();
4665                comp = intent.getComponent();
4666            }
4667        }
4668        if (comp != null) {
4669            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4670            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4671            if (pi != null) {
4672                final ResolveInfo ri = new ResolveInfo();
4673                ri.providerInfo = pi;
4674                list.add(ri);
4675            }
4676            return list;
4677        }
4678
4679        // reader
4680        synchronized (mPackages) {
4681            String pkgName = intent.getPackage();
4682            if (pkgName == null) {
4683                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4684            }
4685            final PackageParser.Package pkg = mPackages.get(pkgName);
4686            if (pkg != null) {
4687                return mProviders.queryIntentForPackage(
4688                        intent, resolvedType, flags, pkg.providers, userId);
4689            }
4690            return null;
4691        }
4692    }
4693
4694    @Override
4695    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4696        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4697
4698        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4699
4700        // writer
4701        synchronized (mPackages) {
4702            ArrayList<PackageInfo> list;
4703            if (listUninstalled) {
4704                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4705                for (PackageSetting ps : mSettings.mPackages.values()) {
4706                    PackageInfo pi;
4707                    if (ps.pkg != null) {
4708                        pi = generatePackageInfo(ps.pkg, flags, userId);
4709                    } else {
4710                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4711                    }
4712                    if (pi != null) {
4713                        list.add(pi);
4714                    }
4715                }
4716            } else {
4717                list = new ArrayList<PackageInfo>(mPackages.size());
4718                for (PackageParser.Package p : mPackages.values()) {
4719                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4720                    if (pi != null) {
4721                        list.add(pi);
4722                    }
4723                }
4724            }
4725
4726            return new ParceledListSlice<PackageInfo>(list);
4727        }
4728    }
4729
4730    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4731            String[] permissions, boolean[] tmp, int flags, int userId) {
4732        int numMatch = 0;
4733        final PermissionsState permissionsState = ps.getPermissionsState();
4734        for (int i=0; i<permissions.length; i++) {
4735            final String permission = permissions[i];
4736            if (permissionsState.hasPermission(permission, userId)) {
4737                tmp[i] = true;
4738                numMatch++;
4739            } else {
4740                tmp[i] = false;
4741            }
4742        }
4743        if (numMatch == 0) {
4744            return;
4745        }
4746        PackageInfo pi;
4747        if (ps.pkg != null) {
4748            pi = generatePackageInfo(ps.pkg, flags, userId);
4749        } else {
4750            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4751        }
4752        // The above might return null in cases of uninstalled apps or install-state
4753        // skew across users/profiles.
4754        if (pi != null) {
4755            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4756                if (numMatch == permissions.length) {
4757                    pi.requestedPermissions = permissions;
4758                } else {
4759                    pi.requestedPermissions = new String[numMatch];
4760                    numMatch = 0;
4761                    for (int i=0; i<permissions.length; i++) {
4762                        if (tmp[i]) {
4763                            pi.requestedPermissions[numMatch] = permissions[i];
4764                            numMatch++;
4765                        }
4766                    }
4767                }
4768            }
4769            list.add(pi);
4770        }
4771    }
4772
4773    @Override
4774    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4775            String[] permissions, int flags, int userId) {
4776        if (!sUserManager.exists(userId)) return null;
4777        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4778
4779        // writer
4780        synchronized (mPackages) {
4781            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4782            boolean[] tmpBools = new boolean[permissions.length];
4783            if (listUninstalled) {
4784                for (PackageSetting ps : mSettings.mPackages.values()) {
4785                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4786                }
4787            } else {
4788                for (PackageParser.Package pkg : mPackages.values()) {
4789                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4790                    if (ps != null) {
4791                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4792                                userId);
4793                    }
4794                }
4795            }
4796
4797            return new ParceledListSlice<PackageInfo>(list);
4798        }
4799    }
4800
4801    @Override
4802    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4803        if (!sUserManager.exists(userId)) return null;
4804        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4805
4806        // writer
4807        synchronized (mPackages) {
4808            ArrayList<ApplicationInfo> list;
4809            if (listUninstalled) {
4810                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4811                for (PackageSetting ps : mSettings.mPackages.values()) {
4812                    ApplicationInfo ai;
4813                    if (ps.pkg != null) {
4814                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4815                                ps.readUserState(userId), userId);
4816                    } else {
4817                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4818                    }
4819                    if (ai != null) {
4820                        list.add(ai);
4821                    }
4822                }
4823            } else {
4824                list = new ArrayList<ApplicationInfo>(mPackages.size());
4825                for (PackageParser.Package p : mPackages.values()) {
4826                    if (p.mExtras != null) {
4827                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4828                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4829                        if (ai != null) {
4830                            list.add(ai);
4831                        }
4832                    }
4833                }
4834            }
4835
4836            return new ParceledListSlice<ApplicationInfo>(list);
4837        }
4838    }
4839
4840    public List<ApplicationInfo> getPersistentApplications(int flags) {
4841        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4842
4843        // reader
4844        synchronized (mPackages) {
4845            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4846            final int userId = UserHandle.getCallingUserId();
4847            while (i.hasNext()) {
4848                final PackageParser.Package p = i.next();
4849                if (p.applicationInfo != null
4850                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4851                        && (!mSafeMode || isSystemApp(p))) {
4852                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4853                    if (ps != null) {
4854                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4855                                ps.readUserState(userId), userId);
4856                        if (ai != null) {
4857                            finalList.add(ai);
4858                        }
4859                    }
4860                }
4861            }
4862        }
4863
4864        return finalList;
4865    }
4866
4867    @Override
4868    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4869        if (!sUserManager.exists(userId)) return null;
4870        // reader
4871        synchronized (mPackages) {
4872            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4873            PackageSetting ps = provider != null
4874                    ? mSettings.mPackages.get(provider.owner.packageName)
4875                    : null;
4876            return ps != null
4877                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4878                    && (!mSafeMode || (provider.info.applicationInfo.flags
4879                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4880                    ? PackageParser.generateProviderInfo(provider, flags,
4881                            ps.readUserState(userId), userId)
4882                    : null;
4883        }
4884    }
4885
4886    /**
4887     * @deprecated
4888     */
4889    @Deprecated
4890    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4891        // reader
4892        synchronized (mPackages) {
4893            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4894                    .entrySet().iterator();
4895            final int userId = UserHandle.getCallingUserId();
4896            while (i.hasNext()) {
4897                Map.Entry<String, PackageParser.Provider> entry = i.next();
4898                PackageParser.Provider p = entry.getValue();
4899                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4900
4901                if (ps != null && p.syncable
4902                        && (!mSafeMode || (p.info.applicationInfo.flags
4903                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4904                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4905                            ps.readUserState(userId), userId);
4906                    if (info != null) {
4907                        outNames.add(entry.getKey());
4908                        outInfo.add(info);
4909                    }
4910                }
4911            }
4912        }
4913    }
4914
4915    @Override
4916    public List<ProviderInfo> queryContentProviders(String processName,
4917            int uid, int flags) {
4918        ArrayList<ProviderInfo> finalList = null;
4919        // reader
4920        synchronized (mPackages) {
4921            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4922            final int userId = processName != null ?
4923                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4924            while (i.hasNext()) {
4925                final PackageParser.Provider p = i.next();
4926                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4927                if (ps != null && p.info.authority != null
4928                        && (processName == null
4929                                || (p.info.processName.equals(processName)
4930                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4931                        && mSettings.isEnabledLPr(p.info, flags, userId)
4932                        && (!mSafeMode
4933                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4934                    if (finalList == null) {
4935                        finalList = new ArrayList<ProviderInfo>(3);
4936                    }
4937                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4938                            ps.readUserState(userId), userId);
4939                    if (info != null) {
4940                        finalList.add(info);
4941                    }
4942                }
4943            }
4944        }
4945
4946        if (finalList != null) {
4947            Collections.sort(finalList, mProviderInitOrderSorter);
4948        }
4949
4950        return finalList;
4951    }
4952
4953    @Override
4954    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4955            int flags) {
4956        // reader
4957        synchronized (mPackages) {
4958            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4959            return PackageParser.generateInstrumentationInfo(i, flags);
4960        }
4961    }
4962
4963    @Override
4964    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4965            int flags) {
4966        ArrayList<InstrumentationInfo> finalList =
4967            new ArrayList<InstrumentationInfo>();
4968
4969        // reader
4970        synchronized (mPackages) {
4971            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4972            while (i.hasNext()) {
4973                final PackageParser.Instrumentation p = i.next();
4974                if (targetPackage == null
4975                        || targetPackage.equals(p.info.targetPackage)) {
4976                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4977                            flags);
4978                    if (ii != null) {
4979                        finalList.add(ii);
4980                    }
4981                }
4982            }
4983        }
4984
4985        return finalList;
4986    }
4987
4988    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4989        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4990        if (overlays == null) {
4991            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4992            return;
4993        }
4994        for (PackageParser.Package opkg : overlays.values()) {
4995            // Not much to do if idmap fails: we already logged the error
4996            // and we certainly don't want to abort installation of pkg simply
4997            // because an overlay didn't fit properly. For these reasons,
4998            // ignore the return value of createIdmapForPackagePairLI.
4999            createIdmapForPackagePairLI(pkg, opkg);
5000        }
5001    }
5002
5003    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5004            PackageParser.Package opkg) {
5005        if (!opkg.mTrustedOverlay) {
5006            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5007                    opkg.baseCodePath + ": overlay not trusted");
5008            return false;
5009        }
5010        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5011        if (overlaySet == null) {
5012            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5013                    opkg.baseCodePath + " but target package has no known overlays");
5014            return false;
5015        }
5016        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5017        // TODO: generate idmap for split APKs
5018        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5019            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5020                    + opkg.baseCodePath);
5021            return false;
5022        }
5023        PackageParser.Package[] overlayArray =
5024            overlaySet.values().toArray(new PackageParser.Package[0]);
5025        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5026            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5027                return p1.mOverlayPriority - p2.mOverlayPriority;
5028            }
5029        };
5030        Arrays.sort(overlayArray, cmp);
5031
5032        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5033        int i = 0;
5034        for (PackageParser.Package p : overlayArray) {
5035            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5036        }
5037        return true;
5038    }
5039
5040    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5041        final File[] files = dir.listFiles();
5042        if (ArrayUtils.isEmpty(files)) {
5043            Log.d(TAG, "No files in app dir " + dir);
5044            return;
5045        }
5046
5047        if (DEBUG_PACKAGE_SCANNING) {
5048            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5049                    + " flags=0x" + Integer.toHexString(parseFlags));
5050        }
5051
5052        for (File file : files) {
5053            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5054                    && !PackageInstallerService.isStageName(file.getName());
5055            if (!isPackage) {
5056                // Ignore entries which are not packages
5057                continue;
5058            }
5059            try {
5060                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5061                        scanFlags, currentTime, null);
5062            } catch (PackageManagerException e) {
5063                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5064
5065                // Delete invalid userdata apps
5066                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5067                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5068                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5069                    if (file.isDirectory()) {
5070                        mInstaller.rmPackageDir(file.getAbsolutePath());
5071                    } else {
5072                        file.delete();
5073                    }
5074                }
5075            }
5076        }
5077    }
5078
5079    private static File getSettingsProblemFile() {
5080        File dataDir = Environment.getDataDirectory();
5081        File systemDir = new File(dataDir, "system");
5082        File fname = new File(systemDir, "uiderrors.txt");
5083        return fname;
5084    }
5085
5086    static void reportSettingsProblem(int priority, String msg) {
5087        logCriticalInfo(priority, msg);
5088    }
5089
5090    static void logCriticalInfo(int priority, String msg) {
5091        Slog.println(priority, TAG, msg);
5092        EventLogTags.writePmCriticalInfo(msg);
5093        try {
5094            File fname = getSettingsProblemFile();
5095            FileOutputStream out = new FileOutputStream(fname, true);
5096            PrintWriter pw = new FastPrintWriter(out);
5097            SimpleDateFormat formatter = new SimpleDateFormat();
5098            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5099            pw.println(dateString + ": " + msg);
5100            pw.close();
5101            FileUtils.setPermissions(
5102                    fname.toString(),
5103                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5104                    -1, -1);
5105        } catch (java.io.IOException e) {
5106        }
5107    }
5108
5109    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5110            PackageParser.Package pkg, File srcFile, int parseFlags)
5111            throws PackageManagerException {
5112        if (ps != null
5113                && ps.codePath.equals(srcFile)
5114                && ps.timeStamp == srcFile.lastModified()
5115                && !isCompatSignatureUpdateNeeded(pkg)
5116                && !isRecoverSignatureUpdateNeeded(pkg)) {
5117            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5118            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5119            ArraySet<PublicKey> signingKs;
5120            synchronized (mPackages) {
5121                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5122            }
5123            if (ps.signatures.mSignatures != null
5124                    && ps.signatures.mSignatures.length != 0
5125                    && signingKs != null) {
5126                // Optimization: reuse the existing cached certificates
5127                // if the package appears to be unchanged.
5128                pkg.mSignatures = ps.signatures.mSignatures;
5129                pkg.mSigningKeys = signingKs;
5130                return;
5131            }
5132
5133            Slog.w(TAG, "PackageSetting for " + ps.name
5134                    + " is missing signatures.  Collecting certs again to recover them.");
5135        } else {
5136            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5137        }
5138
5139        try {
5140            pp.collectCertificates(pkg, parseFlags);
5141            pp.collectManifestDigest(pkg);
5142        } catch (PackageParserException e) {
5143            throw PackageManagerException.from(e);
5144        }
5145    }
5146
5147    /*
5148     *  Scan a package and return the newly parsed package.
5149     *  Returns null in case of errors and the error code is stored in mLastScanError
5150     */
5151    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5152            long currentTime, UserHandle user) throws PackageManagerException {
5153        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5154        parseFlags |= mDefParseFlags;
5155        PackageParser pp = new PackageParser();
5156        pp.setSeparateProcesses(mSeparateProcesses);
5157        pp.setOnlyCoreApps(mOnlyCore);
5158        pp.setDisplayMetrics(mMetrics);
5159
5160        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5161            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5162        }
5163
5164        final PackageParser.Package pkg;
5165        try {
5166            pkg = pp.parsePackage(scanFile, parseFlags);
5167        } catch (PackageParserException e) {
5168            throw PackageManagerException.from(e);
5169        }
5170
5171        PackageSetting ps = null;
5172        PackageSetting updatedPkg;
5173        // reader
5174        synchronized (mPackages) {
5175            // Look to see if we already know about this package.
5176            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5177            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5178                // This package has been renamed to its original name.  Let's
5179                // use that.
5180                ps = mSettings.peekPackageLPr(oldName);
5181            }
5182            // If there was no original package, see one for the real package name.
5183            if (ps == null) {
5184                ps = mSettings.peekPackageLPr(pkg.packageName);
5185            }
5186            // Check to see if this package could be hiding/updating a system
5187            // package.  Must look for it either under the original or real
5188            // package name depending on our state.
5189            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5190            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5191        }
5192        boolean updatedPkgBetter = false;
5193        // First check if this is a system package that may involve an update
5194        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5195            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5196            // it needs to drop FLAG_PRIVILEGED.
5197            if (locationIsPrivileged(scanFile)) {
5198                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5199            } else {
5200                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5201            }
5202
5203            if (ps != null && !ps.codePath.equals(scanFile)) {
5204                // The path has changed from what was last scanned...  check the
5205                // version of the new path against what we have stored to determine
5206                // what to do.
5207                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5208                if (pkg.mVersionCode <= ps.versionCode) {
5209                    // The system package has been updated and the code path does not match
5210                    // Ignore entry. Skip it.
5211                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5212                            + " ignored: updated version " + ps.versionCode
5213                            + " better than this " + pkg.mVersionCode);
5214                    if (!updatedPkg.codePath.equals(scanFile)) {
5215                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5216                                + ps.name + " changing from " + updatedPkg.codePathString
5217                                + " to " + scanFile);
5218                        updatedPkg.codePath = scanFile;
5219                        updatedPkg.codePathString = scanFile.toString();
5220                        updatedPkg.resourcePath = scanFile;
5221                        updatedPkg.resourcePathString = scanFile.toString();
5222                    }
5223                    updatedPkg.pkg = pkg;
5224                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5225                } else {
5226                    // The current app on the system partition is better than
5227                    // what we have updated to on the data partition; switch
5228                    // back to the system partition version.
5229                    // At this point, its safely assumed that package installation for
5230                    // apps in system partition will go through. If not there won't be a working
5231                    // version of the app
5232                    // writer
5233                    synchronized (mPackages) {
5234                        // Just remove the loaded entries from package lists.
5235                        mPackages.remove(ps.name);
5236                    }
5237
5238                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5239                            + " reverting from " + ps.codePathString
5240                            + ": new version " + pkg.mVersionCode
5241                            + " better than installed " + ps.versionCode);
5242
5243                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5244                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5245                    synchronized (mInstallLock) {
5246                        args.cleanUpResourcesLI();
5247                    }
5248                    synchronized (mPackages) {
5249                        mSettings.enableSystemPackageLPw(ps.name);
5250                    }
5251                    updatedPkgBetter = true;
5252                }
5253            }
5254        }
5255
5256        if (updatedPkg != null) {
5257            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5258            // initially
5259            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5260
5261            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5262            // flag set initially
5263            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5264                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5265            }
5266        }
5267
5268        // Verify certificates against what was last scanned
5269        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5270
5271        /*
5272         * A new system app appeared, but we already had a non-system one of the
5273         * same name installed earlier.
5274         */
5275        boolean shouldHideSystemApp = false;
5276        if (updatedPkg == null && ps != null
5277                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5278            /*
5279             * Check to make sure the signatures match first. If they don't,
5280             * wipe the installed application and its data.
5281             */
5282            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5283                    != PackageManager.SIGNATURE_MATCH) {
5284                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5285                        + " signatures don't match existing userdata copy; removing");
5286                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5287                ps = null;
5288            } else {
5289                /*
5290                 * If the newly-added system app is an older version than the
5291                 * already installed version, hide it. It will be scanned later
5292                 * and re-added like an update.
5293                 */
5294                if (pkg.mVersionCode <= ps.versionCode) {
5295                    shouldHideSystemApp = true;
5296                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5297                            + " but new version " + pkg.mVersionCode + " better than installed "
5298                            + ps.versionCode + "; hiding system");
5299                } else {
5300                    /*
5301                     * The newly found system app is a newer version that the
5302                     * one previously installed. Simply remove the
5303                     * already-installed application and replace it with our own
5304                     * while keeping the application data.
5305                     */
5306                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5307                            + " reverting from " + ps.codePathString + ": new version "
5308                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5309                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5310                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5311                    synchronized (mInstallLock) {
5312                        args.cleanUpResourcesLI();
5313                    }
5314                }
5315            }
5316        }
5317
5318        // The apk is forward locked (not public) if its code and resources
5319        // are kept in different files. (except for app in either system or
5320        // vendor path).
5321        // TODO grab this value from PackageSettings
5322        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5323            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5324                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5325            }
5326        }
5327
5328        // TODO: extend to support forward-locked splits
5329        String resourcePath = null;
5330        String baseResourcePath = null;
5331        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5332            if (ps != null && ps.resourcePathString != null) {
5333                resourcePath = ps.resourcePathString;
5334                baseResourcePath = ps.resourcePathString;
5335            } else {
5336                // Should not happen at all. Just log an error.
5337                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5338            }
5339        } else {
5340            resourcePath = pkg.codePath;
5341            baseResourcePath = pkg.baseCodePath;
5342        }
5343
5344        // Set application objects path explicitly.
5345        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5346        pkg.applicationInfo.setCodePath(pkg.codePath);
5347        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5348        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5349        pkg.applicationInfo.setResourcePath(resourcePath);
5350        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5351        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5352
5353        // Note that we invoke the following method only if we are about to unpack an application
5354        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5355                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5356
5357        /*
5358         * If the system app should be overridden by a previously installed
5359         * data, hide the system app now and let the /data/app scan pick it up
5360         * again.
5361         */
5362        if (shouldHideSystemApp) {
5363            synchronized (mPackages) {
5364                /*
5365                 * We have to grant systems permissions before we hide, because
5366                 * grantPermissions will assume the package update is trying to
5367                 * expand its permissions.
5368                 */
5369                grantPermissionsLPw(pkg, true, pkg.packageName);
5370                mSettings.disableSystemPackageLPw(pkg.packageName);
5371            }
5372        }
5373
5374        return scannedPkg;
5375    }
5376
5377    private static String fixProcessName(String defProcessName,
5378            String processName, int uid) {
5379        if (processName == null) {
5380            return defProcessName;
5381        }
5382        return processName;
5383    }
5384
5385    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5386            throws PackageManagerException {
5387        if (pkgSetting.signatures.mSignatures != null) {
5388            // Already existing package. Make sure signatures match
5389            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5390                    == PackageManager.SIGNATURE_MATCH;
5391            if (!match) {
5392                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5393                        == PackageManager.SIGNATURE_MATCH;
5394            }
5395            if (!match) {
5396                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5397                        == PackageManager.SIGNATURE_MATCH;
5398            }
5399            if (!match) {
5400                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5401                        + pkg.packageName + " signatures do not match the "
5402                        + "previously installed version; ignoring!");
5403            }
5404        }
5405
5406        // Check for shared user signatures
5407        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5408            // Already existing package. Make sure signatures match
5409            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5410                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5411            if (!match) {
5412                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5413                        == PackageManager.SIGNATURE_MATCH;
5414            }
5415            if (!match) {
5416                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5417                        == PackageManager.SIGNATURE_MATCH;
5418            }
5419            if (!match) {
5420                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5421                        "Package " + pkg.packageName
5422                        + " has no signatures that match those in shared user "
5423                        + pkgSetting.sharedUser.name + "; ignoring!");
5424            }
5425        }
5426    }
5427
5428    /**
5429     * Enforces that only the system UID or root's UID can call a method exposed
5430     * via Binder.
5431     *
5432     * @param message used as message if SecurityException is thrown
5433     * @throws SecurityException if the caller is not system or root
5434     */
5435    private static final void enforceSystemOrRoot(String message) {
5436        final int uid = Binder.getCallingUid();
5437        if (uid != Process.SYSTEM_UID && uid != 0) {
5438            throw new SecurityException(message);
5439        }
5440    }
5441
5442    @Override
5443    public void performBootDexOpt() {
5444        enforceSystemOrRoot("Only the system can request dexopt be performed");
5445
5446        // Before everything else, see whether we need to fstrim.
5447        try {
5448            IMountService ms = PackageHelper.getMountService();
5449            if (ms != null) {
5450                final boolean isUpgrade = isUpgrade();
5451                boolean doTrim = isUpgrade;
5452                if (doTrim) {
5453                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5454                } else {
5455                    final long interval = android.provider.Settings.Global.getLong(
5456                            mContext.getContentResolver(),
5457                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5458                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5459                    if (interval > 0) {
5460                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5461                        if (timeSinceLast > interval) {
5462                            doTrim = true;
5463                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5464                                    + "; running immediately");
5465                        }
5466                    }
5467                }
5468                if (doTrim) {
5469                    if (!isFirstBoot()) {
5470                        try {
5471                            ActivityManagerNative.getDefault().showBootMessage(
5472                                    mContext.getResources().getString(
5473                                            R.string.android_upgrading_fstrim), true);
5474                        } catch (RemoteException e) {
5475                        }
5476                    }
5477                    ms.runMaintenance();
5478                }
5479            } else {
5480                Slog.e(TAG, "Mount service unavailable!");
5481            }
5482        } catch (RemoteException e) {
5483            // Can't happen; MountService is local
5484        }
5485
5486        final ArraySet<PackageParser.Package> pkgs;
5487        synchronized (mPackages) {
5488            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5489        }
5490
5491        if (pkgs != null) {
5492            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5493            // in case the device runs out of space.
5494            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5495            // Give priority to core apps.
5496            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5497                PackageParser.Package pkg = it.next();
5498                if (pkg.coreApp) {
5499                    if (DEBUG_DEXOPT) {
5500                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5501                    }
5502                    sortedPkgs.add(pkg);
5503                    it.remove();
5504                }
5505            }
5506            // Give priority to system apps that listen for pre boot complete.
5507            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5508            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5509            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5510                PackageParser.Package pkg = it.next();
5511                if (pkgNames.contains(pkg.packageName)) {
5512                    if (DEBUG_DEXOPT) {
5513                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5514                    }
5515                    sortedPkgs.add(pkg);
5516                    it.remove();
5517                }
5518            }
5519            // Give priority to system apps.
5520            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5521                PackageParser.Package pkg = it.next();
5522                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5523                    if (DEBUG_DEXOPT) {
5524                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5525                    }
5526                    sortedPkgs.add(pkg);
5527                    it.remove();
5528                }
5529            }
5530            // Give priority to updated system apps.
5531            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5532                PackageParser.Package pkg = it.next();
5533                if (pkg.isUpdatedSystemApp()) {
5534                    if (DEBUG_DEXOPT) {
5535                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5536                    }
5537                    sortedPkgs.add(pkg);
5538                    it.remove();
5539                }
5540            }
5541            // Give priority to apps that listen for boot complete.
5542            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5543            pkgNames = getPackageNamesForIntent(intent);
5544            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5545                PackageParser.Package pkg = it.next();
5546                if (pkgNames.contains(pkg.packageName)) {
5547                    if (DEBUG_DEXOPT) {
5548                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5549                    }
5550                    sortedPkgs.add(pkg);
5551                    it.remove();
5552                }
5553            }
5554            // Filter out packages that aren't recently used.
5555            filterRecentlyUsedApps(pkgs);
5556            // Add all remaining apps.
5557            for (PackageParser.Package pkg : pkgs) {
5558                if (DEBUG_DEXOPT) {
5559                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5560                }
5561                sortedPkgs.add(pkg);
5562            }
5563
5564            // If we want to be lazy, filter everything that wasn't recently used.
5565            if (mLazyDexOpt) {
5566                filterRecentlyUsedApps(sortedPkgs);
5567            }
5568
5569            int i = 0;
5570            int total = sortedPkgs.size();
5571            File dataDir = Environment.getDataDirectory();
5572            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5573            if (lowThreshold == 0) {
5574                throw new IllegalStateException("Invalid low memory threshold");
5575            }
5576            for (PackageParser.Package pkg : sortedPkgs) {
5577                long usableSpace = dataDir.getUsableSpace();
5578                if (usableSpace < lowThreshold) {
5579                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5580                    break;
5581                }
5582                performBootDexOpt(pkg, ++i, total);
5583            }
5584        }
5585    }
5586
5587    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5588        // Filter out packages that aren't recently used.
5589        //
5590        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5591        // should do a full dexopt.
5592        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5593            int total = pkgs.size();
5594            int skipped = 0;
5595            long now = System.currentTimeMillis();
5596            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5597                PackageParser.Package pkg = i.next();
5598                long then = pkg.mLastPackageUsageTimeInMills;
5599                if (then + mDexOptLRUThresholdInMills < now) {
5600                    if (DEBUG_DEXOPT) {
5601                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5602                              ((then == 0) ? "never" : new Date(then)));
5603                    }
5604                    i.remove();
5605                    skipped++;
5606                }
5607            }
5608            if (DEBUG_DEXOPT) {
5609                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5610            }
5611        }
5612    }
5613
5614    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5615        List<ResolveInfo> ris = null;
5616        try {
5617            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5618                    intent, null, 0, UserHandle.USER_OWNER);
5619        } catch (RemoteException e) {
5620        }
5621        ArraySet<String> pkgNames = new ArraySet<String>();
5622        if (ris != null) {
5623            for (ResolveInfo ri : ris) {
5624                pkgNames.add(ri.activityInfo.packageName);
5625            }
5626        }
5627        return pkgNames;
5628    }
5629
5630    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5631        if (DEBUG_DEXOPT) {
5632            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5633        }
5634        if (!isFirstBoot()) {
5635            try {
5636                ActivityManagerNative.getDefault().showBootMessage(
5637                        mContext.getResources().getString(R.string.android_upgrading_apk,
5638                                curr, total), true);
5639            } catch (RemoteException e) {
5640            }
5641        }
5642        PackageParser.Package p = pkg;
5643        synchronized (mInstallLock) {
5644            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5645                    false /* force dex */, false /* defer */, true /* include dependencies */);
5646        }
5647    }
5648
5649    @Override
5650    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5651        return performDexOpt(packageName, instructionSet, false);
5652    }
5653
5654    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5655        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5656        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5657        if (!dexopt && !updateUsage) {
5658            // We aren't going to dexopt or update usage, so bail early.
5659            return false;
5660        }
5661        PackageParser.Package p;
5662        final String targetInstructionSet;
5663        synchronized (mPackages) {
5664            p = mPackages.get(packageName);
5665            if (p == null) {
5666                return false;
5667            }
5668            if (updateUsage) {
5669                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5670            }
5671            mPackageUsage.write(false);
5672            if (!dexopt) {
5673                // We aren't going to dexopt, so bail early.
5674                return false;
5675            }
5676
5677            targetInstructionSet = instructionSet != null ? instructionSet :
5678                    getPrimaryInstructionSet(p.applicationInfo);
5679            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5680                return false;
5681            }
5682        }
5683
5684        synchronized (mInstallLock) {
5685            final String[] instructionSets = new String[] { targetInstructionSet };
5686            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5687                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5688            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5689        }
5690    }
5691
5692    public ArraySet<String> getPackagesThatNeedDexOpt() {
5693        ArraySet<String> pkgs = null;
5694        synchronized (mPackages) {
5695            for (PackageParser.Package p : mPackages.values()) {
5696                if (DEBUG_DEXOPT) {
5697                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5698                }
5699                if (!p.mDexOptPerformed.isEmpty()) {
5700                    continue;
5701                }
5702                if (pkgs == null) {
5703                    pkgs = new ArraySet<String>();
5704                }
5705                pkgs.add(p.packageName);
5706            }
5707        }
5708        return pkgs;
5709    }
5710
5711    public void shutdown() {
5712        mPackageUsage.write(true);
5713    }
5714
5715    @Override
5716    public void forceDexOpt(String packageName) {
5717        enforceSystemOrRoot("forceDexOpt");
5718
5719        PackageParser.Package pkg;
5720        synchronized (mPackages) {
5721            pkg = mPackages.get(packageName);
5722            if (pkg == null) {
5723                throw new IllegalArgumentException("Missing package: " + packageName);
5724            }
5725        }
5726
5727        synchronized (mInstallLock) {
5728            final String[] instructionSets = new String[] {
5729                    getPrimaryInstructionSet(pkg.applicationInfo) };
5730            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5731                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5732            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5733                throw new IllegalStateException("Failed to dexopt: " + res);
5734            }
5735        }
5736    }
5737
5738    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5739        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5740            Slog.w(TAG, "Unable to update from " + oldPkg.name
5741                    + " to " + newPkg.packageName
5742                    + ": old package not in system partition");
5743            return false;
5744        } else if (mPackages.get(oldPkg.name) != null) {
5745            Slog.w(TAG, "Unable to update from " + oldPkg.name
5746                    + " to " + newPkg.packageName
5747                    + ": old package still exists");
5748            return false;
5749        }
5750        return true;
5751    }
5752
5753    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5754        int[] users = sUserManager.getUserIds();
5755        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5756        if (res < 0) {
5757            return res;
5758        }
5759        for (int user : users) {
5760            if (user != 0) {
5761                res = mInstaller.createUserData(volumeUuid, packageName,
5762                        UserHandle.getUid(user, uid), user, seinfo);
5763                if (res < 0) {
5764                    return res;
5765                }
5766            }
5767        }
5768        return res;
5769    }
5770
5771    private int removeDataDirsLI(String volumeUuid, String packageName) {
5772        int[] users = sUserManager.getUserIds();
5773        int res = 0;
5774        for (int user : users) {
5775            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5776            if (resInner < 0) {
5777                res = resInner;
5778            }
5779        }
5780
5781        return res;
5782    }
5783
5784    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5785        int[] users = sUserManager.getUserIds();
5786        int res = 0;
5787        for (int user : users) {
5788            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5789            if (resInner < 0) {
5790                res = resInner;
5791            }
5792        }
5793        return res;
5794    }
5795
5796    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5797            PackageParser.Package changingLib) {
5798        if (file.path != null) {
5799            usesLibraryFiles.add(file.path);
5800            return;
5801        }
5802        PackageParser.Package p = mPackages.get(file.apk);
5803        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5804            // If we are doing this while in the middle of updating a library apk,
5805            // then we need to make sure to use that new apk for determining the
5806            // dependencies here.  (We haven't yet finished committing the new apk
5807            // to the package manager state.)
5808            if (p == null || p.packageName.equals(changingLib.packageName)) {
5809                p = changingLib;
5810            }
5811        }
5812        if (p != null) {
5813            usesLibraryFiles.addAll(p.getAllCodePaths());
5814        }
5815    }
5816
5817    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5818            PackageParser.Package changingLib) throws PackageManagerException {
5819        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5820            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5821            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5822            for (int i=0; i<N; i++) {
5823                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5824                if (file == null) {
5825                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5826                            "Package " + pkg.packageName + " requires unavailable shared library "
5827                            + pkg.usesLibraries.get(i) + "; failing!");
5828                }
5829                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5830            }
5831            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5832            for (int i=0; i<N; i++) {
5833                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5834                if (file == null) {
5835                    Slog.w(TAG, "Package " + pkg.packageName
5836                            + " desires unavailable shared library "
5837                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5838                } else {
5839                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5840                }
5841            }
5842            N = usesLibraryFiles.size();
5843            if (N > 0) {
5844                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5845            } else {
5846                pkg.usesLibraryFiles = null;
5847            }
5848        }
5849    }
5850
5851    private static boolean hasString(List<String> list, List<String> which) {
5852        if (list == null) {
5853            return false;
5854        }
5855        for (int i=list.size()-1; i>=0; i--) {
5856            for (int j=which.size()-1; j>=0; j--) {
5857                if (which.get(j).equals(list.get(i))) {
5858                    return true;
5859                }
5860            }
5861        }
5862        return false;
5863    }
5864
5865    private void updateAllSharedLibrariesLPw() {
5866        for (PackageParser.Package pkg : mPackages.values()) {
5867            try {
5868                updateSharedLibrariesLPw(pkg, null);
5869            } catch (PackageManagerException e) {
5870                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5871            }
5872        }
5873    }
5874
5875    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5876            PackageParser.Package changingPkg) {
5877        ArrayList<PackageParser.Package> res = null;
5878        for (PackageParser.Package pkg : mPackages.values()) {
5879            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5880                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5881                if (res == null) {
5882                    res = new ArrayList<PackageParser.Package>();
5883                }
5884                res.add(pkg);
5885                try {
5886                    updateSharedLibrariesLPw(pkg, changingPkg);
5887                } catch (PackageManagerException e) {
5888                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5889                }
5890            }
5891        }
5892        return res;
5893    }
5894
5895    /**
5896     * Derive the value of the {@code cpuAbiOverride} based on the provided
5897     * value and an optional stored value from the package settings.
5898     */
5899    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5900        String cpuAbiOverride = null;
5901
5902        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5903            cpuAbiOverride = null;
5904        } else if (abiOverride != null) {
5905            cpuAbiOverride = abiOverride;
5906        } else if (settings != null) {
5907            cpuAbiOverride = settings.cpuAbiOverrideString;
5908        }
5909
5910        return cpuAbiOverride;
5911    }
5912
5913    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5914            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5915        boolean success = false;
5916        try {
5917            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5918                    currentTime, user);
5919            success = true;
5920            return res;
5921        } finally {
5922            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5923                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
5924            }
5925        }
5926    }
5927
5928    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5929            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5930        final File scanFile = new File(pkg.codePath);
5931        if (pkg.applicationInfo.getCodePath() == null ||
5932                pkg.applicationInfo.getResourcePath() == null) {
5933            // Bail out. The resource and code paths haven't been set.
5934            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5935                    "Code and resource paths haven't been set correctly");
5936        }
5937
5938        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5939            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5940        } else {
5941            // Only allow system apps to be flagged as core apps.
5942            pkg.coreApp = false;
5943        }
5944
5945        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5946            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5947        }
5948
5949        if (mCustomResolverComponentName != null &&
5950                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5951            setUpCustomResolverActivity(pkg);
5952        }
5953
5954        if (pkg.packageName.equals("android")) {
5955            synchronized (mPackages) {
5956                if (mAndroidApplication != null) {
5957                    Slog.w(TAG, "*************************************************");
5958                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5959                    Slog.w(TAG, " file=" + scanFile);
5960                    Slog.w(TAG, "*************************************************");
5961                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5962                            "Core android package being redefined.  Skipping.");
5963                }
5964
5965                // Set up information for our fall-back user intent resolution activity.
5966                mPlatformPackage = pkg;
5967                pkg.mVersionCode = mSdkVersion;
5968                mAndroidApplication = pkg.applicationInfo;
5969
5970                if (!mResolverReplaced) {
5971                    mResolveActivity.applicationInfo = mAndroidApplication;
5972                    mResolveActivity.name = ResolverActivity.class.getName();
5973                    mResolveActivity.packageName = mAndroidApplication.packageName;
5974                    mResolveActivity.processName = "system:ui";
5975                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5976                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5977                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5978                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5979                    mResolveActivity.exported = true;
5980                    mResolveActivity.enabled = true;
5981                    mResolveInfo.activityInfo = mResolveActivity;
5982                    mResolveInfo.priority = 0;
5983                    mResolveInfo.preferredOrder = 0;
5984                    mResolveInfo.match = 0;
5985                    mResolveComponentName = new ComponentName(
5986                            mAndroidApplication.packageName, mResolveActivity.name);
5987                }
5988            }
5989        }
5990
5991        if (DEBUG_PACKAGE_SCANNING) {
5992            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5993                Log.d(TAG, "Scanning package " + pkg.packageName);
5994        }
5995
5996        if (mPackages.containsKey(pkg.packageName)
5997                || mSharedLibraries.containsKey(pkg.packageName)) {
5998            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5999                    "Application package " + pkg.packageName
6000                    + " already installed.  Skipping duplicate.");
6001        }
6002
6003        // If we're only installing presumed-existing packages, require that the
6004        // scanned APK is both already known and at the path previously established
6005        // for it.  Previously unknown packages we pick up normally, but if we have an
6006        // a priori expectation about this package's install presence, enforce it.
6007        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6008            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6009            if (known != null) {
6010                if (DEBUG_PACKAGE_SCANNING) {
6011                    Log.d(TAG, "Examining " + pkg.codePath
6012                            + " and requiring known paths " + known.codePathString
6013                            + " & " + known.resourcePathString);
6014                }
6015                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6016                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6017                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6018                            "Application package " + pkg.packageName
6019                            + " found at " + pkg.applicationInfo.getCodePath()
6020                            + " but expected at " + known.codePathString + "; ignoring.");
6021                }
6022            }
6023        }
6024
6025        // Initialize package source and resource directories
6026        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6027        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6028
6029        SharedUserSetting suid = null;
6030        PackageSetting pkgSetting = null;
6031
6032        if (!isSystemApp(pkg)) {
6033            // Only system apps can use these features.
6034            pkg.mOriginalPackages = null;
6035            pkg.mRealPackage = null;
6036            pkg.mAdoptPermissions = null;
6037        }
6038
6039        // writer
6040        synchronized (mPackages) {
6041            if (pkg.mSharedUserId != null) {
6042                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6043                if (suid == null) {
6044                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6045                            "Creating application package " + pkg.packageName
6046                            + " for shared user failed");
6047                }
6048                if (DEBUG_PACKAGE_SCANNING) {
6049                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6050                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6051                                + "): packages=" + suid.packages);
6052                }
6053            }
6054
6055            // Check if we are renaming from an original package name.
6056            PackageSetting origPackage = null;
6057            String realName = null;
6058            if (pkg.mOriginalPackages != null) {
6059                // This package may need to be renamed to a previously
6060                // installed name.  Let's check on that...
6061                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6062                if (pkg.mOriginalPackages.contains(renamed)) {
6063                    // This package had originally been installed as the
6064                    // original name, and we have already taken care of
6065                    // transitioning to the new one.  Just update the new
6066                    // one to continue using the old name.
6067                    realName = pkg.mRealPackage;
6068                    if (!pkg.packageName.equals(renamed)) {
6069                        // Callers into this function may have already taken
6070                        // care of renaming the package; only do it here if
6071                        // it is not already done.
6072                        pkg.setPackageName(renamed);
6073                    }
6074
6075                } else {
6076                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6077                        if ((origPackage = mSettings.peekPackageLPr(
6078                                pkg.mOriginalPackages.get(i))) != null) {
6079                            // We do have the package already installed under its
6080                            // original name...  should we use it?
6081                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6082                                // New package is not compatible with original.
6083                                origPackage = null;
6084                                continue;
6085                            } else if (origPackage.sharedUser != null) {
6086                                // Make sure uid is compatible between packages.
6087                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6088                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6089                                            + " to " + pkg.packageName + ": old uid "
6090                                            + origPackage.sharedUser.name
6091                                            + " differs from " + pkg.mSharedUserId);
6092                                    origPackage = null;
6093                                    continue;
6094                                }
6095                            } else {
6096                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6097                                        + pkg.packageName + " to old name " + origPackage.name);
6098                            }
6099                            break;
6100                        }
6101                    }
6102                }
6103            }
6104
6105            if (mTransferedPackages.contains(pkg.packageName)) {
6106                Slog.w(TAG, "Package " + pkg.packageName
6107                        + " was transferred to another, but its .apk remains");
6108            }
6109
6110            // Just create the setting, don't add it yet. For already existing packages
6111            // the PkgSetting exists already and doesn't have to be created.
6112            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6113                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6114                    pkg.applicationInfo.primaryCpuAbi,
6115                    pkg.applicationInfo.secondaryCpuAbi,
6116                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6117                    user, false);
6118            if (pkgSetting == null) {
6119                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6120                        "Creating application package " + pkg.packageName + " failed");
6121            }
6122
6123            if (pkgSetting.origPackage != null) {
6124                // If we are first transitioning from an original package,
6125                // fix up the new package's name now.  We need to do this after
6126                // looking up the package under its new name, so getPackageLP
6127                // can take care of fiddling things correctly.
6128                pkg.setPackageName(origPackage.name);
6129
6130                // File a report about this.
6131                String msg = "New package " + pkgSetting.realName
6132                        + " renamed to replace old package " + pkgSetting.name;
6133                reportSettingsProblem(Log.WARN, msg);
6134
6135                // Make a note of it.
6136                mTransferedPackages.add(origPackage.name);
6137
6138                // No longer need to retain this.
6139                pkgSetting.origPackage = null;
6140            }
6141
6142            if (realName != null) {
6143                // Make a note of it.
6144                mTransferedPackages.add(pkg.packageName);
6145            }
6146
6147            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6148                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6149            }
6150
6151            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6152                // Check all shared libraries and map to their actual file path.
6153                // We only do this here for apps not on a system dir, because those
6154                // are the only ones that can fail an install due to this.  We
6155                // will take care of the system apps by updating all of their
6156                // library paths after the scan is done.
6157                updateSharedLibrariesLPw(pkg, null);
6158            }
6159
6160            if (mFoundPolicyFile) {
6161                SELinuxMMAC.assignSeinfoValue(pkg);
6162            }
6163
6164            pkg.applicationInfo.uid = pkgSetting.appId;
6165            pkg.mExtras = pkgSetting;
6166            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6167                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6168                    // We just determined the app is signed correctly, so bring
6169                    // over the latest parsed certs.
6170                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6171                } else {
6172                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6173                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6174                                "Package " + pkg.packageName + " upgrade keys do not match the "
6175                                + "previously installed version");
6176                    } else {
6177                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6178                        String msg = "System package " + pkg.packageName
6179                            + " signature changed; retaining data.";
6180                        reportSettingsProblem(Log.WARN, msg);
6181                    }
6182                }
6183            } else {
6184                try {
6185                    verifySignaturesLP(pkgSetting, pkg);
6186                    // We just determined the app is signed correctly, so bring
6187                    // over the latest parsed certs.
6188                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6189                } catch (PackageManagerException e) {
6190                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6191                        throw e;
6192                    }
6193                    // The signature has changed, but this package is in the system
6194                    // image...  let's recover!
6195                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6196                    // However...  if this package is part of a shared user, but it
6197                    // doesn't match the signature of the shared user, let's fail.
6198                    // What this means is that you can't change the signatures
6199                    // associated with an overall shared user, which doesn't seem all
6200                    // that unreasonable.
6201                    if (pkgSetting.sharedUser != null) {
6202                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6203                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6204                            throw new PackageManagerException(
6205                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6206                                            "Signature mismatch for shared user : "
6207                                            + pkgSetting.sharedUser);
6208                        }
6209                    }
6210                    // File a report about this.
6211                    String msg = "System package " + pkg.packageName
6212                        + " signature changed; retaining data.";
6213                    reportSettingsProblem(Log.WARN, msg);
6214                }
6215            }
6216            // Verify that this new package doesn't have any content providers
6217            // that conflict with existing packages.  Only do this if the
6218            // package isn't already installed, since we don't want to break
6219            // things that are installed.
6220            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6221                final int N = pkg.providers.size();
6222                int i;
6223                for (i=0; i<N; i++) {
6224                    PackageParser.Provider p = pkg.providers.get(i);
6225                    if (p.info.authority != null) {
6226                        String names[] = p.info.authority.split(";");
6227                        for (int j = 0; j < names.length; j++) {
6228                            if (mProvidersByAuthority.containsKey(names[j])) {
6229                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6230                                final String otherPackageName =
6231                                        ((other != null && other.getComponentName() != null) ?
6232                                                other.getComponentName().getPackageName() : "?");
6233                                throw new PackageManagerException(
6234                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6235                                                "Can't install because provider name " + names[j]
6236                                                + " (in package " + pkg.applicationInfo.packageName
6237                                                + ") is already used by " + otherPackageName);
6238                            }
6239                        }
6240                    }
6241                }
6242            }
6243
6244            if (pkg.mAdoptPermissions != null) {
6245                // This package wants to adopt ownership of permissions from
6246                // another package.
6247                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6248                    final String origName = pkg.mAdoptPermissions.get(i);
6249                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6250                    if (orig != null) {
6251                        if (verifyPackageUpdateLPr(orig, pkg)) {
6252                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6253                                    + pkg.packageName);
6254                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6255                        }
6256                    }
6257                }
6258            }
6259        }
6260
6261        final String pkgName = pkg.packageName;
6262
6263        final long scanFileTime = scanFile.lastModified();
6264        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6265        pkg.applicationInfo.processName = fixProcessName(
6266                pkg.applicationInfo.packageName,
6267                pkg.applicationInfo.processName,
6268                pkg.applicationInfo.uid);
6269
6270        File dataPath;
6271        if (mPlatformPackage == pkg) {
6272            // The system package is special.
6273            dataPath = new File(Environment.getDataDirectory(), "system");
6274
6275            pkg.applicationInfo.dataDir = dataPath.getPath();
6276
6277        } else {
6278            // This is a normal package, need to make its data directory.
6279            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6280                    UserHandle.USER_OWNER);
6281
6282            boolean uidError = false;
6283            if (dataPath.exists()) {
6284                int currentUid = 0;
6285                try {
6286                    StructStat stat = Os.stat(dataPath.getPath());
6287                    currentUid = stat.st_uid;
6288                } catch (ErrnoException e) {
6289                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6290                }
6291
6292                // If we have mismatched owners for the data path, we have a problem.
6293                if (currentUid != pkg.applicationInfo.uid) {
6294                    boolean recovered = false;
6295                    if (currentUid == 0) {
6296                        // The directory somehow became owned by root.  Wow.
6297                        // This is probably because the system was stopped while
6298                        // installd was in the middle of messing with its libs
6299                        // directory.  Ask installd to fix that.
6300                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6301                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6302                        if (ret >= 0) {
6303                            recovered = true;
6304                            String msg = "Package " + pkg.packageName
6305                                    + " unexpectedly changed to uid 0; recovered to " +
6306                                    + pkg.applicationInfo.uid;
6307                            reportSettingsProblem(Log.WARN, msg);
6308                        }
6309                    }
6310                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6311                            || (scanFlags&SCAN_BOOTING) != 0)) {
6312                        // If this is a system app, we can at least delete its
6313                        // current data so the application will still work.
6314                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6315                        if (ret >= 0) {
6316                            // TODO: Kill the processes first
6317                            // Old data gone!
6318                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6319                                    ? "System package " : "Third party package ";
6320                            String msg = prefix + pkg.packageName
6321                                    + " has changed from uid: "
6322                                    + currentUid + " to "
6323                                    + pkg.applicationInfo.uid + "; old data erased";
6324                            reportSettingsProblem(Log.WARN, msg);
6325                            recovered = true;
6326
6327                            // And now re-install the app.
6328                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6329                                    pkg.applicationInfo.seinfo);
6330                            if (ret == -1) {
6331                                // Ack should not happen!
6332                                msg = prefix + pkg.packageName
6333                                        + " could not have data directory re-created after delete.";
6334                                reportSettingsProblem(Log.WARN, msg);
6335                                throw new PackageManagerException(
6336                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6337                            }
6338                        }
6339                        if (!recovered) {
6340                            mHasSystemUidErrors = true;
6341                        }
6342                    } else if (!recovered) {
6343                        // If we allow this install to proceed, we will be broken.
6344                        // Abort, abort!
6345                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6346                                "scanPackageLI");
6347                    }
6348                    if (!recovered) {
6349                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6350                            + pkg.applicationInfo.uid + "/fs_"
6351                            + currentUid;
6352                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6353                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6354                        String msg = "Package " + pkg.packageName
6355                                + " has mismatched uid: "
6356                                + currentUid + " on disk, "
6357                                + pkg.applicationInfo.uid + " in settings";
6358                        // writer
6359                        synchronized (mPackages) {
6360                            mSettings.mReadMessages.append(msg);
6361                            mSettings.mReadMessages.append('\n');
6362                            uidError = true;
6363                            if (!pkgSetting.uidError) {
6364                                reportSettingsProblem(Log.ERROR, msg);
6365                            }
6366                        }
6367                    }
6368                }
6369                pkg.applicationInfo.dataDir = dataPath.getPath();
6370                if (mShouldRestoreconData) {
6371                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6372                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6373                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6374                }
6375            } else {
6376                if (DEBUG_PACKAGE_SCANNING) {
6377                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6378                        Log.v(TAG, "Want this data dir: " + dataPath);
6379                }
6380                //invoke installer to do the actual installation
6381                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6382                        pkg.applicationInfo.seinfo);
6383                if (ret < 0) {
6384                    // Error from installer
6385                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6386                            "Unable to create data dirs [errorCode=" + ret + "]");
6387                }
6388
6389                if (dataPath.exists()) {
6390                    pkg.applicationInfo.dataDir = dataPath.getPath();
6391                } else {
6392                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6393                    pkg.applicationInfo.dataDir = null;
6394                }
6395            }
6396
6397            pkgSetting.uidError = uidError;
6398        }
6399
6400        final String path = scanFile.getPath();
6401        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6402
6403        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6404            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6405
6406            // Some system apps still use directory structure for native libraries
6407            // in which case we might end up not detecting abi solely based on apk
6408            // structure. Try to detect abi based on directory structure.
6409            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6410                    pkg.applicationInfo.primaryCpuAbi == null) {
6411                setBundledAppAbisAndRoots(pkg, pkgSetting);
6412                setNativeLibraryPaths(pkg);
6413            }
6414
6415        } else {
6416            if ((scanFlags & SCAN_MOVE) != 0) {
6417                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6418                // but we already have this packages package info in the PackageSetting. We just
6419                // use that and derive the native library path based on the new codepath.
6420                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6421                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6422            }
6423
6424            // Set native library paths again. For moves, the path will be updated based on the
6425            // ABIs we've determined above. For non-moves, the path will be updated based on the
6426            // ABIs we determined during compilation, but the path will depend on the final
6427            // package path (after the rename away from the stage path).
6428            setNativeLibraryPaths(pkg);
6429        }
6430
6431        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6432        final int[] userIds = sUserManager.getUserIds();
6433        synchronized (mInstallLock) {
6434            // Create a native library symlink only if we have native libraries
6435            // and if the native libraries are 32 bit libraries. We do not provide
6436            // this symlink for 64 bit libraries.
6437            if (pkg.applicationInfo.primaryCpuAbi != null &&
6438                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6439                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6440                for (int userId : userIds) {
6441                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6442                            nativeLibPath, userId) < 0) {
6443                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6444                                "Failed linking native library dir (user=" + userId + ")");
6445                    }
6446                }
6447            }
6448        }
6449
6450        // This is a special case for the "system" package, where the ABI is
6451        // dictated by the zygote configuration (and init.rc). We should keep track
6452        // of this ABI so that we can deal with "normal" applications that run under
6453        // the same UID correctly.
6454        if (mPlatformPackage == pkg) {
6455            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6456                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6457        }
6458
6459        // If there's a mismatch between the abi-override in the package setting
6460        // and the abiOverride specified for the install. Warn about this because we
6461        // would've already compiled the app without taking the package setting into
6462        // account.
6463        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6464            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6465                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6466                        " for package: " + pkg.packageName);
6467            }
6468        }
6469
6470        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6471        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6472        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6473
6474        // Copy the derived override back to the parsed package, so that we can
6475        // update the package settings accordingly.
6476        pkg.cpuAbiOverride = cpuAbiOverride;
6477
6478        if (DEBUG_ABI_SELECTION) {
6479            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6480                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6481                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6482        }
6483
6484        // Push the derived path down into PackageSettings so we know what to
6485        // clean up at uninstall time.
6486        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6487
6488        if (DEBUG_ABI_SELECTION) {
6489            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6490                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6491                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6492        }
6493
6494        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6495            // We don't do this here during boot because we can do it all
6496            // at once after scanning all existing packages.
6497            //
6498            // We also do this *before* we perform dexopt on this package, so that
6499            // we can avoid redundant dexopts, and also to make sure we've got the
6500            // code and package path correct.
6501            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6502                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6503        }
6504
6505        if ((scanFlags & SCAN_NO_DEX) == 0) {
6506            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6507                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6508            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6509                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6510            }
6511        }
6512        if (mFactoryTest && pkg.requestedPermissions.contains(
6513                android.Manifest.permission.FACTORY_TEST)) {
6514            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6515        }
6516
6517        ArrayList<PackageParser.Package> clientLibPkgs = null;
6518
6519        // writer
6520        synchronized (mPackages) {
6521            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6522                // Only system apps can add new shared libraries.
6523                if (pkg.libraryNames != null) {
6524                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6525                        String name = pkg.libraryNames.get(i);
6526                        boolean allowed = false;
6527                        if (pkg.isUpdatedSystemApp()) {
6528                            // New library entries can only be added through the
6529                            // system image.  This is important to get rid of a lot
6530                            // of nasty edge cases: for example if we allowed a non-
6531                            // system update of the app to add a library, then uninstalling
6532                            // the update would make the library go away, and assumptions
6533                            // we made such as through app install filtering would now
6534                            // have allowed apps on the device which aren't compatible
6535                            // with it.  Better to just have the restriction here, be
6536                            // conservative, and create many fewer cases that can negatively
6537                            // impact the user experience.
6538                            final PackageSetting sysPs = mSettings
6539                                    .getDisabledSystemPkgLPr(pkg.packageName);
6540                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6541                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6542                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6543                                        allowed = true;
6544                                        allowed = true;
6545                                        break;
6546                                    }
6547                                }
6548                            }
6549                        } else {
6550                            allowed = true;
6551                        }
6552                        if (allowed) {
6553                            if (!mSharedLibraries.containsKey(name)) {
6554                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6555                            } else if (!name.equals(pkg.packageName)) {
6556                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6557                                        + name + " already exists; skipping");
6558                            }
6559                        } else {
6560                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6561                                    + name + " that is not declared on system image; skipping");
6562                        }
6563                    }
6564                    if ((scanFlags&SCAN_BOOTING) == 0) {
6565                        // If we are not booting, we need to update any applications
6566                        // that are clients of our shared library.  If we are booting,
6567                        // this will all be done once the scan is complete.
6568                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6569                    }
6570                }
6571            }
6572        }
6573
6574        // We also need to dexopt any apps that are dependent on this library.  Note that
6575        // if these fail, we should abort the install since installing the library will
6576        // result in some apps being broken.
6577        if (clientLibPkgs != null) {
6578            if ((scanFlags & SCAN_NO_DEX) == 0) {
6579                for (int i = 0; i < clientLibPkgs.size(); i++) {
6580                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6581                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6582                            null /* instruction sets */, forceDex,
6583                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6584                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6585                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6586                                "scanPackageLI failed to dexopt clientLibPkgs");
6587                    }
6588                }
6589            }
6590        }
6591
6592        // Also need to kill any apps that are dependent on the library.
6593        if (clientLibPkgs != null) {
6594            for (int i=0; i<clientLibPkgs.size(); i++) {
6595                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6596                killApplication(clientPkg.applicationInfo.packageName,
6597                        clientPkg.applicationInfo.uid, "update lib");
6598            }
6599        }
6600
6601        // Make sure we're not adding any bogus keyset info
6602        KeySetManagerService ksms = mSettings.mKeySetManagerService;
6603        ksms.assertScannedPackageValid(pkg);
6604
6605        // writer
6606        synchronized (mPackages) {
6607            // We don't expect installation to fail beyond this point
6608
6609            // Add the new setting to mSettings
6610            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6611            // Add the new setting to mPackages
6612            mPackages.put(pkg.applicationInfo.packageName, pkg);
6613            // Make sure we don't accidentally delete its data.
6614            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6615            while (iter.hasNext()) {
6616                PackageCleanItem item = iter.next();
6617                if (pkgName.equals(item.packageName)) {
6618                    iter.remove();
6619                }
6620            }
6621
6622            // Take care of first install / last update times.
6623            if (currentTime != 0) {
6624                if (pkgSetting.firstInstallTime == 0) {
6625                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6626                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6627                    pkgSetting.lastUpdateTime = currentTime;
6628                }
6629            } else if (pkgSetting.firstInstallTime == 0) {
6630                // We need *something*.  Take time time stamp of the file.
6631                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6632            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6633                if (scanFileTime != pkgSetting.timeStamp) {
6634                    // A package on the system image has changed; consider this
6635                    // to be an update.
6636                    pkgSetting.lastUpdateTime = scanFileTime;
6637                }
6638            }
6639
6640            // Add the package's KeySets to the global KeySetManagerService
6641            ksms.addScannedPackageLPw(pkg);
6642
6643            int N = pkg.providers.size();
6644            StringBuilder r = null;
6645            int i;
6646            for (i=0; i<N; i++) {
6647                PackageParser.Provider p = pkg.providers.get(i);
6648                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6649                        p.info.processName, pkg.applicationInfo.uid);
6650                mProviders.addProvider(p);
6651                p.syncable = p.info.isSyncable;
6652                if (p.info.authority != null) {
6653                    String names[] = p.info.authority.split(";");
6654                    p.info.authority = null;
6655                    for (int j = 0; j < names.length; j++) {
6656                        if (j == 1 && p.syncable) {
6657                            // We only want the first authority for a provider to possibly be
6658                            // syncable, so if we already added this provider using a different
6659                            // authority clear the syncable flag. We copy the provider before
6660                            // changing it because the mProviders object contains a reference
6661                            // to a provider that we don't want to change.
6662                            // Only do this for the second authority since the resulting provider
6663                            // object can be the same for all future authorities for this provider.
6664                            p = new PackageParser.Provider(p);
6665                            p.syncable = false;
6666                        }
6667                        if (!mProvidersByAuthority.containsKey(names[j])) {
6668                            mProvidersByAuthority.put(names[j], p);
6669                            if (p.info.authority == null) {
6670                                p.info.authority = names[j];
6671                            } else {
6672                                p.info.authority = p.info.authority + ";" + names[j];
6673                            }
6674                            if (DEBUG_PACKAGE_SCANNING) {
6675                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6676                                    Log.d(TAG, "Registered content provider: " + names[j]
6677                                            + ", className = " + p.info.name + ", isSyncable = "
6678                                            + p.info.isSyncable);
6679                            }
6680                        } else {
6681                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6682                            Slog.w(TAG, "Skipping provider name " + names[j] +
6683                                    " (in package " + pkg.applicationInfo.packageName +
6684                                    "): name already used by "
6685                                    + ((other != null && other.getComponentName() != null)
6686                                            ? other.getComponentName().getPackageName() : "?"));
6687                        }
6688                    }
6689                }
6690                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6691                    if (r == null) {
6692                        r = new StringBuilder(256);
6693                    } else {
6694                        r.append(' ');
6695                    }
6696                    r.append(p.info.name);
6697                }
6698            }
6699            if (r != null) {
6700                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6701            }
6702
6703            N = pkg.services.size();
6704            r = null;
6705            for (i=0; i<N; i++) {
6706                PackageParser.Service s = pkg.services.get(i);
6707                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6708                        s.info.processName, pkg.applicationInfo.uid);
6709                mServices.addService(s);
6710                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6711                    if (r == null) {
6712                        r = new StringBuilder(256);
6713                    } else {
6714                        r.append(' ');
6715                    }
6716                    r.append(s.info.name);
6717                }
6718            }
6719            if (r != null) {
6720                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6721            }
6722
6723            N = pkg.receivers.size();
6724            r = null;
6725            for (i=0; i<N; i++) {
6726                PackageParser.Activity a = pkg.receivers.get(i);
6727                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6728                        a.info.processName, pkg.applicationInfo.uid);
6729                mReceivers.addActivity(a, "receiver");
6730                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6731                    if (r == null) {
6732                        r = new StringBuilder(256);
6733                    } else {
6734                        r.append(' ');
6735                    }
6736                    r.append(a.info.name);
6737                }
6738            }
6739            if (r != null) {
6740                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6741            }
6742
6743            N = pkg.activities.size();
6744            r = null;
6745            for (i=0; i<N; i++) {
6746                PackageParser.Activity a = pkg.activities.get(i);
6747                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6748                        a.info.processName, pkg.applicationInfo.uid);
6749                mActivities.addActivity(a, "activity");
6750                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6751                    if (r == null) {
6752                        r = new StringBuilder(256);
6753                    } else {
6754                        r.append(' ');
6755                    }
6756                    r.append(a.info.name);
6757                }
6758            }
6759            if (r != null) {
6760                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6761            }
6762
6763            N = pkg.permissionGroups.size();
6764            r = null;
6765            for (i=0; i<N; i++) {
6766                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6767                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6768                if (cur == null) {
6769                    mPermissionGroups.put(pg.info.name, pg);
6770                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6771                        if (r == null) {
6772                            r = new StringBuilder(256);
6773                        } else {
6774                            r.append(' ');
6775                        }
6776                        r.append(pg.info.name);
6777                    }
6778                } else {
6779                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6780                            + pg.info.packageName + " ignored: original from "
6781                            + cur.info.packageName);
6782                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6783                        if (r == null) {
6784                            r = new StringBuilder(256);
6785                        } else {
6786                            r.append(' ');
6787                        }
6788                        r.append("DUP:");
6789                        r.append(pg.info.name);
6790                    }
6791                }
6792            }
6793            if (r != null) {
6794                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6795            }
6796
6797            N = pkg.permissions.size();
6798            r = null;
6799            for (i=0; i<N; i++) {
6800                PackageParser.Permission p = pkg.permissions.get(i);
6801
6802                // Now that permission groups have a special meaning, we ignore permission
6803                // groups for legacy apps to prevent unexpected behavior. In particular,
6804                // permissions for one app being granted to someone just becuase they happen
6805                // to be in a group defined by another app (before this had no implications).
6806                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6807                    p.group = mPermissionGroups.get(p.info.group);
6808                    // Warn for a permission in an unknown group.
6809                    if (p.info.group != null && p.group == null) {
6810                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6811                                + p.info.packageName + " in an unknown group " + p.info.group);
6812                    }
6813                }
6814
6815                ArrayMap<String, BasePermission> permissionMap =
6816                        p.tree ? mSettings.mPermissionTrees
6817                                : mSettings.mPermissions;
6818                BasePermission bp = permissionMap.get(p.info.name);
6819
6820                // Allow system apps to redefine non-system permissions
6821                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6822                    final boolean currentOwnerIsSystem = (bp.perm != null
6823                            && isSystemApp(bp.perm.owner));
6824                    if (isSystemApp(p.owner)) {
6825                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6826                            // It's a built-in permission and no owner, take ownership now
6827                            bp.packageSetting = pkgSetting;
6828                            bp.perm = p;
6829                            bp.uid = pkg.applicationInfo.uid;
6830                            bp.sourcePackage = p.info.packageName;
6831                        } else if (!currentOwnerIsSystem) {
6832                            String msg = "New decl " + p.owner + " of permission  "
6833                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6834                            reportSettingsProblem(Log.WARN, msg);
6835                            bp = null;
6836                        }
6837                    }
6838                }
6839
6840                if (bp == null) {
6841                    bp = new BasePermission(p.info.name, p.info.packageName,
6842                            BasePermission.TYPE_NORMAL);
6843                    permissionMap.put(p.info.name, bp);
6844                }
6845
6846                if (bp.perm == null) {
6847                    if (bp.sourcePackage == null
6848                            || bp.sourcePackage.equals(p.info.packageName)) {
6849                        BasePermission tree = findPermissionTreeLP(p.info.name);
6850                        if (tree == null
6851                                || tree.sourcePackage.equals(p.info.packageName)) {
6852                            bp.packageSetting = pkgSetting;
6853                            bp.perm = p;
6854                            bp.uid = pkg.applicationInfo.uid;
6855                            bp.sourcePackage = p.info.packageName;
6856                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6857                                if (r == null) {
6858                                    r = new StringBuilder(256);
6859                                } else {
6860                                    r.append(' ');
6861                                }
6862                                r.append(p.info.name);
6863                            }
6864                        } else {
6865                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6866                                    + p.info.packageName + " ignored: base tree "
6867                                    + tree.name + " is from package "
6868                                    + tree.sourcePackage);
6869                        }
6870                    } else {
6871                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6872                                + p.info.packageName + " ignored: original from "
6873                                + bp.sourcePackage);
6874                    }
6875                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6876                    if (r == null) {
6877                        r = new StringBuilder(256);
6878                    } else {
6879                        r.append(' ');
6880                    }
6881                    r.append("DUP:");
6882                    r.append(p.info.name);
6883                }
6884                if (bp.perm == p) {
6885                    bp.protectionLevel = p.info.protectionLevel;
6886                }
6887            }
6888
6889            if (r != null) {
6890                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6891            }
6892
6893            N = pkg.instrumentation.size();
6894            r = null;
6895            for (i=0; i<N; i++) {
6896                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6897                a.info.packageName = pkg.applicationInfo.packageName;
6898                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6899                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6900                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6901                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6902                a.info.dataDir = pkg.applicationInfo.dataDir;
6903
6904                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6905                // need other information about the application, like the ABI and what not ?
6906                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6907                mInstrumentation.put(a.getComponentName(), a);
6908                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6909                    if (r == null) {
6910                        r = new StringBuilder(256);
6911                    } else {
6912                        r.append(' ');
6913                    }
6914                    r.append(a.info.name);
6915                }
6916            }
6917            if (r != null) {
6918                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6919            }
6920
6921            if (pkg.protectedBroadcasts != null) {
6922                N = pkg.protectedBroadcasts.size();
6923                for (i=0; i<N; i++) {
6924                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6925                }
6926            }
6927
6928            pkgSetting.setTimeStamp(scanFileTime);
6929
6930            // Create idmap files for pairs of (packages, overlay packages).
6931            // Note: "android", ie framework-res.apk, is handled by native layers.
6932            if (pkg.mOverlayTarget != null) {
6933                // This is an overlay package.
6934                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6935                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6936                        mOverlays.put(pkg.mOverlayTarget,
6937                                new ArrayMap<String, PackageParser.Package>());
6938                    }
6939                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6940                    map.put(pkg.packageName, pkg);
6941                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6942                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6943                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6944                                "scanPackageLI failed to createIdmap");
6945                    }
6946                }
6947            } else if (mOverlays.containsKey(pkg.packageName) &&
6948                    !pkg.packageName.equals("android")) {
6949                // This is a regular package, with one or more known overlay packages.
6950                createIdmapsForPackageLI(pkg);
6951            }
6952        }
6953
6954        return pkg;
6955    }
6956
6957    /**
6958     * Derive the ABI of a non-system package located at {@code scanFile}. This information
6959     * is derived purely on the basis of the contents of {@code scanFile} and
6960     * {@code cpuAbiOverride}.
6961     *
6962     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
6963     */
6964    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
6965                                 String cpuAbiOverride, boolean extractLibs)
6966            throws PackageManagerException {
6967        // TODO: We can probably be smarter about this stuff. For installed apps,
6968        // we can calculate this information at install time once and for all. For
6969        // system apps, we can probably assume that this information doesn't change
6970        // after the first boot scan. As things stand, we do lots of unnecessary work.
6971
6972        // Give ourselves some initial paths; we'll come back for another
6973        // pass once we've determined ABI below.
6974        setNativeLibraryPaths(pkg);
6975
6976        // We would never need to extract libs for forward-locked and external packages,
6977        // since the container service will do it for us. We shouldn't attempt to
6978        // extract libs from system app when it was not updated.
6979        if (pkg.isForwardLocked() || isExternal(pkg) ||
6980            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
6981            extractLibs = false;
6982        }
6983
6984        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6985        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6986
6987        NativeLibraryHelper.Handle handle = null;
6988        try {
6989            handle = NativeLibraryHelper.Handle.create(scanFile);
6990            // TODO(multiArch): This can be null for apps that didn't go through the
6991            // usual installation process. We can calculate it again, like we
6992            // do during install time.
6993            //
6994            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6995            // unnecessary.
6996            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6997
6998            // Null out the abis so that they can be recalculated.
6999            pkg.applicationInfo.primaryCpuAbi = null;
7000            pkg.applicationInfo.secondaryCpuAbi = null;
7001            if (isMultiArch(pkg.applicationInfo)) {
7002                // Warn if we've set an abiOverride for multi-lib packages..
7003                // By definition, we need to copy both 32 and 64 bit libraries for
7004                // such packages.
7005                if (pkg.cpuAbiOverride != null
7006                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7007                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7008                }
7009
7010                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7011                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7012                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7013                    if (extractLibs) {
7014                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7015                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7016                                useIsaSpecificSubdirs);
7017                    } else {
7018                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7019                    }
7020                }
7021
7022                maybeThrowExceptionForMultiArchCopy(
7023                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7024
7025                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7026                    if (extractLibs) {
7027                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7028                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7029                                useIsaSpecificSubdirs);
7030                    } else {
7031                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7032                    }
7033                }
7034
7035                maybeThrowExceptionForMultiArchCopy(
7036                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7037
7038                if (abi64 >= 0) {
7039                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7040                }
7041
7042                if (abi32 >= 0) {
7043                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7044                    if (abi64 >= 0) {
7045                        pkg.applicationInfo.secondaryCpuAbi = abi;
7046                    } else {
7047                        pkg.applicationInfo.primaryCpuAbi = abi;
7048                    }
7049                }
7050            } else {
7051                String[] abiList = (cpuAbiOverride != null) ?
7052                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7053
7054                // Enable gross and lame hacks for apps that are built with old
7055                // SDK tools. We must scan their APKs for renderscript bitcode and
7056                // not launch them if it's present. Don't bother checking on devices
7057                // that don't have 64 bit support.
7058                boolean needsRenderScriptOverride = false;
7059                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7060                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7061                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7062                    needsRenderScriptOverride = true;
7063                }
7064
7065                final int copyRet;
7066                if (extractLibs) {
7067                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7068                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7069                } else {
7070                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7071                }
7072
7073                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7074                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7075                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7076                }
7077
7078                if (copyRet >= 0) {
7079                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7080                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7081                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7082                } else if (needsRenderScriptOverride) {
7083                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7084                }
7085            }
7086        } catch (IOException ioe) {
7087            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7088        } finally {
7089            IoUtils.closeQuietly(handle);
7090        }
7091
7092        // Now that we've calculated the ABIs and determined if it's an internal app,
7093        // we will go ahead and populate the nativeLibraryPath.
7094        setNativeLibraryPaths(pkg);
7095    }
7096
7097    /**
7098     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7099     * i.e, so that all packages can be run inside a single process if required.
7100     *
7101     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7102     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7103     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7104     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7105     * updating a package that belongs to a shared user.
7106     *
7107     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7108     * adds unnecessary complexity.
7109     */
7110    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7111            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7112        String requiredInstructionSet = null;
7113        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7114            requiredInstructionSet = VMRuntime.getInstructionSet(
7115                     scannedPackage.applicationInfo.primaryCpuAbi);
7116        }
7117
7118        PackageSetting requirer = null;
7119        for (PackageSetting ps : packagesForUser) {
7120            // If packagesForUser contains scannedPackage, we skip it. This will happen
7121            // when scannedPackage is an update of an existing package. Without this check,
7122            // we will never be able to change the ABI of any package belonging to a shared
7123            // user, even if it's compatible with other packages.
7124            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7125                if (ps.primaryCpuAbiString == null) {
7126                    continue;
7127                }
7128
7129                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7130                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7131                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7132                    // this but there's not much we can do.
7133                    String errorMessage = "Instruction set mismatch, "
7134                            + ((requirer == null) ? "[caller]" : requirer)
7135                            + " requires " + requiredInstructionSet + " whereas " + ps
7136                            + " requires " + instructionSet;
7137                    Slog.w(TAG, errorMessage);
7138                }
7139
7140                if (requiredInstructionSet == null) {
7141                    requiredInstructionSet = instructionSet;
7142                    requirer = ps;
7143                }
7144            }
7145        }
7146
7147        if (requiredInstructionSet != null) {
7148            String adjustedAbi;
7149            if (requirer != null) {
7150                // requirer != null implies that either scannedPackage was null or that scannedPackage
7151                // did not require an ABI, in which case we have to adjust scannedPackage to match
7152                // the ABI of the set (which is the same as requirer's ABI)
7153                adjustedAbi = requirer.primaryCpuAbiString;
7154                if (scannedPackage != null) {
7155                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7156                }
7157            } else {
7158                // requirer == null implies that we're updating all ABIs in the set to
7159                // match scannedPackage.
7160                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7161            }
7162
7163            for (PackageSetting ps : packagesForUser) {
7164                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7165                    if (ps.primaryCpuAbiString != null) {
7166                        continue;
7167                    }
7168
7169                    ps.primaryCpuAbiString = adjustedAbi;
7170                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7171                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7172                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7173
7174                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7175                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7176                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7177                            ps.primaryCpuAbiString = null;
7178                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7179                            return;
7180                        } else {
7181                            mInstaller.rmdex(ps.codePathString,
7182                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7183                        }
7184                    }
7185                }
7186            }
7187        }
7188    }
7189
7190    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7191        synchronized (mPackages) {
7192            mResolverReplaced = true;
7193            // Set up information for custom user intent resolution activity.
7194            mResolveActivity.applicationInfo = pkg.applicationInfo;
7195            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7196            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7197            mResolveActivity.processName = pkg.applicationInfo.packageName;
7198            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7199            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7200                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7201            mResolveActivity.theme = 0;
7202            mResolveActivity.exported = true;
7203            mResolveActivity.enabled = true;
7204            mResolveInfo.activityInfo = mResolveActivity;
7205            mResolveInfo.priority = 0;
7206            mResolveInfo.preferredOrder = 0;
7207            mResolveInfo.match = 0;
7208            mResolveComponentName = mCustomResolverComponentName;
7209            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7210                    mResolveComponentName);
7211        }
7212    }
7213
7214    private static String calculateBundledApkRoot(final String codePathString) {
7215        final File codePath = new File(codePathString);
7216        final File codeRoot;
7217        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7218            codeRoot = Environment.getRootDirectory();
7219        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7220            codeRoot = Environment.getOemDirectory();
7221        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7222            codeRoot = Environment.getVendorDirectory();
7223        } else {
7224            // Unrecognized code path; take its top real segment as the apk root:
7225            // e.g. /something/app/blah.apk => /something
7226            try {
7227                File f = codePath.getCanonicalFile();
7228                File parent = f.getParentFile();    // non-null because codePath is a file
7229                File tmp;
7230                while ((tmp = parent.getParentFile()) != null) {
7231                    f = parent;
7232                    parent = tmp;
7233                }
7234                codeRoot = f;
7235                Slog.w(TAG, "Unrecognized code path "
7236                        + codePath + " - using " + codeRoot);
7237            } catch (IOException e) {
7238                // Can't canonicalize the code path -- shenanigans?
7239                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7240                return Environment.getRootDirectory().getPath();
7241            }
7242        }
7243        return codeRoot.getPath();
7244    }
7245
7246    /**
7247     * Derive and set the location of native libraries for the given package,
7248     * which varies depending on where and how the package was installed.
7249     */
7250    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7251        final ApplicationInfo info = pkg.applicationInfo;
7252        final String codePath = pkg.codePath;
7253        final File codeFile = new File(codePath);
7254        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7255        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7256
7257        info.nativeLibraryRootDir = null;
7258        info.nativeLibraryRootRequiresIsa = false;
7259        info.nativeLibraryDir = null;
7260        info.secondaryNativeLibraryDir = null;
7261
7262        if (isApkFile(codeFile)) {
7263            // Monolithic install
7264            if (bundledApp) {
7265                // If "/system/lib64/apkname" exists, assume that is the per-package
7266                // native library directory to use; otherwise use "/system/lib/apkname".
7267                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7268                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7269                        getPrimaryInstructionSet(info));
7270
7271                // This is a bundled system app so choose the path based on the ABI.
7272                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7273                // is just the default path.
7274                final String apkName = deriveCodePathName(codePath);
7275                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7276                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7277                        apkName).getAbsolutePath();
7278
7279                if (info.secondaryCpuAbi != null) {
7280                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7281                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7282                            secondaryLibDir, apkName).getAbsolutePath();
7283                }
7284            } else if (asecApp) {
7285                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7286                        .getAbsolutePath();
7287            } else {
7288                final String apkName = deriveCodePathName(codePath);
7289                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7290                        .getAbsolutePath();
7291            }
7292
7293            info.nativeLibraryRootRequiresIsa = false;
7294            info.nativeLibraryDir = info.nativeLibraryRootDir;
7295        } else {
7296            // Cluster install
7297            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7298            info.nativeLibraryRootRequiresIsa = true;
7299
7300            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7301                    getPrimaryInstructionSet(info)).getAbsolutePath();
7302
7303            if (info.secondaryCpuAbi != null) {
7304                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7305                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7306            }
7307        }
7308    }
7309
7310    /**
7311     * Calculate the abis and roots for a bundled app. These can uniquely
7312     * be determined from the contents of the system partition, i.e whether
7313     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7314     * of this information, and instead assume that the system was built
7315     * sensibly.
7316     */
7317    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7318                                           PackageSetting pkgSetting) {
7319        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7320
7321        // If "/system/lib64/apkname" exists, assume that is the per-package
7322        // native library directory to use; otherwise use "/system/lib/apkname".
7323        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7324        setBundledAppAbi(pkg, apkRoot, apkName);
7325        // pkgSetting might be null during rescan following uninstall of updates
7326        // to a bundled app, so accommodate that possibility.  The settings in
7327        // that case will be established later from the parsed package.
7328        //
7329        // If the settings aren't null, sync them up with what we've just derived.
7330        // note that apkRoot isn't stored in the package settings.
7331        if (pkgSetting != null) {
7332            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7333            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7334        }
7335    }
7336
7337    /**
7338     * Deduces the ABI of a bundled app and sets the relevant fields on the
7339     * parsed pkg object.
7340     *
7341     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7342     *        under which system libraries are installed.
7343     * @param apkName the name of the installed package.
7344     */
7345    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7346        final File codeFile = new File(pkg.codePath);
7347
7348        final boolean has64BitLibs;
7349        final boolean has32BitLibs;
7350        if (isApkFile(codeFile)) {
7351            // Monolithic install
7352            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7353            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7354        } else {
7355            // Cluster install
7356            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7357            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7358                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7359                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7360                has64BitLibs = (new File(rootDir, isa)).exists();
7361            } else {
7362                has64BitLibs = false;
7363            }
7364            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7365                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7366                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7367                has32BitLibs = (new File(rootDir, isa)).exists();
7368            } else {
7369                has32BitLibs = false;
7370            }
7371        }
7372
7373        if (has64BitLibs && !has32BitLibs) {
7374            // The package has 64 bit libs, but not 32 bit libs. Its primary
7375            // ABI should be 64 bit. We can safely assume here that the bundled
7376            // native libraries correspond to the most preferred ABI in the list.
7377
7378            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7379            pkg.applicationInfo.secondaryCpuAbi = null;
7380        } else if (has32BitLibs && !has64BitLibs) {
7381            // The package has 32 bit libs but not 64 bit libs. Its primary
7382            // ABI should be 32 bit.
7383
7384            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7385            pkg.applicationInfo.secondaryCpuAbi = null;
7386        } else if (has32BitLibs && has64BitLibs) {
7387            // The application has both 64 and 32 bit bundled libraries. We check
7388            // here that the app declares multiArch support, and warn if it doesn't.
7389            //
7390            // We will be lenient here and record both ABIs. The primary will be the
7391            // ABI that's higher on the list, i.e, a device that's configured to prefer
7392            // 64 bit apps will see a 64 bit primary ABI,
7393
7394            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7395                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7396            }
7397
7398            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7399                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7400                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7401            } else {
7402                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7403                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7404            }
7405        } else {
7406            pkg.applicationInfo.primaryCpuAbi = null;
7407            pkg.applicationInfo.secondaryCpuAbi = null;
7408        }
7409    }
7410
7411    private void killApplication(String pkgName, int appId, String reason) {
7412        // Request the ActivityManager to kill the process(only for existing packages)
7413        // so that we do not end up in a confused state while the user is still using the older
7414        // version of the application while the new one gets installed.
7415        IActivityManager am = ActivityManagerNative.getDefault();
7416        if (am != null) {
7417            try {
7418                am.killApplicationWithAppId(pkgName, appId, reason);
7419            } catch (RemoteException e) {
7420            }
7421        }
7422    }
7423
7424    void removePackageLI(PackageSetting ps, boolean chatty) {
7425        if (DEBUG_INSTALL) {
7426            if (chatty)
7427                Log.d(TAG, "Removing package " + ps.name);
7428        }
7429
7430        // writer
7431        synchronized (mPackages) {
7432            mPackages.remove(ps.name);
7433            final PackageParser.Package pkg = ps.pkg;
7434            if (pkg != null) {
7435                cleanPackageDataStructuresLILPw(pkg, chatty);
7436            }
7437        }
7438    }
7439
7440    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7441        if (DEBUG_INSTALL) {
7442            if (chatty)
7443                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7444        }
7445
7446        // writer
7447        synchronized (mPackages) {
7448            mPackages.remove(pkg.applicationInfo.packageName);
7449            cleanPackageDataStructuresLILPw(pkg, chatty);
7450        }
7451    }
7452
7453    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7454        int N = pkg.providers.size();
7455        StringBuilder r = null;
7456        int i;
7457        for (i=0; i<N; i++) {
7458            PackageParser.Provider p = pkg.providers.get(i);
7459            mProviders.removeProvider(p);
7460            if (p.info.authority == null) {
7461
7462                /* There was another ContentProvider with this authority when
7463                 * this app was installed so this authority is null,
7464                 * Ignore it as we don't have to unregister the provider.
7465                 */
7466                continue;
7467            }
7468            String names[] = p.info.authority.split(";");
7469            for (int j = 0; j < names.length; j++) {
7470                if (mProvidersByAuthority.get(names[j]) == p) {
7471                    mProvidersByAuthority.remove(names[j]);
7472                    if (DEBUG_REMOVE) {
7473                        if (chatty)
7474                            Log.d(TAG, "Unregistered content provider: " + names[j]
7475                                    + ", className = " + p.info.name + ", isSyncable = "
7476                                    + p.info.isSyncable);
7477                    }
7478                }
7479            }
7480            if (DEBUG_REMOVE && chatty) {
7481                if (r == null) {
7482                    r = new StringBuilder(256);
7483                } else {
7484                    r.append(' ');
7485                }
7486                r.append(p.info.name);
7487            }
7488        }
7489        if (r != null) {
7490            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7491        }
7492
7493        N = pkg.services.size();
7494        r = null;
7495        for (i=0; i<N; i++) {
7496            PackageParser.Service s = pkg.services.get(i);
7497            mServices.removeService(s);
7498            if (chatty) {
7499                if (r == null) {
7500                    r = new StringBuilder(256);
7501                } else {
7502                    r.append(' ');
7503                }
7504                r.append(s.info.name);
7505            }
7506        }
7507        if (r != null) {
7508            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7509        }
7510
7511        N = pkg.receivers.size();
7512        r = null;
7513        for (i=0; i<N; i++) {
7514            PackageParser.Activity a = pkg.receivers.get(i);
7515            mReceivers.removeActivity(a, "receiver");
7516            if (DEBUG_REMOVE && chatty) {
7517                if (r == null) {
7518                    r = new StringBuilder(256);
7519                } else {
7520                    r.append(' ');
7521                }
7522                r.append(a.info.name);
7523            }
7524        }
7525        if (r != null) {
7526            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7527        }
7528
7529        N = pkg.activities.size();
7530        r = null;
7531        for (i=0; i<N; i++) {
7532            PackageParser.Activity a = pkg.activities.get(i);
7533            mActivities.removeActivity(a, "activity");
7534            if (DEBUG_REMOVE && chatty) {
7535                if (r == null) {
7536                    r = new StringBuilder(256);
7537                } else {
7538                    r.append(' ');
7539                }
7540                r.append(a.info.name);
7541            }
7542        }
7543        if (r != null) {
7544            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7545        }
7546
7547        N = pkg.permissions.size();
7548        r = null;
7549        for (i=0; i<N; i++) {
7550            PackageParser.Permission p = pkg.permissions.get(i);
7551            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7552            if (bp == null) {
7553                bp = mSettings.mPermissionTrees.get(p.info.name);
7554            }
7555            if (bp != null && bp.perm == p) {
7556                bp.perm = null;
7557                if (DEBUG_REMOVE && chatty) {
7558                    if (r == null) {
7559                        r = new StringBuilder(256);
7560                    } else {
7561                        r.append(' ');
7562                    }
7563                    r.append(p.info.name);
7564                }
7565            }
7566            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7567                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7568                if (appOpPerms != null) {
7569                    appOpPerms.remove(pkg.packageName);
7570                }
7571            }
7572        }
7573        if (r != null) {
7574            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7575        }
7576
7577        N = pkg.requestedPermissions.size();
7578        r = null;
7579        for (i=0; i<N; i++) {
7580            String perm = pkg.requestedPermissions.get(i);
7581            BasePermission bp = mSettings.mPermissions.get(perm);
7582            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7583                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7584                if (appOpPerms != null) {
7585                    appOpPerms.remove(pkg.packageName);
7586                    if (appOpPerms.isEmpty()) {
7587                        mAppOpPermissionPackages.remove(perm);
7588                    }
7589                }
7590            }
7591        }
7592        if (r != null) {
7593            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7594        }
7595
7596        N = pkg.instrumentation.size();
7597        r = null;
7598        for (i=0; i<N; i++) {
7599            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7600            mInstrumentation.remove(a.getComponentName());
7601            if (DEBUG_REMOVE && chatty) {
7602                if (r == null) {
7603                    r = new StringBuilder(256);
7604                } else {
7605                    r.append(' ');
7606                }
7607                r.append(a.info.name);
7608            }
7609        }
7610        if (r != null) {
7611            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7612        }
7613
7614        r = null;
7615        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7616            // Only system apps can hold shared libraries.
7617            if (pkg.libraryNames != null) {
7618                for (i=0; i<pkg.libraryNames.size(); i++) {
7619                    String name = pkg.libraryNames.get(i);
7620                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7621                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7622                        mSharedLibraries.remove(name);
7623                        if (DEBUG_REMOVE && chatty) {
7624                            if (r == null) {
7625                                r = new StringBuilder(256);
7626                            } else {
7627                                r.append(' ');
7628                            }
7629                            r.append(name);
7630                        }
7631                    }
7632                }
7633            }
7634        }
7635        if (r != null) {
7636            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7637        }
7638    }
7639
7640    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7641        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7642            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7643                return true;
7644            }
7645        }
7646        return false;
7647    }
7648
7649    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7650    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7651    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7652
7653    private void updatePermissionsLPw(String changingPkg,
7654            PackageParser.Package pkgInfo, int flags) {
7655        // Make sure there are no dangling permission trees.
7656        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7657        while (it.hasNext()) {
7658            final BasePermission bp = it.next();
7659            if (bp.packageSetting == null) {
7660                // We may not yet have parsed the package, so just see if
7661                // we still know about its settings.
7662                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7663            }
7664            if (bp.packageSetting == null) {
7665                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7666                        + " from package " + bp.sourcePackage);
7667                it.remove();
7668            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7669                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7670                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7671                            + " from package " + bp.sourcePackage);
7672                    flags |= UPDATE_PERMISSIONS_ALL;
7673                    it.remove();
7674                }
7675            }
7676        }
7677
7678        // Make sure all dynamic permissions have been assigned to a package,
7679        // and make sure there are no dangling permissions.
7680        it = mSettings.mPermissions.values().iterator();
7681        while (it.hasNext()) {
7682            final BasePermission bp = it.next();
7683            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7684                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7685                        + bp.name + " pkg=" + bp.sourcePackage
7686                        + " info=" + bp.pendingInfo);
7687                if (bp.packageSetting == null && bp.pendingInfo != null) {
7688                    final BasePermission tree = findPermissionTreeLP(bp.name);
7689                    if (tree != null && tree.perm != null) {
7690                        bp.packageSetting = tree.packageSetting;
7691                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7692                                new PermissionInfo(bp.pendingInfo));
7693                        bp.perm.info.packageName = tree.perm.info.packageName;
7694                        bp.perm.info.name = bp.name;
7695                        bp.uid = tree.uid;
7696                    }
7697                }
7698            }
7699            if (bp.packageSetting == null) {
7700                // We may not yet have parsed the package, so just see if
7701                // we still know about its settings.
7702                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7703            }
7704            if (bp.packageSetting == null) {
7705                Slog.w(TAG, "Removing dangling permission: " + bp.name
7706                        + " from package " + bp.sourcePackage);
7707                it.remove();
7708            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7709                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7710                    Slog.i(TAG, "Removing old permission: " + bp.name
7711                            + " from package " + bp.sourcePackage);
7712                    flags |= UPDATE_PERMISSIONS_ALL;
7713                    it.remove();
7714                }
7715            }
7716        }
7717
7718        // Now update the permissions for all packages, in particular
7719        // replace the granted permissions of the system packages.
7720        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7721            for (PackageParser.Package pkg : mPackages.values()) {
7722                if (pkg != pkgInfo) {
7723                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7724                            changingPkg);
7725                }
7726            }
7727        }
7728
7729        if (pkgInfo != null) {
7730            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7731        }
7732    }
7733
7734    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7735            String packageOfInterest) {
7736        // IMPORTANT: There are two types of permissions: install and runtime.
7737        // Install time permissions are granted when the app is installed to
7738        // all device users and users added in the future. Runtime permissions
7739        // are granted at runtime explicitly to specific users. Normal and signature
7740        // protected permissions are install time permissions. Dangerous permissions
7741        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7742        // otherwise they are runtime permissions. This function does not manage
7743        // runtime permissions except for the case an app targeting Lollipop MR1
7744        // being upgraded to target a newer SDK, in which case dangerous permissions
7745        // are transformed from install time to runtime ones.
7746
7747        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7748        if (ps == null) {
7749            return;
7750        }
7751
7752        PermissionsState permissionsState = ps.getPermissionsState();
7753        PermissionsState origPermissions = permissionsState;
7754
7755        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7756
7757        int[] upgradeUserIds = EMPTY_INT_ARRAY;
7758        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7759
7760        boolean changedInstallPermission = false;
7761
7762        if (replace) {
7763            ps.installPermissionsFixed = false;
7764            if (!ps.isSharedUser()) {
7765                origPermissions = new PermissionsState(permissionsState);
7766                permissionsState.reset();
7767            }
7768        }
7769
7770        permissionsState.setGlobalGids(mGlobalGids);
7771
7772        final int N = pkg.requestedPermissions.size();
7773        for (int i=0; i<N; i++) {
7774            final String name = pkg.requestedPermissions.get(i);
7775            final BasePermission bp = mSettings.mPermissions.get(name);
7776
7777            if (DEBUG_INSTALL) {
7778                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7779            }
7780
7781            if (bp == null || bp.packageSetting == null) {
7782                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7783                    Slog.w(TAG, "Unknown permission " + name
7784                            + " in package " + pkg.packageName);
7785                }
7786                continue;
7787            }
7788
7789            final String perm = bp.name;
7790            boolean allowedSig = false;
7791            int grant = GRANT_DENIED;
7792
7793            // Keep track of app op permissions.
7794            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7795                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7796                if (pkgs == null) {
7797                    pkgs = new ArraySet<>();
7798                    mAppOpPermissionPackages.put(bp.name, pkgs);
7799                }
7800                pkgs.add(pkg.packageName);
7801            }
7802
7803            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7804            switch (level) {
7805                case PermissionInfo.PROTECTION_NORMAL: {
7806                    // For all apps normal permissions are install time ones.
7807                    grant = GRANT_INSTALL;
7808                } break;
7809
7810                case PermissionInfo.PROTECTION_DANGEROUS: {
7811                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7812                        // For legacy apps dangerous permissions are install time ones.
7813                        grant = GRANT_INSTALL_LEGACY;
7814                    } else if (ps.isSystem()) {
7815                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7816                        if (origPermissions.hasInstallPermission(bp.name)) {
7817                            // If a system app had an install permission, then the app was
7818                            // upgraded and we grant the permissions as runtime to all users.
7819                            grant = GRANT_UPGRADE;
7820                            upgradeUserIds = currentUserIds;
7821                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7822                            // If users changed since the last permissions update for a
7823                            // system app, we grant the permission as runtime to the new users.
7824                            grant = GRANT_UPGRADE;
7825                            upgradeUserIds = currentUserIds;
7826                            for (int userId : updatedUserIds) {
7827                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7828                            }
7829                        } else {
7830                            // Otherwise, we grant the permission as runtime if the app
7831                            // already had it, i.e. we preserve runtime permissions.
7832                            grant = GRANT_RUNTIME;
7833                        }
7834                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7835                        // For legacy apps that became modern, install becomes runtime.
7836                        grant = GRANT_UPGRADE;
7837                        upgradeUserIds = currentUserIds;
7838                    } else if (replace) {
7839                        // For upgraded modern apps keep runtime permissions unchanged.
7840                        grant = GRANT_RUNTIME;
7841                    }
7842                } break;
7843
7844                case PermissionInfo.PROTECTION_SIGNATURE: {
7845                    // For all apps signature permissions are install time ones.
7846                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7847                    if (allowedSig) {
7848                        grant = GRANT_INSTALL;
7849                    }
7850                } break;
7851            }
7852
7853            if (DEBUG_INSTALL) {
7854                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7855            }
7856
7857            if (grant != GRANT_DENIED) {
7858                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7859                    // If this is an existing, non-system package, then
7860                    // we can't add any new permissions to it.
7861                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7862                        // Except...  if this is a permission that was added
7863                        // to the platform (note: need to only do this when
7864                        // updating the platform).
7865                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7866                            grant = GRANT_DENIED;
7867                        }
7868                    }
7869                }
7870
7871                switch (grant) {
7872                    case GRANT_INSTALL: {
7873                        // Revoke this as runtime permission to handle the case of
7874                        // a runtime permssion being downgraded to an install one.
7875                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7876                            if (origPermissions.getRuntimePermissionState(
7877                                    bp.name, userId) != null) {
7878                                // Revoke the runtime permission and clear the flags.
7879                                origPermissions.revokeRuntimePermission(bp, userId);
7880                                origPermissions.updatePermissionFlags(bp, userId,
7881                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
7882                                // If we revoked a permission permission, we have to write.
7883                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7884                                        changedRuntimePermissionUserIds, userId);
7885                            }
7886                        }
7887                        // Grant an install permission.
7888                        if (permissionsState.grantInstallPermission(bp) !=
7889                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7890                            changedInstallPermission = true;
7891                        }
7892                    } break;
7893
7894                    case GRANT_INSTALL_LEGACY: {
7895                        // Grant an install permission.
7896                        if (permissionsState.grantInstallPermission(bp) !=
7897                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7898                            changedInstallPermission = true;
7899                        }
7900                    } break;
7901
7902                    case GRANT_RUNTIME: {
7903                        // Grant previously granted runtime permissions.
7904                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7905                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7906                                PermissionState permissionState = origPermissions
7907                                        .getRuntimePermissionState(bp.name, userId);
7908                                final int flags = permissionState.getFlags();
7909                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7910                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7911                                    // If we cannot put the permission as it was, we have to write.
7912                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7913                                            changedRuntimePermissionUserIds, userId);
7914                                } else {
7915                                    // System components not only get the permissions but
7916                                    // they are also fixed, so nothing can change that.
7917                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7918                                            ? flags
7919                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7920                                    // Propagate the permission flags.
7921                                    permissionsState.updatePermissionFlags(bp, userId,
7922                                            newFlags, newFlags);
7923                                }
7924                            }
7925                        }
7926                    } break;
7927
7928                    case GRANT_UPGRADE: {
7929                        // Grant runtime permissions for a previously held install permission.
7930                        PermissionState permissionState = origPermissions
7931                                .getInstallPermissionState(bp.name);
7932                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
7933
7934                        origPermissions.revokeInstallPermission(bp);
7935                        // We will be transferring the permission flags, so clear them.
7936                        origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
7937                                PackageManager.MASK_PERMISSION_FLAGS, 0);
7938
7939                        // If the permission is not to be promoted to runtime we ignore it and
7940                        // also its other flags as they are not applicable to install permissions.
7941                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
7942                            for (int userId : upgradeUserIds) {
7943                                if (permissionsState.grantRuntimePermission(bp, userId) !=
7944                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7945                                    // System components not only get the permissions but
7946                                    // they are also fixed so nothing can change that.
7947                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7948                                            ? flags
7949                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7950                                    // Transfer the permission flags.
7951                                    permissionsState.updatePermissionFlags(bp, userId,
7952                                            newFlags, newFlags);
7953                                    // If we granted the permission, we have to write.
7954                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7955                                            changedRuntimePermissionUserIds, userId);
7956                                }
7957                            }
7958                        }
7959                    } break;
7960
7961                    default: {
7962                        if (packageOfInterest == null
7963                                || packageOfInterest.equals(pkg.packageName)) {
7964                            Slog.w(TAG, "Not granting permission " + perm
7965                                    + " to package " + pkg.packageName
7966                                    + " because it was previously installed without");
7967                        }
7968                    } break;
7969                }
7970            } else {
7971                if (permissionsState.revokeInstallPermission(bp) !=
7972                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7973                    // Also drop the permission flags.
7974                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
7975                            PackageManager.MASK_PERMISSION_FLAGS, 0);
7976                    changedInstallPermission = true;
7977                    Slog.i(TAG, "Un-granting permission " + perm
7978                            + " from package " + pkg.packageName
7979                            + " (protectionLevel=" + bp.protectionLevel
7980                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7981                            + ")");
7982                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7983                    // Don't print warning for app op permissions, since it is fine for them
7984                    // not to be granted, there is a UI for the user to decide.
7985                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7986                        Slog.w(TAG, "Not granting permission " + perm
7987                                + " to package " + pkg.packageName
7988                                + " (protectionLevel=" + bp.protectionLevel
7989                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7990                                + ")");
7991                    }
7992                }
7993            }
7994        }
7995
7996        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7997                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7998            // This is the first that we have heard about this package, so the
7999            // permissions we have now selected are fixed until explicitly
8000            // changed.
8001            ps.installPermissionsFixed = true;
8002        }
8003
8004        ps.setPermissionsUpdatedForUserIds(currentUserIds);
8005
8006        // Persist the runtime permissions state for users with changes.
8007        for (int userId : changedRuntimePermissionUserIds) {
8008            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
8009        }
8010    }
8011
8012    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8013        boolean allowed = false;
8014        final int NP = PackageParser.NEW_PERMISSIONS.length;
8015        for (int ip=0; ip<NP; ip++) {
8016            final PackageParser.NewPermissionInfo npi
8017                    = PackageParser.NEW_PERMISSIONS[ip];
8018            if (npi.name.equals(perm)
8019                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8020                allowed = true;
8021                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8022                        + pkg.packageName);
8023                break;
8024            }
8025        }
8026        return allowed;
8027    }
8028
8029    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8030            BasePermission bp, PermissionsState origPermissions) {
8031        boolean allowed;
8032        allowed = (compareSignatures(
8033                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8034                        == PackageManager.SIGNATURE_MATCH)
8035                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8036                        == PackageManager.SIGNATURE_MATCH);
8037        if (!allowed && (bp.protectionLevel
8038                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8039            if (isSystemApp(pkg)) {
8040                // For updated system applications, a system permission
8041                // is granted only if it had been defined by the original application.
8042                if (pkg.isUpdatedSystemApp()) {
8043                    final PackageSetting sysPs = mSettings
8044                            .getDisabledSystemPkgLPr(pkg.packageName);
8045                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8046                        // If the original was granted this permission, we take
8047                        // that grant decision as read and propagate it to the
8048                        // update.
8049                        if (sysPs.isPrivileged()) {
8050                            allowed = true;
8051                        }
8052                    } else {
8053                        // The system apk may have been updated with an older
8054                        // version of the one on the data partition, but which
8055                        // granted a new system permission that it didn't have
8056                        // before.  In this case we do want to allow the app to
8057                        // now get the new permission if the ancestral apk is
8058                        // privileged to get it.
8059                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8060                            for (int j=0;
8061                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8062                                if (perm.equals(
8063                                        sysPs.pkg.requestedPermissions.get(j))) {
8064                                    allowed = true;
8065                                    break;
8066                                }
8067                            }
8068                        }
8069                    }
8070                } else {
8071                    allowed = isPrivilegedApp(pkg);
8072                }
8073            }
8074        }
8075        if (!allowed && (bp.protectionLevel
8076                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8077            // For development permissions, a development permission
8078            // is granted only if it was already granted.
8079            allowed = origPermissions.hasInstallPermission(perm);
8080        }
8081        return allowed;
8082    }
8083
8084    final class ActivityIntentResolver
8085            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8086        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8087                boolean defaultOnly, int userId) {
8088            if (!sUserManager.exists(userId)) return null;
8089            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8090            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8091        }
8092
8093        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8094                int userId) {
8095            if (!sUserManager.exists(userId)) return null;
8096            mFlags = flags;
8097            return super.queryIntent(intent, resolvedType,
8098                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8099        }
8100
8101        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8102                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8103            if (!sUserManager.exists(userId)) return null;
8104            if (packageActivities == null) {
8105                return null;
8106            }
8107            mFlags = flags;
8108            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8109            final int N = packageActivities.size();
8110            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8111                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8112
8113            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8114            for (int i = 0; i < N; ++i) {
8115                intentFilters = packageActivities.get(i).intents;
8116                if (intentFilters != null && intentFilters.size() > 0) {
8117                    PackageParser.ActivityIntentInfo[] array =
8118                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8119                    intentFilters.toArray(array);
8120                    listCut.add(array);
8121                }
8122            }
8123            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8124        }
8125
8126        public final void addActivity(PackageParser.Activity a, String type) {
8127            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8128            mActivities.put(a.getComponentName(), a);
8129            if (DEBUG_SHOW_INFO)
8130                Log.v(
8131                TAG, "  " + type + " " +
8132                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8133            if (DEBUG_SHOW_INFO)
8134                Log.v(TAG, "    Class=" + a.info.name);
8135            final int NI = a.intents.size();
8136            for (int j=0; j<NI; j++) {
8137                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8138                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8139                    intent.setPriority(0);
8140                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8141                            + a.className + " with priority > 0, forcing to 0");
8142                }
8143                if (DEBUG_SHOW_INFO) {
8144                    Log.v(TAG, "    IntentFilter:");
8145                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8146                }
8147                if (!intent.debugCheck()) {
8148                    Log.w(TAG, "==> For Activity " + a.info.name);
8149                }
8150                addFilter(intent);
8151            }
8152        }
8153
8154        public final void removeActivity(PackageParser.Activity a, String type) {
8155            mActivities.remove(a.getComponentName());
8156            if (DEBUG_SHOW_INFO) {
8157                Log.v(TAG, "  " + type + " "
8158                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8159                                : a.info.name) + ":");
8160                Log.v(TAG, "    Class=" + a.info.name);
8161            }
8162            final int NI = a.intents.size();
8163            for (int j=0; j<NI; j++) {
8164                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8165                if (DEBUG_SHOW_INFO) {
8166                    Log.v(TAG, "    IntentFilter:");
8167                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8168                }
8169                removeFilter(intent);
8170            }
8171        }
8172
8173        @Override
8174        protected boolean allowFilterResult(
8175                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8176            ActivityInfo filterAi = filter.activity.info;
8177            for (int i=dest.size()-1; i>=0; i--) {
8178                ActivityInfo destAi = dest.get(i).activityInfo;
8179                if (destAi.name == filterAi.name
8180                        && destAi.packageName == filterAi.packageName) {
8181                    return false;
8182                }
8183            }
8184            return true;
8185        }
8186
8187        @Override
8188        protected ActivityIntentInfo[] newArray(int size) {
8189            return new ActivityIntentInfo[size];
8190        }
8191
8192        @Override
8193        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8194            if (!sUserManager.exists(userId)) return true;
8195            PackageParser.Package p = filter.activity.owner;
8196            if (p != null) {
8197                PackageSetting ps = (PackageSetting)p.mExtras;
8198                if (ps != null) {
8199                    // System apps are never considered stopped for purposes of
8200                    // filtering, because there may be no way for the user to
8201                    // actually re-launch them.
8202                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8203                            && ps.getStopped(userId);
8204                }
8205            }
8206            return false;
8207        }
8208
8209        @Override
8210        protected boolean isPackageForFilter(String packageName,
8211                PackageParser.ActivityIntentInfo info) {
8212            return packageName.equals(info.activity.owner.packageName);
8213        }
8214
8215        @Override
8216        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8217                int match, int userId) {
8218            if (!sUserManager.exists(userId)) return null;
8219            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8220                return null;
8221            }
8222            final PackageParser.Activity activity = info.activity;
8223            if (mSafeMode && (activity.info.applicationInfo.flags
8224                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8225                return null;
8226            }
8227            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8228            if (ps == null) {
8229                return null;
8230            }
8231            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8232                    ps.readUserState(userId), userId);
8233            if (ai == null) {
8234                return null;
8235            }
8236            final ResolveInfo res = new ResolveInfo();
8237            res.activityInfo = ai;
8238            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8239                res.filter = info;
8240            }
8241            if (info != null) {
8242                res.handleAllWebDataURI = info.handleAllWebDataURI();
8243            }
8244            res.priority = info.getPriority();
8245            res.preferredOrder = activity.owner.mPreferredOrder;
8246            //System.out.println("Result: " + res.activityInfo.className +
8247            //                   " = " + res.priority);
8248            res.match = match;
8249            res.isDefault = info.hasDefault;
8250            res.labelRes = info.labelRes;
8251            res.nonLocalizedLabel = info.nonLocalizedLabel;
8252            if (userNeedsBadging(userId)) {
8253                res.noResourceId = true;
8254            } else {
8255                res.icon = info.icon;
8256            }
8257            res.system = res.activityInfo.applicationInfo.isSystemApp();
8258            return res;
8259        }
8260
8261        @Override
8262        protected void sortResults(List<ResolveInfo> results) {
8263            Collections.sort(results, mResolvePrioritySorter);
8264        }
8265
8266        @Override
8267        protected void dumpFilter(PrintWriter out, String prefix,
8268                PackageParser.ActivityIntentInfo filter) {
8269            out.print(prefix); out.print(
8270                    Integer.toHexString(System.identityHashCode(filter.activity)));
8271                    out.print(' ');
8272                    filter.activity.printComponentShortName(out);
8273                    out.print(" filter ");
8274                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8275        }
8276
8277        @Override
8278        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8279            return filter.activity;
8280        }
8281
8282        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8283            PackageParser.Activity activity = (PackageParser.Activity)label;
8284            out.print(prefix); out.print(
8285                    Integer.toHexString(System.identityHashCode(activity)));
8286                    out.print(' ');
8287                    activity.printComponentShortName(out);
8288            if (count > 1) {
8289                out.print(" ("); out.print(count); out.print(" filters)");
8290            }
8291            out.println();
8292        }
8293
8294//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8295//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8296//            final List<ResolveInfo> retList = Lists.newArrayList();
8297//            while (i.hasNext()) {
8298//                final ResolveInfo resolveInfo = i.next();
8299//                if (isEnabledLP(resolveInfo.activityInfo)) {
8300//                    retList.add(resolveInfo);
8301//                }
8302//            }
8303//            return retList;
8304//        }
8305
8306        // Keys are String (activity class name), values are Activity.
8307        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8308                = new ArrayMap<ComponentName, PackageParser.Activity>();
8309        private int mFlags;
8310    }
8311
8312    private final class ServiceIntentResolver
8313            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8314        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8315                boolean defaultOnly, int userId) {
8316            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8317            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8318        }
8319
8320        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8321                int userId) {
8322            if (!sUserManager.exists(userId)) return null;
8323            mFlags = flags;
8324            return super.queryIntent(intent, resolvedType,
8325                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8326        }
8327
8328        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8329                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8330            if (!sUserManager.exists(userId)) return null;
8331            if (packageServices == null) {
8332                return null;
8333            }
8334            mFlags = flags;
8335            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8336            final int N = packageServices.size();
8337            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8338                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8339
8340            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8341            for (int i = 0; i < N; ++i) {
8342                intentFilters = packageServices.get(i).intents;
8343                if (intentFilters != null && intentFilters.size() > 0) {
8344                    PackageParser.ServiceIntentInfo[] array =
8345                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8346                    intentFilters.toArray(array);
8347                    listCut.add(array);
8348                }
8349            }
8350            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8351        }
8352
8353        public final void addService(PackageParser.Service s) {
8354            mServices.put(s.getComponentName(), s);
8355            if (DEBUG_SHOW_INFO) {
8356                Log.v(TAG, "  "
8357                        + (s.info.nonLocalizedLabel != null
8358                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8359                Log.v(TAG, "    Class=" + s.info.name);
8360            }
8361            final int NI = s.intents.size();
8362            int j;
8363            for (j=0; j<NI; j++) {
8364                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8365                if (DEBUG_SHOW_INFO) {
8366                    Log.v(TAG, "    IntentFilter:");
8367                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8368                }
8369                if (!intent.debugCheck()) {
8370                    Log.w(TAG, "==> For Service " + s.info.name);
8371                }
8372                addFilter(intent);
8373            }
8374        }
8375
8376        public final void removeService(PackageParser.Service s) {
8377            mServices.remove(s.getComponentName());
8378            if (DEBUG_SHOW_INFO) {
8379                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8380                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8381                Log.v(TAG, "    Class=" + s.info.name);
8382            }
8383            final int NI = s.intents.size();
8384            int j;
8385            for (j=0; j<NI; j++) {
8386                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8387                if (DEBUG_SHOW_INFO) {
8388                    Log.v(TAG, "    IntentFilter:");
8389                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8390                }
8391                removeFilter(intent);
8392            }
8393        }
8394
8395        @Override
8396        protected boolean allowFilterResult(
8397                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8398            ServiceInfo filterSi = filter.service.info;
8399            for (int i=dest.size()-1; i>=0; i--) {
8400                ServiceInfo destAi = dest.get(i).serviceInfo;
8401                if (destAi.name == filterSi.name
8402                        && destAi.packageName == filterSi.packageName) {
8403                    return false;
8404                }
8405            }
8406            return true;
8407        }
8408
8409        @Override
8410        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8411            return new PackageParser.ServiceIntentInfo[size];
8412        }
8413
8414        @Override
8415        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8416            if (!sUserManager.exists(userId)) return true;
8417            PackageParser.Package p = filter.service.owner;
8418            if (p != null) {
8419                PackageSetting ps = (PackageSetting)p.mExtras;
8420                if (ps != null) {
8421                    // System apps are never considered stopped for purposes of
8422                    // filtering, because there may be no way for the user to
8423                    // actually re-launch them.
8424                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8425                            && ps.getStopped(userId);
8426                }
8427            }
8428            return false;
8429        }
8430
8431        @Override
8432        protected boolean isPackageForFilter(String packageName,
8433                PackageParser.ServiceIntentInfo info) {
8434            return packageName.equals(info.service.owner.packageName);
8435        }
8436
8437        @Override
8438        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8439                int match, int userId) {
8440            if (!sUserManager.exists(userId)) return null;
8441            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8442            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8443                return null;
8444            }
8445            final PackageParser.Service service = info.service;
8446            if (mSafeMode && (service.info.applicationInfo.flags
8447                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8448                return null;
8449            }
8450            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8451            if (ps == null) {
8452                return null;
8453            }
8454            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8455                    ps.readUserState(userId), userId);
8456            if (si == null) {
8457                return null;
8458            }
8459            final ResolveInfo res = new ResolveInfo();
8460            res.serviceInfo = si;
8461            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8462                res.filter = filter;
8463            }
8464            res.priority = info.getPriority();
8465            res.preferredOrder = service.owner.mPreferredOrder;
8466            res.match = match;
8467            res.isDefault = info.hasDefault;
8468            res.labelRes = info.labelRes;
8469            res.nonLocalizedLabel = info.nonLocalizedLabel;
8470            res.icon = info.icon;
8471            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8472            return res;
8473        }
8474
8475        @Override
8476        protected void sortResults(List<ResolveInfo> results) {
8477            Collections.sort(results, mResolvePrioritySorter);
8478        }
8479
8480        @Override
8481        protected void dumpFilter(PrintWriter out, String prefix,
8482                PackageParser.ServiceIntentInfo filter) {
8483            out.print(prefix); out.print(
8484                    Integer.toHexString(System.identityHashCode(filter.service)));
8485                    out.print(' ');
8486                    filter.service.printComponentShortName(out);
8487                    out.print(" filter ");
8488                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8489        }
8490
8491        @Override
8492        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8493            return filter.service;
8494        }
8495
8496        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8497            PackageParser.Service service = (PackageParser.Service)label;
8498            out.print(prefix); out.print(
8499                    Integer.toHexString(System.identityHashCode(service)));
8500                    out.print(' ');
8501                    service.printComponentShortName(out);
8502            if (count > 1) {
8503                out.print(" ("); out.print(count); out.print(" filters)");
8504            }
8505            out.println();
8506        }
8507
8508//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8509//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8510//            final List<ResolveInfo> retList = Lists.newArrayList();
8511//            while (i.hasNext()) {
8512//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8513//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8514//                    retList.add(resolveInfo);
8515//                }
8516//            }
8517//            return retList;
8518//        }
8519
8520        // Keys are String (activity class name), values are Activity.
8521        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8522                = new ArrayMap<ComponentName, PackageParser.Service>();
8523        private int mFlags;
8524    };
8525
8526    private final class ProviderIntentResolver
8527            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8528        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8529                boolean defaultOnly, int userId) {
8530            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8531            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8532        }
8533
8534        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8535                int userId) {
8536            if (!sUserManager.exists(userId))
8537                return null;
8538            mFlags = flags;
8539            return super.queryIntent(intent, resolvedType,
8540                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8541        }
8542
8543        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8544                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8545            if (!sUserManager.exists(userId))
8546                return null;
8547            if (packageProviders == null) {
8548                return null;
8549            }
8550            mFlags = flags;
8551            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8552            final int N = packageProviders.size();
8553            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8554                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8555
8556            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8557            for (int i = 0; i < N; ++i) {
8558                intentFilters = packageProviders.get(i).intents;
8559                if (intentFilters != null && intentFilters.size() > 0) {
8560                    PackageParser.ProviderIntentInfo[] array =
8561                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8562                    intentFilters.toArray(array);
8563                    listCut.add(array);
8564                }
8565            }
8566            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8567        }
8568
8569        public final void addProvider(PackageParser.Provider p) {
8570            if (mProviders.containsKey(p.getComponentName())) {
8571                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8572                return;
8573            }
8574
8575            mProviders.put(p.getComponentName(), p);
8576            if (DEBUG_SHOW_INFO) {
8577                Log.v(TAG, "  "
8578                        + (p.info.nonLocalizedLabel != null
8579                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8580                Log.v(TAG, "    Class=" + p.info.name);
8581            }
8582            final int NI = p.intents.size();
8583            int j;
8584            for (j = 0; j < NI; j++) {
8585                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8586                if (DEBUG_SHOW_INFO) {
8587                    Log.v(TAG, "    IntentFilter:");
8588                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8589                }
8590                if (!intent.debugCheck()) {
8591                    Log.w(TAG, "==> For Provider " + p.info.name);
8592                }
8593                addFilter(intent);
8594            }
8595        }
8596
8597        public final void removeProvider(PackageParser.Provider p) {
8598            mProviders.remove(p.getComponentName());
8599            if (DEBUG_SHOW_INFO) {
8600                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8601                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8602                Log.v(TAG, "    Class=" + p.info.name);
8603            }
8604            final int NI = p.intents.size();
8605            int j;
8606            for (j = 0; j < NI; j++) {
8607                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8608                if (DEBUG_SHOW_INFO) {
8609                    Log.v(TAG, "    IntentFilter:");
8610                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8611                }
8612                removeFilter(intent);
8613            }
8614        }
8615
8616        @Override
8617        protected boolean allowFilterResult(
8618                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8619            ProviderInfo filterPi = filter.provider.info;
8620            for (int i = dest.size() - 1; i >= 0; i--) {
8621                ProviderInfo destPi = dest.get(i).providerInfo;
8622                if (destPi.name == filterPi.name
8623                        && destPi.packageName == filterPi.packageName) {
8624                    return false;
8625                }
8626            }
8627            return true;
8628        }
8629
8630        @Override
8631        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8632            return new PackageParser.ProviderIntentInfo[size];
8633        }
8634
8635        @Override
8636        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8637            if (!sUserManager.exists(userId))
8638                return true;
8639            PackageParser.Package p = filter.provider.owner;
8640            if (p != null) {
8641                PackageSetting ps = (PackageSetting) p.mExtras;
8642                if (ps != null) {
8643                    // System apps are never considered stopped for purposes of
8644                    // filtering, because there may be no way for the user to
8645                    // actually re-launch them.
8646                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8647                            && ps.getStopped(userId);
8648                }
8649            }
8650            return false;
8651        }
8652
8653        @Override
8654        protected boolean isPackageForFilter(String packageName,
8655                PackageParser.ProviderIntentInfo info) {
8656            return packageName.equals(info.provider.owner.packageName);
8657        }
8658
8659        @Override
8660        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8661                int match, int userId) {
8662            if (!sUserManager.exists(userId))
8663                return null;
8664            final PackageParser.ProviderIntentInfo info = filter;
8665            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8666                return null;
8667            }
8668            final PackageParser.Provider provider = info.provider;
8669            if (mSafeMode && (provider.info.applicationInfo.flags
8670                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8671                return null;
8672            }
8673            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8674            if (ps == null) {
8675                return null;
8676            }
8677            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8678                    ps.readUserState(userId), userId);
8679            if (pi == null) {
8680                return null;
8681            }
8682            final ResolveInfo res = new ResolveInfo();
8683            res.providerInfo = pi;
8684            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8685                res.filter = filter;
8686            }
8687            res.priority = info.getPriority();
8688            res.preferredOrder = provider.owner.mPreferredOrder;
8689            res.match = match;
8690            res.isDefault = info.hasDefault;
8691            res.labelRes = info.labelRes;
8692            res.nonLocalizedLabel = info.nonLocalizedLabel;
8693            res.icon = info.icon;
8694            res.system = res.providerInfo.applicationInfo.isSystemApp();
8695            return res;
8696        }
8697
8698        @Override
8699        protected void sortResults(List<ResolveInfo> results) {
8700            Collections.sort(results, mResolvePrioritySorter);
8701        }
8702
8703        @Override
8704        protected void dumpFilter(PrintWriter out, String prefix,
8705                PackageParser.ProviderIntentInfo filter) {
8706            out.print(prefix);
8707            out.print(
8708                    Integer.toHexString(System.identityHashCode(filter.provider)));
8709            out.print(' ');
8710            filter.provider.printComponentShortName(out);
8711            out.print(" filter ");
8712            out.println(Integer.toHexString(System.identityHashCode(filter)));
8713        }
8714
8715        @Override
8716        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8717            return filter.provider;
8718        }
8719
8720        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8721            PackageParser.Provider provider = (PackageParser.Provider)label;
8722            out.print(prefix); out.print(
8723                    Integer.toHexString(System.identityHashCode(provider)));
8724                    out.print(' ');
8725                    provider.printComponentShortName(out);
8726            if (count > 1) {
8727                out.print(" ("); out.print(count); out.print(" filters)");
8728            }
8729            out.println();
8730        }
8731
8732        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8733                = new ArrayMap<ComponentName, PackageParser.Provider>();
8734        private int mFlags;
8735    };
8736
8737    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8738            new Comparator<ResolveInfo>() {
8739        public int compare(ResolveInfo r1, ResolveInfo r2) {
8740            int v1 = r1.priority;
8741            int v2 = r2.priority;
8742            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8743            if (v1 != v2) {
8744                return (v1 > v2) ? -1 : 1;
8745            }
8746            v1 = r1.preferredOrder;
8747            v2 = r2.preferredOrder;
8748            if (v1 != v2) {
8749                return (v1 > v2) ? -1 : 1;
8750            }
8751            if (r1.isDefault != r2.isDefault) {
8752                return r1.isDefault ? -1 : 1;
8753            }
8754            v1 = r1.match;
8755            v2 = r2.match;
8756            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8757            if (v1 != v2) {
8758                return (v1 > v2) ? -1 : 1;
8759            }
8760            if (r1.system != r2.system) {
8761                return r1.system ? -1 : 1;
8762            }
8763            return 0;
8764        }
8765    };
8766
8767    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8768            new Comparator<ProviderInfo>() {
8769        public int compare(ProviderInfo p1, ProviderInfo p2) {
8770            final int v1 = p1.initOrder;
8771            final int v2 = p2.initOrder;
8772            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8773        }
8774    };
8775
8776    final void sendPackageBroadcast(final String action, final String pkg,
8777            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8778            final int[] userIds) {
8779        mHandler.post(new Runnable() {
8780            @Override
8781            public void run() {
8782                try {
8783                    final IActivityManager am = ActivityManagerNative.getDefault();
8784                    if (am == null) return;
8785                    final int[] resolvedUserIds;
8786                    if (userIds == null) {
8787                        resolvedUserIds = am.getRunningUserIds();
8788                    } else {
8789                        resolvedUserIds = userIds;
8790                    }
8791                    for (int id : resolvedUserIds) {
8792                        final Intent intent = new Intent(action,
8793                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8794                        if (extras != null) {
8795                            intent.putExtras(extras);
8796                        }
8797                        if (targetPkg != null) {
8798                            intent.setPackage(targetPkg);
8799                        }
8800                        // Modify the UID when posting to other users
8801                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8802                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8803                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8804                            intent.putExtra(Intent.EXTRA_UID, uid);
8805                        }
8806                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8807                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8808                        if (DEBUG_BROADCASTS) {
8809                            RuntimeException here = new RuntimeException("here");
8810                            here.fillInStackTrace();
8811                            Slog.d(TAG, "Sending to user " + id + ": "
8812                                    + intent.toShortString(false, true, false, false)
8813                                    + " " + intent.getExtras(), here);
8814                        }
8815                        am.broadcastIntent(null, intent, null, finishedReceiver,
8816                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8817                                null, finishedReceiver != null, false, id);
8818                    }
8819                } catch (RemoteException ex) {
8820                }
8821            }
8822        });
8823    }
8824
8825    /**
8826     * Check if the external storage media is available. This is true if there
8827     * is a mounted external storage medium or if the external storage is
8828     * emulated.
8829     */
8830    private boolean isExternalMediaAvailable() {
8831        return mMediaMounted || Environment.isExternalStorageEmulated();
8832    }
8833
8834    @Override
8835    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8836        // writer
8837        synchronized (mPackages) {
8838            if (!isExternalMediaAvailable()) {
8839                // If the external storage is no longer mounted at this point,
8840                // the caller may not have been able to delete all of this
8841                // packages files and can not delete any more.  Bail.
8842                return null;
8843            }
8844            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8845            if (lastPackage != null) {
8846                pkgs.remove(lastPackage);
8847            }
8848            if (pkgs.size() > 0) {
8849                return pkgs.get(0);
8850            }
8851        }
8852        return null;
8853    }
8854
8855    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8856        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8857                userId, andCode ? 1 : 0, packageName);
8858        if (mSystemReady) {
8859            msg.sendToTarget();
8860        } else {
8861            if (mPostSystemReadyMessages == null) {
8862                mPostSystemReadyMessages = new ArrayList<>();
8863            }
8864            mPostSystemReadyMessages.add(msg);
8865        }
8866    }
8867
8868    void startCleaningPackages() {
8869        // reader
8870        synchronized (mPackages) {
8871            if (!isExternalMediaAvailable()) {
8872                return;
8873            }
8874            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8875                return;
8876            }
8877        }
8878        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8879        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8880        IActivityManager am = ActivityManagerNative.getDefault();
8881        if (am != null) {
8882            try {
8883                am.startService(null, intent, null, UserHandle.USER_OWNER);
8884            } catch (RemoteException e) {
8885            }
8886        }
8887    }
8888
8889    @Override
8890    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8891            int installFlags, String installerPackageName, VerificationParams verificationParams,
8892            String packageAbiOverride) {
8893        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8894                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8895    }
8896
8897    @Override
8898    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8899            int installFlags, String installerPackageName, VerificationParams verificationParams,
8900            String packageAbiOverride, int userId) {
8901        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8902
8903        final int callingUid = Binder.getCallingUid();
8904        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8905
8906        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8907            try {
8908                if (observer != null) {
8909                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8910                }
8911            } catch (RemoteException re) {
8912            }
8913            return;
8914        }
8915
8916        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8917            installFlags |= PackageManager.INSTALL_FROM_ADB;
8918
8919        } else {
8920            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8921            // about installerPackageName.
8922
8923            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8924            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8925        }
8926
8927        UserHandle user;
8928        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8929            user = UserHandle.ALL;
8930        } else {
8931            user = new UserHandle(userId);
8932        }
8933
8934        // Only system components can circumvent runtime permissions when installing.
8935        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
8936                && mContext.checkCallingOrSelfPermission(Manifest.permission
8937                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
8938            throw new SecurityException("You need the "
8939                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
8940                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
8941        }
8942
8943        verificationParams.setInstallerUid(callingUid);
8944
8945        final File originFile = new File(originPath);
8946        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8947
8948        final Message msg = mHandler.obtainMessage(INIT_COPY);
8949        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
8950                null, verificationParams, user, packageAbiOverride);
8951        mHandler.sendMessage(msg);
8952    }
8953
8954    void installStage(String packageName, File stagedDir, String stagedCid,
8955            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8956            String installerPackageName, int installerUid, UserHandle user) {
8957        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8958                params.referrerUri, installerUid, null);
8959
8960        final OriginInfo origin;
8961        if (stagedDir != null) {
8962            origin = OriginInfo.fromStagedFile(stagedDir);
8963        } else {
8964            origin = OriginInfo.fromStagedContainer(stagedCid);
8965        }
8966
8967        final Message msg = mHandler.obtainMessage(INIT_COPY);
8968        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
8969                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8970        mHandler.sendMessage(msg);
8971    }
8972
8973    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8974        Bundle extras = new Bundle(1);
8975        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8976
8977        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8978                packageName, extras, null, null, new int[] {userId});
8979        try {
8980            IActivityManager am = ActivityManagerNative.getDefault();
8981            final boolean isSystem =
8982                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8983            if (isSystem && am.isUserRunning(userId, false)) {
8984                // The just-installed/enabled app is bundled on the system, so presumed
8985                // to be able to run automatically without needing an explicit launch.
8986                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8987                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8988                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8989                        .setPackage(packageName);
8990                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8991                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
8992            }
8993        } catch (RemoteException e) {
8994            // shouldn't happen
8995            Slog.w(TAG, "Unable to bootstrap installed package", e);
8996        }
8997    }
8998
8999    @Override
9000    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9001            int userId) {
9002        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9003        PackageSetting pkgSetting;
9004        final int uid = Binder.getCallingUid();
9005        enforceCrossUserPermission(uid, userId, true, true,
9006                "setApplicationHiddenSetting for user " + userId);
9007
9008        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9009            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9010            return false;
9011        }
9012
9013        long callingId = Binder.clearCallingIdentity();
9014        try {
9015            boolean sendAdded = false;
9016            boolean sendRemoved = false;
9017            // writer
9018            synchronized (mPackages) {
9019                pkgSetting = mSettings.mPackages.get(packageName);
9020                if (pkgSetting == null) {
9021                    return false;
9022                }
9023                if (pkgSetting.getHidden(userId) != hidden) {
9024                    pkgSetting.setHidden(hidden, userId);
9025                    mSettings.writePackageRestrictionsLPr(userId);
9026                    if (hidden) {
9027                        sendRemoved = true;
9028                    } else {
9029                        sendAdded = true;
9030                    }
9031                }
9032            }
9033            if (sendAdded) {
9034                sendPackageAddedForUser(packageName, pkgSetting, userId);
9035                return true;
9036            }
9037            if (sendRemoved) {
9038                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9039                        "hiding pkg");
9040                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9041            }
9042        } finally {
9043            Binder.restoreCallingIdentity(callingId);
9044        }
9045        return false;
9046    }
9047
9048    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9049            int userId) {
9050        final PackageRemovedInfo info = new PackageRemovedInfo();
9051        info.removedPackage = packageName;
9052        info.removedUsers = new int[] {userId};
9053        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9054        info.sendBroadcast(false, false, false);
9055    }
9056
9057    /**
9058     * Returns true if application is not found or there was an error. Otherwise it returns
9059     * the hidden state of the package for the given user.
9060     */
9061    @Override
9062    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9063        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9064        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9065                false, "getApplicationHidden for user " + userId);
9066        PackageSetting pkgSetting;
9067        long callingId = Binder.clearCallingIdentity();
9068        try {
9069            // writer
9070            synchronized (mPackages) {
9071                pkgSetting = mSettings.mPackages.get(packageName);
9072                if (pkgSetting == null) {
9073                    return true;
9074                }
9075                return pkgSetting.getHidden(userId);
9076            }
9077        } finally {
9078            Binder.restoreCallingIdentity(callingId);
9079        }
9080    }
9081
9082    /**
9083     * @hide
9084     */
9085    @Override
9086    public int installExistingPackageAsUser(String packageName, int userId) {
9087        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9088                null);
9089        PackageSetting pkgSetting;
9090        final int uid = Binder.getCallingUid();
9091        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9092                + userId);
9093        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9094            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9095        }
9096
9097        long callingId = Binder.clearCallingIdentity();
9098        try {
9099            boolean sendAdded = false;
9100
9101            // writer
9102            synchronized (mPackages) {
9103                pkgSetting = mSettings.mPackages.get(packageName);
9104                if (pkgSetting == null) {
9105                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9106                }
9107                if (!pkgSetting.getInstalled(userId)) {
9108                    pkgSetting.setInstalled(true, userId);
9109                    pkgSetting.setHidden(false, userId);
9110                    mSettings.writePackageRestrictionsLPr(userId);
9111                    sendAdded = true;
9112                }
9113            }
9114
9115            if (sendAdded) {
9116                sendPackageAddedForUser(packageName, pkgSetting, userId);
9117            }
9118        } finally {
9119            Binder.restoreCallingIdentity(callingId);
9120        }
9121
9122        return PackageManager.INSTALL_SUCCEEDED;
9123    }
9124
9125    boolean isUserRestricted(int userId, String restrictionKey) {
9126        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9127        if (restrictions.getBoolean(restrictionKey, false)) {
9128            Log.w(TAG, "User is restricted: " + restrictionKey);
9129            return true;
9130        }
9131        return false;
9132    }
9133
9134    @Override
9135    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9136        mContext.enforceCallingOrSelfPermission(
9137                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9138                "Only package verification agents can verify applications");
9139
9140        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9141        final PackageVerificationResponse response = new PackageVerificationResponse(
9142                verificationCode, Binder.getCallingUid());
9143        msg.arg1 = id;
9144        msg.obj = response;
9145        mHandler.sendMessage(msg);
9146    }
9147
9148    @Override
9149    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9150            long millisecondsToDelay) {
9151        mContext.enforceCallingOrSelfPermission(
9152                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9153                "Only package verification agents can extend verification timeouts");
9154
9155        final PackageVerificationState state = mPendingVerification.get(id);
9156        final PackageVerificationResponse response = new PackageVerificationResponse(
9157                verificationCodeAtTimeout, Binder.getCallingUid());
9158
9159        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9160            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9161        }
9162        if (millisecondsToDelay < 0) {
9163            millisecondsToDelay = 0;
9164        }
9165        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9166                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9167            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9168        }
9169
9170        if ((state != null) && !state.timeoutExtended()) {
9171            state.extendTimeout();
9172
9173            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9174            msg.arg1 = id;
9175            msg.obj = response;
9176            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9177        }
9178    }
9179
9180    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9181            int verificationCode, UserHandle user) {
9182        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9183        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9184        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9185        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9186        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9187
9188        mContext.sendBroadcastAsUser(intent, user,
9189                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9190    }
9191
9192    private ComponentName matchComponentForVerifier(String packageName,
9193            List<ResolveInfo> receivers) {
9194        ActivityInfo targetReceiver = null;
9195
9196        final int NR = receivers.size();
9197        for (int i = 0; i < NR; i++) {
9198            final ResolveInfo info = receivers.get(i);
9199            if (info.activityInfo == null) {
9200                continue;
9201            }
9202
9203            if (packageName.equals(info.activityInfo.packageName)) {
9204                targetReceiver = info.activityInfo;
9205                break;
9206            }
9207        }
9208
9209        if (targetReceiver == null) {
9210            return null;
9211        }
9212
9213        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9214    }
9215
9216    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9217            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9218        if (pkgInfo.verifiers.length == 0) {
9219            return null;
9220        }
9221
9222        final int N = pkgInfo.verifiers.length;
9223        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9224        for (int i = 0; i < N; i++) {
9225            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9226
9227            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9228                    receivers);
9229            if (comp == null) {
9230                continue;
9231            }
9232
9233            final int verifierUid = getUidForVerifier(verifierInfo);
9234            if (verifierUid == -1) {
9235                continue;
9236            }
9237
9238            if (DEBUG_VERIFY) {
9239                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9240                        + " with the correct signature");
9241            }
9242            sufficientVerifiers.add(comp);
9243            verificationState.addSufficientVerifier(verifierUid);
9244        }
9245
9246        return sufficientVerifiers;
9247    }
9248
9249    private int getUidForVerifier(VerifierInfo verifierInfo) {
9250        synchronized (mPackages) {
9251            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9252            if (pkg == null) {
9253                return -1;
9254            } else if (pkg.mSignatures.length != 1) {
9255                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9256                        + " has more than one signature; ignoring");
9257                return -1;
9258            }
9259
9260            /*
9261             * If the public key of the package's signature does not match
9262             * our expected public key, then this is a different package and
9263             * we should skip.
9264             */
9265
9266            final byte[] expectedPublicKey;
9267            try {
9268                final Signature verifierSig = pkg.mSignatures[0];
9269                final PublicKey publicKey = verifierSig.getPublicKey();
9270                expectedPublicKey = publicKey.getEncoded();
9271            } catch (CertificateException e) {
9272                return -1;
9273            }
9274
9275            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9276
9277            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9278                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9279                        + " does not have the expected public key; ignoring");
9280                return -1;
9281            }
9282
9283            return pkg.applicationInfo.uid;
9284        }
9285    }
9286
9287    @Override
9288    public void finishPackageInstall(int token) {
9289        enforceSystemOrRoot("Only the system is allowed to finish installs");
9290
9291        if (DEBUG_INSTALL) {
9292            Slog.v(TAG, "BM finishing package install for " + token);
9293        }
9294
9295        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9296        mHandler.sendMessage(msg);
9297    }
9298
9299    /**
9300     * Get the verification agent timeout.
9301     *
9302     * @return verification timeout in milliseconds
9303     */
9304    private long getVerificationTimeout() {
9305        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9306                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9307                DEFAULT_VERIFICATION_TIMEOUT);
9308    }
9309
9310    /**
9311     * Get the default verification agent response code.
9312     *
9313     * @return default verification response code
9314     */
9315    private int getDefaultVerificationResponse() {
9316        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9317                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9318                DEFAULT_VERIFICATION_RESPONSE);
9319    }
9320
9321    /**
9322     * Check whether or not package verification has been enabled.
9323     *
9324     * @return true if verification should be performed
9325     */
9326    private boolean isVerificationEnabled(int userId, int installFlags) {
9327        if (!DEFAULT_VERIFY_ENABLE) {
9328            return false;
9329        }
9330
9331        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9332
9333        // Check if installing from ADB
9334        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9335            // Do not run verification in a test harness environment
9336            if (ActivityManager.isRunningInTestHarness()) {
9337                return false;
9338            }
9339            if (ensureVerifyAppsEnabled) {
9340                return true;
9341            }
9342            // Check if the developer does not want package verification for ADB installs
9343            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9344                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9345                return false;
9346            }
9347        }
9348
9349        if (ensureVerifyAppsEnabled) {
9350            return true;
9351        }
9352
9353        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9354                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9355    }
9356
9357    @Override
9358    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9359            throws RemoteException {
9360        mContext.enforceCallingOrSelfPermission(
9361                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9362                "Only intentfilter verification agents can verify applications");
9363
9364        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9365        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9366                Binder.getCallingUid(), verificationCode, failedDomains);
9367        msg.arg1 = id;
9368        msg.obj = response;
9369        mHandler.sendMessage(msg);
9370    }
9371
9372    @Override
9373    public int getIntentVerificationStatus(String packageName, int userId) {
9374        synchronized (mPackages) {
9375            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9376        }
9377    }
9378
9379    @Override
9380    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9381        boolean result = false;
9382        synchronized (mPackages) {
9383            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9384        }
9385        if (result) {
9386            scheduleWritePackageRestrictionsLocked(userId);
9387        }
9388        return result;
9389    }
9390
9391    @Override
9392    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9393        synchronized (mPackages) {
9394            return mSettings.getIntentFilterVerificationsLPr(packageName);
9395        }
9396    }
9397
9398    @Override
9399    public List<IntentFilter> getAllIntentFilters(String packageName) {
9400        if (TextUtils.isEmpty(packageName)) {
9401            return Collections.<IntentFilter>emptyList();
9402        }
9403        synchronized (mPackages) {
9404            PackageParser.Package pkg = mPackages.get(packageName);
9405            if (pkg == null || pkg.activities == null) {
9406                return Collections.<IntentFilter>emptyList();
9407            }
9408            final int count = pkg.activities.size();
9409            ArrayList<IntentFilter> result = new ArrayList<>();
9410            for (int n=0; n<count; n++) {
9411                PackageParser.Activity activity = pkg.activities.get(n);
9412                if (activity.intents != null || activity.intents.size() > 0) {
9413                    result.addAll(activity.intents);
9414                }
9415            }
9416            return result;
9417        }
9418    }
9419
9420    @Override
9421    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9422        synchronized (mPackages) {
9423            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9424            if (packageName != null) {
9425                result |= updateIntentVerificationStatus(packageName,
9426                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9427                        UserHandle.myUserId());
9428            }
9429            return result;
9430        }
9431    }
9432
9433    @Override
9434    public String getDefaultBrowserPackageName(int userId) {
9435        synchronized (mPackages) {
9436            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9437        }
9438    }
9439
9440    /**
9441     * Get the "allow unknown sources" setting.
9442     *
9443     * @return the current "allow unknown sources" setting
9444     */
9445    private int getUnknownSourcesSettings() {
9446        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9447                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9448                -1);
9449    }
9450
9451    @Override
9452    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9453        final int uid = Binder.getCallingUid();
9454        // writer
9455        synchronized (mPackages) {
9456            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9457            if (targetPackageSetting == null) {
9458                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9459            }
9460
9461            PackageSetting installerPackageSetting;
9462            if (installerPackageName != null) {
9463                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9464                if (installerPackageSetting == null) {
9465                    throw new IllegalArgumentException("Unknown installer package: "
9466                            + installerPackageName);
9467                }
9468            } else {
9469                installerPackageSetting = null;
9470            }
9471
9472            Signature[] callerSignature;
9473            Object obj = mSettings.getUserIdLPr(uid);
9474            if (obj != null) {
9475                if (obj instanceof SharedUserSetting) {
9476                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9477                } else if (obj instanceof PackageSetting) {
9478                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9479                } else {
9480                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9481                }
9482            } else {
9483                throw new SecurityException("Unknown calling uid " + uid);
9484            }
9485
9486            // Verify: can't set installerPackageName to a package that is
9487            // not signed with the same cert as the caller.
9488            if (installerPackageSetting != null) {
9489                if (compareSignatures(callerSignature,
9490                        installerPackageSetting.signatures.mSignatures)
9491                        != PackageManager.SIGNATURE_MATCH) {
9492                    throw new SecurityException(
9493                            "Caller does not have same cert as new installer package "
9494                            + installerPackageName);
9495                }
9496            }
9497
9498            // Verify: if target already has an installer package, it must
9499            // be signed with the same cert as the caller.
9500            if (targetPackageSetting.installerPackageName != null) {
9501                PackageSetting setting = mSettings.mPackages.get(
9502                        targetPackageSetting.installerPackageName);
9503                // If the currently set package isn't valid, then it's always
9504                // okay to change it.
9505                if (setting != null) {
9506                    if (compareSignatures(callerSignature,
9507                            setting.signatures.mSignatures)
9508                            != PackageManager.SIGNATURE_MATCH) {
9509                        throw new SecurityException(
9510                                "Caller does not have same cert as old installer package "
9511                                + targetPackageSetting.installerPackageName);
9512                    }
9513                }
9514            }
9515
9516            // Okay!
9517            targetPackageSetting.installerPackageName = installerPackageName;
9518            scheduleWriteSettingsLocked();
9519        }
9520    }
9521
9522    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9523        // Queue up an async operation since the package installation may take a little while.
9524        mHandler.post(new Runnable() {
9525            public void run() {
9526                mHandler.removeCallbacks(this);
9527                 // Result object to be returned
9528                PackageInstalledInfo res = new PackageInstalledInfo();
9529                res.returnCode = currentStatus;
9530                res.uid = -1;
9531                res.pkg = null;
9532                res.removedInfo = new PackageRemovedInfo();
9533                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9534                    args.doPreInstall(res.returnCode);
9535                    synchronized (mInstallLock) {
9536                        installPackageLI(args, res);
9537                    }
9538                    args.doPostInstall(res.returnCode, res.uid);
9539                }
9540
9541                // A restore should be performed at this point if (a) the install
9542                // succeeded, (b) the operation is not an update, and (c) the new
9543                // package has not opted out of backup participation.
9544                final boolean update = res.removedInfo.removedPackage != null;
9545                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9546                boolean doRestore = !update
9547                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9548
9549                // Set up the post-install work request bookkeeping.  This will be used
9550                // and cleaned up by the post-install event handling regardless of whether
9551                // there's a restore pass performed.  Token values are >= 1.
9552                int token;
9553                if (mNextInstallToken < 0) mNextInstallToken = 1;
9554                token = mNextInstallToken++;
9555
9556                PostInstallData data = new PostInstallData(args, res);
9557                mRunningInstalls.put(token, data);
9558                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9559
9560                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9561                    // Pass responsibility to the Backup Manager.  It will perform a
9562                    // restore if appropriate, then pass responsibility back to the
9563                    // Package Manager to run the post-install observer callbacks
9564                    // and broadcasts.
9565                    IBackupManager bm = IBackupManager.Stub.asInterface(
9566                            ServiceManager.getService(Context.BACKUP_SERVICE));
9567                    if (bm != null) {
9568                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9569                                + " to BM for possible restore");
9570                        try {
9571                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9572                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9573                            } else {
9574                                doRestore = false;
9575                            }
9576                        } catch (RemoteException e) {
9577                            // can't happen; the backup manager is local
9578                        } catch (Exception e) {
9579                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9580                            doRestore = false;
9581                        }
9582                    } else {
9583                        Slog.e(TAG, "Backup Manager not found!");
9584                        doRestore = false;
9585                    }
9586                }
9587
9588                if (!doRestore) {
9589                    // No restore possible, or the Backup Manager was mysteriously not
9590                    // available -- just fire the post-install work request directly.
9591                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9592                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9593                    mHandler.sendMessage(msg);
9594                }
9595            }
9596        });
9597    }
9598
9599    private abstract class HandlerParams {
9600        private static final int MAX_RETRIES = 4;
9601
9602        /**
9603         * Number of times startCopy() has been attempted and had a non-fatal
9604         * error.
9605         */
9606        private int mRetries = 0;
9607
9608        /** User handle for the user requesting the information or installation. */
9609        private final UserHandle mUser;
9610
9611        HandlerParams(UserHandle user) {
9612            mUser = user;
9613        }
9614
9615        UserHandle getUser() {
9616            return mUser;
9617        }
9618
9619        final boolean startCopy() {
9620            boolean res;
9621            try {
9622                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9623
9624                if (++mRetries > MAX_RETRIES) {
9625                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9626                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9627                    handleServiceError();
9628                    return false;
9629                } else {
9630                    handleStartCopy();
9631                    res = true;
9632                }
9633            } catch (RemoteException e) {
9634                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9635                mHandler.sendEmptyMessage(MCS_RECONNECT);
9636                res = false;
9637            }
9638            handleReturnCode();
9639            return res;
9640        }
9641
9642        final void serviceError() {
9643            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9644            handleServiceError();
9645            handleReturnCode();
9646        }
9647
9648        abstract void handleStartCopy() throws RemoteException;
9649        abstract void handleServiceError();
9650        abstract void handleReturnCode();
9651    }
9652
9653    class MeasureParams extends HandlerParams {
9654        private final PackageStats mStats;
9655        private boolean mSuccess;
9656
9657        private final IPackageStatsObserver mObserver;
9658
9659        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9660            super(new UserHandle(stats.userHandle));
9661            mObserver = observer;
9662            mStats = stats;
9663        }
9664
9665        @Override
9666        public String toString() {
9667            return "MeasureParams{"
9668                + Integer.toHexString(System.identityHashCode(this))
9669                + " " + mStats.packageName + "}";
9670        }
9671
9672        @Override
9673        void handleStartCopy() throws RemoteException {
9674            synchronized (mInstallLock) {
9675                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9676            }
9677
9678            if (mSuccess) {
9679                final boolean mounted;
9680                if (Environment.isExternalStorageEmulated()) {
9681                    mounted = true;
9682                } else {
9683                    final String status = Environment.getExternalStorageState();
9684                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9685                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9686                }
9687
9688                if (mounted) {
9689                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9690
9691                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9692                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9693
9694                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9695                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9696
9697                    // Always subtract cache size, since it's a subdirectory
9698                    mStats.externalDataSize -= mStats.externalCacheSize;
9699
9700                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9701                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9702
9703                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9704                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9705                }
9706            }
9707        }
9708
9709        @Override
9710        void handleReturnCode() {
9711            if (mObserver != null) {
9712                try {
9713                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9714                } catch (RemoteException e) {
9715                    Slog.i(TAG, "Observer no longer exists.");
9716                }
9717            }
9718        }
9719
9720        @Override
9721        void handleServiceError() {
9722            Slog.e(TAG, "Could not measure application " + mStats.packageName
9723                            + " external storage");
9724        }
9725    }
9726
9727    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9728            throws RemoteException {
9729        long result = 0;
9730        for (File path : paths) {
9731            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9732        }
9733        return result;
9734    }
9735
9736    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9737        for (File path : paths) {
9738            try {
9739                mcs.clearDirectory(path.getAbsolutePath());
9740            } catch (RemoteException e) {
9741            }
9742        }
9743    }
9744
9745    static class OriginInfo {
9746        /**
9747         * Location where install is coming from, before it has been
9748         * copied/renamed into place. This could be a single monolithic APK
9749         * file, or a cluster directory. This location may be untrusted.
9750         */
9751        final File file;
9752        final String cid;
9753
9754        /**
9755         * Flag indicating that {@link #file} or {@link #cid} has already been
9756         * staged, meaning downstream users don't need to defensively copy the
9757         * contents.
9758         */
9759        final boolean staged;
9760
9761        /**
9762         * Flag indicating that {@link #file} or {@link #cid} is an already
9763         * installed app that is being moved.
9764         */
9765        final boolean existing;
9766
9767        final String resolvedPath;
9768        final File resolvedFile;
9769
9770        static OriginInfo fromNothing() {
9771            return new OriginInfo(null, null, false, false);
9772        }
9773
9774        static OriginInfo fromUntrustedFile(File file) {
9775            return new OriginInfo(file, null, false, false);
9776        }
9777
9778        static OriginInfo fromExistingFile(File file) {
9779            return new OriginInfo(file, null, false, true);
9780        }
9781
9782        static OriginInfo fromStagedFile(File file) {
9783            return new OriginInfo(file, null, true, false);
9784        }
9785
9786        static OriginInfo fromStagedContainer(String cid) {
9787            return new OriginInfo(null, cid, true, false);
9788        }
9789
9790        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9791            this.file = file;
9792            this.cid = cid;
9793            this.staged = staged;
9794            this.existing = existing;
9795
9796            if (cid != null) {
9797                resolvedPath = PackageHelper.getSdDir(cid);
9798                resolvedFile = new File(resolvedPath);
9799            } else if (file != null) {
9800                resolvedPath = file.getAbsolutePath();
9801                resolvedFile = file;
9802            } else {
9803                resolvedPath = null;
9804                resolvedFile = null;
9805            }
9806        }
9807    }
9808
9809    class MoveInfo {
9810        final int moveId;
9811        final String fromUuid;
9812        final String toUuid;
9813        final String packageName;
9814        final String dataAppName;
9815        final int appId;
9816        final String seinfo;
9817
9818        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9819                String dataAppName, int appId, String seinfo) {
9820            this.moveId = moveId;
9821            this.fromUuid = fromUuid;
9822            this.toUuid = toUuid;
9823            this.packageName = packageName;
9824            this.dataAppName = dataAppName;
9825            this.appId = appId;
9826            this.seinfo = seinfo;
9827        }
9828    }
9829
9830    class InstallParams extends HandlerParams {
9831        final OriginInfo origin;
9832        final MoveInfo move;
9833        final IPackageInstallObserver2 observer;
9834        int installFlags;
9835        final String installerPackageName;
9836        final String volumeUuid;
9837        final VerificationParams verificationParams;
9838        private InstallArgs mArgs;
9839        private int mRet;
9840        final String packageAbiOverride;
9841
9842        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
9843                int installFlags, String installerPackageName, String volumeUuid,
9844                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9845            super(user);
9846            this.origin = origin;
9847            this.move = move;
9848            this.observer = observer;
9849            this.installFlags = installFlags;
9850            this.installerPackageName = installerPackageName;
9851            this.volumeUuid = volumeUuid;
9852            this.verificationParams = verificationParams;
9853            this.packageAbiOverride = packageAbiOverride;
9854        }
9855
9856        @Override
9857        public String toString() {
9858            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9859                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9860        }
9861
9862        public ManifestDigest getManifestDigest() {
9863            if (verificationParams == null) {
9864                return null;
9865            }
9866            return verificationParams.getManifestDigest();
9867        }
9868
9869        private int installLocationPolicy(PackageInfoLite pkgLite) {
9870            String packageName = pkgLite.packageName;
9871            int installLocation = pkgLite.installLocation;
9872            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9873            // reader
9874            synchronized (mPackages) {
9875                PackageParser.Package pkg = mPackages.get(packageName);
9876                if (pkg != null) {
9877                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9878                        // Check for downgrading.
9879                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9880                            try {
9881                                checkDowngrade(pkg, pkgLite);
9882                            } catch (PackageManagerException e) {
9883                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9884                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9885                            }
9886                        }
9887                        // Check for updated system application.
9888                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9889                            if (onSd) {
9890                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9891                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9892                            }
9893                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9894                        } else {
9895                            if (onSd) {
9896                                // Install flag overrides everything.
9897                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9898                            }
9899                            // If current upgrade specifies particular preference
9900                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9901                                // Application explicitly specified internal.
9902                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9903                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9904                                // App explictly prefers external. Let policy decide
9905                            } else {
9906                                // Prefer previous location
9907                                if (isExternal(pkg)) {
9908                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9909                                }
9910                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9911                            }
9912                        }
9913                    } else {
9914                        // Invalid install. Return error code
9915                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9916                    }
9917                }
9918            }
9919            // All the special cases have been taken care of.
9920            // Return result based on recommended install location.
9921            if (onSd) {
9922                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9923            }
9924            return pkgLite.recommendedInstallLocation;
9925        }
9926
9927        /*
9928         * Invoke remote method to get package information and install
9929         * location values. Override install location based on default
9930         * policy if needed and then create install arguments based
9931         * on the install location.
9932         */
9933        public void handleStartCopy() throws RemoteException {
9934            int ret = PackageManager.INSTALL_SUCCEEDED;
9935
9936            // If we're already staged, we've firmly committed to an install location
9937            if (origin.staged) {
9938                if (origin.file != null) {
9939                    installFlags |= PackageManager.INSTALL_INTERNAL;
9940                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9941                } else if (origin.cid != null) {
9942                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9943                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9944                } else {
9945                    throw new IllegalStateException("Invalid stage location");
9946                }
9947            }
9948
9949            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9950            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9951
9952            PackageInfoLite pkgLite = null;
9953
9954            if (onInt && onSd) {
9955                // Check if both bits are set.
9956                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9957                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9958            } else {
9959                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9960                        packageAbiOverride);
9961
9962                /*
9963                 * If we have too little free space, try to free cache
9964                 * before giving up.
9965                 */
9966                if (!origin.staged && pkgLite.recommendedInstallLocation
9967                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9968                    // TODO: focus freeing disk space on the target device
9969                    final StorageManager storage = StorageManager.from(mContext);
9970                    final long lowThreshold = storage.getStorageLowBytes(
9971                            Environment.getDataDirectory());
9972
9973                    final long sizeBytes = mContainerService.calculateInstalledSize(
9974                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9975
9976                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
9977                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9978                                installFlags, packageAbiOverride);
9979                    }
9980
9981                    /*
9982                     * The cache free must have deleted the file we
9983                     * downloaded to install.
9984                     *
9985                     * TODO: fix the "freeCache" call to not delete
9986                     *       the file we care about.
9987                     */
9988                    if (pkgLite.recommendedInstallLocation
9989                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9990                        pkgLite.recommendedInstallLocation
9991                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9992                    }
9993                }
9994            }
9995
9996            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9997                int loc = pkgLite.recommendedInstallLocation;
9998                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9999                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10000                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10001                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10002                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10003                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10004                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10005                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10006                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10007                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10008                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10009                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10010                } else {
10011                    // Override with defaults if needed.
10012                    loc = installLocationPolicy(pkgLite);
10013                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10014                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10015                    } else if (!onSd && !onInt) {
10016                        // Override install location with flags
10017                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10018                            // Set the flag to install on external media.
10019                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10020                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10021                        } else {
10022                            // Make sure the flag for installing on external
10023                            // media is unset
10024                            installFlags |= PackageManager.INSTALL_INTERNAL;
10025                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10026                        }
10027                    }
10028                }
10029            }
10030
10031            final InstallArgs args = createInstallArgs(this);
10032            mArgs = args;
10033
10034            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10035                 /*
10036                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10037                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10038                 */
10039                int userIdentifier = getUser().getIdentifier();
10040                if (userIdentifier == UserHandle.USER_ALL
10041                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10042                    userIdentifier = UserHandle.USER_OWNER;
10043                }
10044
10045                /*
10046                 * Determine if we have any installed package verifiers. If we
10047                 * do, then we'll defer to them to verify the packages.
10048                 */
10049                final int requiredUid = mRequiredVerifierPackage == null ? -1
10050                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10051                if (!origin.existing && requiredUid != -1
10052                        && isVerificationEnabled(userIdentifier, installFlags)) {
10053                    final Intent verification = new Intent(
10054                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10055                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10056                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10057                            PACKAGE_MIME_TYPE);
10058                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10059
10060                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10061                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10062                            0 /* TODO: Which userId? */);
10063
10064                    if (DEBUG_VERIFY) {
10065                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10066                                + verification.toString() + " with " + pkgLite.verifiers.length
10067                                + " optional verifiers");
10068                    }
10069
10070                    final int verificationId = mPendingVerificationToken++;
10071
10072                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10073
10074                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10075                            installerPackageName);
10076
10077                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10078                            installFlags);
10079
10080                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10081                            pkgLite.packageName);
10082
10083                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10084                            pkgLite.versionCode);
10085
10086                    if (verificationParams != null) {
10087                        if (verificationParams.getVerificationURI() != null) {
10088                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10089                                 verificationParams.getVerificationURI());
10090                        }
10091                        if (verificationParams.getOriginatingURI() != null) {
10092                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10093                                  verificationParams.getOriginatingURI());
10094                        }
10095                        if (verificationParams.getReferrer() != null) {
10096                            verification.putExtra(Intent.EXTRA_REFERRER,
10097                                  verificationParams.getReferrer());
10098                        }
10099                        if (verificationParams.getOriginatingUid() >= 0) {
10100                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10101                                  verificationParams.getOriginatingUid());
10102                        }
10103                        if (verificationParams.getInstallerUid() >= 0) {
10104                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10105                                  verificationParams.getInstallerUid());
10106                        }
10107                    }
10108
10109                    final PackageVerificationState verificationState = new PackageVerificationState(
10110                            requiredUid, args);
10111
10112                    mPendingVerification.append(verificationId, verificationState);
10113
10114                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10115                            receivers, verificationState);
10116
10117                    /*
10118                     * If any sufficient verifiers were listed in the package
10119                     * manifest, attempt to ask them.
10120                     */
10121                    if (sufficientVerifiers != null) {
10122                        final int N = sufficientVerifiers.size();
10123                        if (N == 0) {
10124                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10125                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10126                        } else {
10127                            for (int i = 0; i < N; i++) {
10128                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10129
10130                                final Intent sufficientIntent = new Intent(verification);
10131                                sufficientIntent.setComponent(verifierComponent);
10132
10133                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10134                            }
10135                        }
10136                    }
10137
10138                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10139                            mRequiredVerifierPackage, receivers);
10140                    if (ret == PackageManager.INSTALL_SUCCEEDED
10141                            && mRequiredVerifierPackage != null) {
10142                        /*
10143                         * Send the intent to the required verification agent,
10144                         * but only start the verification timeout after the
10145                         * target BroadcastReceivers have run.
10146                         */
10147                        verification.setComponent(requiredVerifierComponent);
10148                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10149                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10150                                new BroadcastReceiver() {
10151                                    @Override
10152                                    public void onReceive(Context context, Intent intent) {
10153                                        final Message msg = mHandler
10154                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10155                                        msg.arg1 = verificationId;
10156                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10157                                    }
10158                                }, null, 0, null, null);
10159
10160                        /*
10161                         * We don't want the copy to proceed until verification
10162                         * succeeds, so null out this field.
10163                         */
10164                        mArgs = null;
10165                    }
10166                } else {
10167                    /*
10168                     * No package verification is enabled, so immediately start
10169                     * the remote call to initiate copy using temporary file.
10170                     */
10171                    ret = args.copyApk(mContainerService, true);
10172                }
10173            }
10174
10175            mRet = ret;
10176        }
10177
10178        @Override
10179        void handleReturnCode() {
10180            // If mArgs is null, then MCS couldn't be reached. When it
10181            // reconnects, it will try again to install. At that point, this
10182            // will succeed.
10183            if (mArgs != null) {
10184                processPendingInstall(mArgs, mRet);
10185            }
10186        }
10187
10188        @Override
10189        void handleServiceError() {
10190            mArgs = createInstallArgs(this);
10191            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10192        }
10193
10194        public boolean isForwardLocked() {
10195            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10196        }
10197    }
10198
10199    /**
10200     * Used during creation of InstallArgs
10201     *
10202     * @param installFlags package installation flags
10203     * @return true if should be installed on external storage
10204     */
10205    private static boolean installOnExternalAsec(int installFlags) {
10206        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10207            return false;
10208        }
10209        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10210            return true;
10211        }
10212        return false;
10213    }
10214
10215    /**
10216     * Used during creation of InstallArgs
10217     *
10218     * @param installFlags package installation flags
10219     * @return true if should be installed as forward locked
10220     */
10221    private static boolean installForwardLocked(int installFlags) {
10222        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10223    }
10224
10225    private InstallArgs createInstallArgs(InstallParams params) {
10226        if (params.move != null) {
10227            return new MoveInstallArgs(params);
10228        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10229            return new AsecInstallArgs(params);
10230        } else {
10231            return new FileInstallArgs(params);
10232        }
10233    }
10234
10235    /**
10236     * Create args that describe an existing installed package. Typically used
10237     * when cleaning up old installs, or used as a move source.
10238     */
10239    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10240            String resourcePath, String[] instructionSets) {
10241        final boolean isInAsec;
10242        if (installOnExternalAsec(installFlags)) {
10243            /* Apps on SD card are always in ASEC containers. */
10244            isInAsec = true;
10245        } else if (installForwardLocked(installFlags)
10246                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10247            /*
10248             * Forward-locked apps are only in ASEC containers if they're the
10249             * new style
10250             */
10251            isInAsec = true;
10252        } else {
10253            isInAsec = false;
10254        }
10255
10256        if (isInAsec) {
10257            return new AsecInstallArgs(codePath, instructionSets,
10258                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10259        } else {
10260            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10261        }
10262    }
10263
10264    static abstract class InstallArgs {
10265        /** @see InstallParams#origin */
10266        final OriginInfo origin;
10267        /** @see InstallParams#move */
10268        final MoveInfo move;
10269
10270        final IPackageInstallObserver2 observer;
10271        // Always refers to PackageManager flags only
10272        final int installFlags;
10273        final String installerPackageName;
10274        final String volumeUuid;
10275        final ManifestDigest manifestDigest;
10276        final UserHandle user;
10277        final String abiOverride;
10278
10279        // The list of instruction sets supported by this app. This is currently
10280        // only used during the rmdex() phase to clean up resources. We can get rid of this
10281        // if we move dex files under the common app path.
10282        /* nullable */ String[] instructionSets;
10283
10284        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10285                int installFlags, String installerPackageName, String volumeUuid,
10286                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10287                String abiOverride) {
10288            this.origin = origin;
10289            this.move = move;
10290            this.installFlags = installFlags;
10291            this.observer = observer;
10292            this.installerPackageName = installerPackageName;
10293            this.volumeUuid = volumeUuid;
10294            this.manifestDigest = manifestDigest;
10295            this.user = user;
10296            this.instructionSets = instructionSets;
10297            this.abiOverride = abiOverride;
10298        }
10299
10300        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10301        abstract int doPreInstall(int status);
10302
10303        /**
10304         * Rename package into final resting place. All paths on the given
10305         * scanned package should be updated to reflect the rename.
10306         */
10307        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10308        abstract int doPostInstall(int status, int uid);
10309
10310        /** @see PackageSettingBase#codePathString */
10311        abstract String getCodePath();
10312        /** @see PackageSettingBase#resourcePathString */
10313        abstract String getResourcePath();
10314
10315        // Need installer lock especially for dex file removal.
10316        abstract void cleanUpResourcesLI();
10317        abstract boolean doPostDeleteLI(boolean delete);
10318
10319        /**
10320         * Called before the source arguments are copied. This is used mostly
10321         * for MoveParams when it needs to read the source file to put it in the
10322         * destination.
10323         */
10324        int doPreCopy() {
10325            return PackageManager.INSTALL_SUCCEEDED;
10326        }
10327
10328        /**
10329         * Called after the source arguments are copied. This is used mostly for
10330         * MoveParams when it needs to read the source file to put it in the
10331         * destination.
10332         *
10333         * @return
10334         */
10335        int doPostCopy(int uid) {
10336            return PackageManager.INSTALL_SUCCEEDED;
10337        }
10338
10339        protected boolean isFwdLocked() {
10340            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10341        }
10342
10343        protected boolean isExternalAsec() {
10344            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10345        }
10346
10347        UserHandle getUser() {
10348            return user;
10349        }
10350    }
10351
10352    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10353        if (!allCodePaths.isEmpty()) {
10354            if (instructionSets == null) {
10355                throw new IllegalStateException("instructionSet == null");
10356            }
10357            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10358            for (String codePath : allCodePaths) {
10359                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10360                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10361                    if (retCode < 0) {
10362                        Slog.w(TAG, "Couldn't remove dex file for package: "
10363                                + " at location " + codePath + ", retcode=" + retCode);
10364                        // we don't consider this to be a failure of the core package deletion
10365                    }
10366                }
10367            }
10368        }
10369    }
10370
10371    /**
10372     * Logic to handle installation of non-ASEC applications, including copying
10373     * and renaming logic.
10374     */
10375    class FileInstallArgs extends InstallArgs {
10376        private File codeFile;
10377        private File resourceFile;
10378
10379        // Example topology:
10380        // /data/app/com.example/base.apk
10381        // /data/app/com.example/split_foo.apk
10382        // /data/app/com.example/lib/arm/libfoo.so
10383        // /data/app/com.example/lib/arm64/libfoo.so
10384        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10385
10386        /** New install */
10387        FileInstallArgs(InstallParams params) {
10388            super(params.origin, params.move, params.observer, params.installFlags,
10389                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10390                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10391            if (isFwdLocked()) {
10392                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10393            }
10394        }
10395
10396        /** Existing install */
10397        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10398            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10399                    null);
10400            this.codeFile = (codePath != null) ? new File(codePath) : null;
10401            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10402        }
10403
10404        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10405            if (origin.staged) {
10406                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10407                codeFile = origin.file;
10408                resourceFile = origin.file;
10409                return PackageManager.INSTALL_SUCCEEDED;
10410            }
10411
10412            try {
10413                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10414                codeFile = tempDir;
10415                resourceFile = tempDir;
10416            } catch (IOException e) {
10417                Slog.w(TAG, "Failed to create copy file: " + e);
10418                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10419            }
10420
10421            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10422                @Override
10423                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10424                    if (!FileUtils.isValidExtFilename(name)) {
10425                        throw new IllegalArgumentException("Invalid filename: " + name);
10426                    }
10427                    try {
10428                        final File file = new File(codeFile, name);
10429                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10430                                O_RDWR | O_CREAT, 0644);
10431                        Os.chmod(file.getAbsolutePath(), 0644);
10432                        return new ParcelFileDescriptor(fd);
10433                    } catch (ErrnoException e) {
10434                        throw new RemoteException("Failed to open: " + e.getMessage());
10435                    }
10436                }
10437            };
10438
10439            int ret = PackageManager.INSTALL_SUCCEEDED;
10440            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10441            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10442                Slog.e(TAG, "Failed to copy package");
10443                return ret;
10444            }
10445
10446            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10447            NativeLibraryHelper.Handle handle = null;
10448            try {
10449                handle = NativeLibraryHelper.Handle.create(codeFile);
10450                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10451                        abiOverride);
10452            } catch (IOException e) {
10453                Slog.e(TAG, "Copying native libraries failed", e);
10454                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10455            } finally {
10456                IoUtils.closeQuietly(handle);
10457            }
10458
10459            return ret;
10460        }
10461
10462        int doPreInstall(int status) {
10463            if (status != PackageManager.INSTALL_SUCCEEDED) {
10464                cleanUp();
10465            }
10466            return status;
10467        }
10468
10469        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10470            if (status != PackageManager.INSTALL_SUCCEEDED) {
10471                cleanUp();
10472                return false;
10473            }
10474
10475            final File targetDir = codeFile.getParentFile();
10476            final File beforeCodeFile = codeFile;
10477            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10478
10479            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10480            try {
10481                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10482            } catch (ErrnoException e) {
10483                Slog.w(TAG, "Failed to rename", e);
10484                return false;
10485            }
10486
10487            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10488                Slog.w(TAG, "Failed to restorecon");
10489                return false;
10490            }
10491
10492            // Reflect the rename internally
10493            codeFile = afterCodeFile;
10494            resourceFile = afterCodeFile;
10495
10496            // Reflect the rename in scanned details
10497            pkg.codePath = afterCodeFile.getAbsolutePath();
10498            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10499                    pkg.baseCodePath);
10500            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10501                    pkg.splitCodePaths);
10502
10503            // Reflect the rename in app info
10504            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10505            pkg.applicationInfo.setCodePath(pkg.codePath);
10506            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10507            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10508            pkg.applicationInfo.setResourcePath(pkg.codePath);
10509            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10510            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10511
10512            return true;
10513        }
10514
10515        int doPostInstall(int status, int uid) {
10516            if (status != PackageManager.INSTALL_SUCCEEDED) {
10517                cleanUp();
10518            }
10519            return status;
10520        }
10521
10522        @Override
10523        String getCodePath() {
10524            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10525        }
10526
10527        @Override
10528        String getResourcePath() {
10529            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10530        }
10531
10532        private boolean cleanUp() {
10533            if (codeFile == null || !codeFile.exists()) {
10534                return false;
10535            }
10536
10537            if (codeFile.isDirectory()) {
10538                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10539            } else {
10540                codeFile.delete();
10541            }
10542
10543            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10544                resourceFile.delete();
10545            }
10546
10547            return true;
10548        }
10549
10550        void cleanUpResourcesLI() {
10551            // Try enumerating all code paths before deleting
10552            List<String> allCodePaths = Collections.EMPTY_LIST;
10553            if (codeFile != null && codeFile.exists()) {
10554                try {
10555                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10556                    allCodePaths = pkg.getAllCodePaths();
10557                } catch (PackageParserException e) {
10558                    // Ignored; we tried our best
10559                }
10560            }
10561
10562            cleanUp();
10563            removeDexFiles(allCodePaths, instructionSets);
10564        }
10565
10566        boolean doPostDeleteLI(boolean delete) {
10567            // XXX err, shouldn't we respect the delete flag?
10568            cleanUpResourcesLI();
10569            return true;
10570        }
10571    }
10572
10573    private boolean isAsecExternal(String cid) {
10574        final String asecPath = PackageHelper.getSdFilesystem(cid);
10575        return !asecPath.startsWith(mAsecInternalPath);
10576    }
10577
10578    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10579            PackageManagerException {
10580        if (copyRet < 0) {
10581            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10582                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10583                throw new PackageManagerException(copyRet, message);
10584            }
10585        }
10586    }
10587
10588    /**
10589     * Extract the MountService "container ID" from the full code path of an
10590     * .apk.
10591     */
10592    static String cidFromCodePath(String fullCodePath) {
10593        int eidx = fullCodePath.lastIndexOf("/");
10594        String subStr1 = fullCodePath.substring(0, eidx);
10595        int sidx = subStr1.lastIndexOf("/");
10596        return subStr1.substring(sidx+1, eidx);
10597    }
10598
10599    /**
10600     * Logic to handle installation of ASEC applications, including copying and
10601     * renaming logic.
10602     */
10603    class AsecInstallArgs extends InstallArgs {
10604        static final String RES_FILE_NAME = "pkg.apk";
10605        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10606
10607        String cid;
10608        String packagePath;
10609        String resourcePath;
10610
10611        /** New install */
10612        AsecInstallArgs(InstallParams params) {
10613            super(params.origin, params.move, params.observer, params.installFlags,
10614                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10615                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10616        }
10617
10618        /** Existing install */
10619        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10620                        boolean isExternal, boolean isForwardLocked) {
10621            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10622                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10623                    instructionSets, null);
10624            // Hackily pretend we're still looking at a full code path
10625            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10626                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10627            }
10628
10629            // Extract cid from fullCodePath
10630            int eidx = fullCodePath.lastIndexOf("/");
10631            String subStr1 = fullCodePath.substring(0, eidx);
10632            int sidx = subStr1.lastIndexOf("/");
10633            cid = subStr1.substring(sidx+1, eidx);
10634            setMountPath(subStr1);
10635        }
10636
10637        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10638            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10639                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10640                    instructionSets, null);
10641            this.cid = cid;
10642            setMountPath(PackageHelper.getSdDir(cid));
10643        }
10644
10645        void createCopyFile() {
10646            cid = mInstallerService.allocateExternalStageCidLegacy();
10647        }
10648
10649        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10650            if (origin.staged) {
10651                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
10652                cid = origin.cid;
10653                setMountPath(PackageHelper.getSdDir(cid));
10654                return PackageManager.INSTALL_SUCCEEDED;
10655            }
10656
10657            if (temp) {
10658                createCopyFile();
10659            } else {
10660                /*
10661                 * Pre-emptively destroy the container since it's destroyed if
10662                 * copying fails due to it existing anyway.
10663                 */
10664                PackageHelper.destroySdDir(cid);
10665            }
10666
10667            final String newMountPath = imcs.copyPackageToContainer(
10668                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10669                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10670
10671            if (newMountPath != null) {
10672                setMountPath(newMountPath);
10673                return PackageManager.INSTALL_SUCCEEDED;
10674            } else {
10675                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10676            }
10677        }
10678
10679        @Override
10680        String getCodePath() {
10681            return packagePath;
10682        }
10683
10684        @Override
10685        String getResourcePath() {
10686            return resourcePath;
10687        }
10688
10689        int doPreInstall(int status) {
10690            if (status != PackageManager.INSTALL_SUCCEEDED) {
10691                // Destroy container
10692                PackageHelper.destroySdDir(cid);
10693            } else {
10694                boolean mounted = PackageHelper.isContainerMounted(cid);
10695                if (!mounted) {
10696                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10697                            Process.SYSTEM_UID);
10698                    if (newMountPath != null) {
10699                        setMountPath(newMountPath);
10700                    } else {
10701                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10702                    }
10703                }
10704            }
10705            return status;
10706        }
10707
10708        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10709            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10710            String newMountPath = null;
10711            if (PackageHelper.isContainerMounted(cid)) {
10712                // Unmount the container
10713                if (!PackageHelper.unMountSdDir(cid)) {
10714                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10715                    return false;
10716                }
10717            }
10718            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10719                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10720                        " which might be stale. Will try to clean up.");
10721                // Clean up the stale container and proceed to recreate.
10722                if (!PackageHelper.destroySdDir(newCacheId)) {
10723                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10724                    return false;
10725                }
10726                // Successfully cleaned up stale container. Try to rename again.
10727                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10728                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10729                            + " inspite of cleaning it up.");
10730                    return false;
10731                }
10732            }
10733            if (!PackageHelper.isContainerMounted(newCacheId)) {
10734                Slog.w(TAG, "Mounting container " + newCacheId);
10735                newMountPath = PackageHelper.mountSdDir(newCacheId,
10736                        getEncryptKey(), Process.SYSTEM_UID);
10737            } else {
10738                newMountPath = PackageHelper.getSdDir(newCacheId);
10739            }
10740            if (newMountPath == null) {
10741                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10742                return false;
10743            }
10744            Log.i(TAG, "Succesfully renamed " + cid +
10745                    " to " + newCacheId +
10746                    " at new path: " + newMountPath);
10747            cid = newCacheId;
10748
10749            final File beforeCodeFile = new File(packagePath);
10750            setMountPath(newMountPath);
10751            final File afterCodeFile = new File(packagePath);
10752
10753            // Reflect the rename in scanned details
10754            pkg.codePath = afterCodeFile.getAbsolutePath();
10755            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10756                    pkg.baseCodePath);
10757            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10758                    pkg.splitCodePaths);
10759
10760            // Reflect the rename in app info
10761            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10762            pkg.applicationInfo.setCodePath(pkg.codePath);
10763            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10764            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10765            pkg.applicationInfo.setResourcePath(pkg.codePath);
10766            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10767            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10768
10769            return true;
10770        }
10771
10772        private void setMountPath(String mountPath) {
10773            final File mountFile = new File(mountPath);
10774
10775            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10776            if (monolithicFile.exists()) {
10777                packagePath = monolithicFile.getAbsolutePath();
10778                if (isFwdLocked()) {
10779                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10780                } else {
10781                    resourcePath = packagePath;
10782                }
10783            } else {
10784                packagePath = mountFile.getAbsolutePath();
10785                resourcePath = packagePath;
10786            }
10787        }
10788
10789        int doPostInstall(int status, int uid) {
10790            if (status != PackageManager.INSTALL_SUCCEEDED) {
10791                cleanUp();
10792            } else {
10793                final int groupOwner;
10794                final String protectedFile;
10795                if (isFwdLocked()) {
10796                    groupOwner = UserHandle.getSharedAppGid(uid);
10797                    protectedFile = RES_FILE_NAME;
10798                } else {
10799                    groupOwner = -1;
10800                    protectedFile = null;
10801                }
10802
10803                if (uid < Process.FIRST_APPLICATION_UID
10804                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10805                    Slog.e(TAG, "Failed to finalize " + cid);
10806                    PackageHelper.destroySdDir(cid);
10807                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10808                }
10809
10810                boolean mounted = PackageHelper.isContainerMounted(cid);
10811                if (!mounted) {
10812                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10813                }
10814            }
10815            return status;
10816        }
10817
10818        private void cleanUp() {
10819            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10820
10821            // Destroy secure container
10822            PackageHelper.destroySdDir(cid);
10823        }
10824
10825        private List<String> getAllCodePaths() {
10826            final File codeFile = new File(getCodePath());
10827            if (codeFile != null && codeFile.exists()) {
10828                try {
10829                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10830                    return pkg.getAllCodePaths();
10831                } catch (PackageParserException e) {
10832                    // Ignored; we tried our best
10833                }
10834            }
10835            return Collections.EMPTY_LIST;
10836        }
10837
10838        void cleanUpResourcesLI() {
10839            // Enumerate all code paths before deleting
10840            cleanUpResourcesLI(getAllCodePaths());
10841        }
10842
10843        private void cleanUpResourcesLI(List<String> allCodePaths) {
10844            cleanUp();
10845            removeDexFiles(allCodePaths, instructionSets);
10846        }
10847
10848        String getPackageName() {
10849            return getAsecPackageName(cid);
10850        }
10851
10852        boolean doPostDeleteLI(boolean delete) {
10853            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10854            final List<String> allCodePaths = getAllCodePaths();
10855            boolean mounted = PackageHelper.isContainerMounted(cid);
10856            if (mounted) {
10857                // Unmount first
10858                if (PackageHelper.unMountSdDir(cid)) {
10859                    mounted = false;
10860                }
10861            }
10862            if (!mounted && delete) {
10863                cleanUpResourcesLI(allCodePaths);
10864            }
10865            return !mounted;
10866        }
10867
10868        @Override
10869        int doPreCopy() {
10870            if (isFwdLocked()) {
10871                if (!PackageHelper.fixSdPermissions(cid,
10872                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10873                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10874                }
10875            }
10876
10877            return PackageManager.INSTALL_SUCCEEDED;
10878        }
10879
10880        @Override
10881        int doPostCopy(int uid) {
10882            if (isFwdLocked()) {
10883                if (uid < Process.FIRST_APPLICATION_UID
10884                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10885                                RES_FILE_NAME)) {
10886                    Slog.e(TAG, "Failed to finalize " + cid);
10887                    PackageHelper.destroySdDir(cid);
10888                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10889                }
10890            }
10891
10892            return PackageManager.INSTALL_SUCCEEDED;
10893        }
10894    }
10895
10896    /**
10897     * Logic to handle movement of existing installed applications.
10898     */
10899    class MoveInstallArgs extends InstallArgs {
10900        private File codeFile;
10901        private File resourceFile;
10902
10903        /** New install */
10904        MoveInstallArgs(InstallParams params) {
10905            super(params.origin, params.move, params.observer, params.installFlags,
10906                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10907                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10908        }
10909
10910        int copyApk(IMediaContainerService imcs, boolean temp) {
10911            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
10912                    + move.fromUuid + " to " + move.toUuid);
10913            synchronized (mInstaller) {
10914                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
10915                        move.dataAppName, move.appId, move.seinfo) != 0) {
10916                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10917                }
10918            }
10919
10920            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
10921            resourceFile = codeFile;
10922            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
10923
10924            return PackageManager.INSTALL_SUCCEEDED;
10925        }
10926
10927        int doPreInstall(int status) {
10928            if (status != PackageManager.INSTALL_SUCCEEDED) {
10929                cleanUp();
10930            }
10931            return status;
10932        }
10933
10934        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10935            if (status != PackageManager.INSTALL_SUCCEEDED) {
10936                cleanUp();
10937                return false;
10938            }
10939
10940            // Reflect the move in app info
10941            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10942            pkg.applicationInfo.setCodePath(pkg.codePath);
10943            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10944            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10945            pkg.applicationInfo.setResourcePath(pkg.codePath);
10946            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10947            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10948
10949            return true;
10950        }
10951
10952        int doPostInstall(int status, int uid) {
10953            if (status != PackageManager.INSTALL_SUCCEEDED) {
10954                cleanUp();
10955            }
10956            return status;
10957        }
10958
10959        @Override
10960        String getCodePath() {
10961            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10962        }
10963
10964        @Override
10965        String getResourcePath() {
10966            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10967        }
10968
10969        private boolean cleanUp() {
10970            if (codeFile == null || !codeFile.exists()) {
10971                return false;
10972            }
10973
10974            if (codeFile.isDirectory()) {
10975                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10976            } else {
10977                codeFile.delete();
10978            }
10979
10980            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10981                resourceFile.delete();
10982            }
10983
10984            return true;
10985        }
10986
10987        void cleanUpResourcesLI() {
10988            cleanUp();
10989        }
10990
10991        boolean doPostDeleteLI(boolean delete) {
10992            // XXX err, shouldn't we respect the delete flag?
10993            cleanUpResourcesLI();
10994            return true;
10995        }
10996    }
10997
10998    static String getAsecPackageName(String packageCid) {
10999        int idx = packageCid.lastIndexOf("-");
11000        if (idx == -1) {
11001            return packageCid;
11002        }
11003        return packageCid.substring(0, idx);
11004    }
11005
11006    // Utility method used to create code paths based on package name and available index.
11007    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11008        String idxStr = "";
11009        int idx = 1;
11010        // Fall back to default value of idx=1 if prefix is not
11011        // part of oldCodePath
11012        if (oldCodePath != null) {
11013            String subStr = oldCodePath;
11014            // Drop the suffix right away
11015            if (suffix != null && subStr.endsWith(suffix)) {
11016                subStr = subStr.substring(0, subStr.length() - suffix.length());
11017            }
11018            // If oldCodePath already contains prefix find out the
11019            // ending index to either increment or decrement.
11020            int sidx = subStr.lastIndexOf(prefix);
11021            if (sidx != -1) {
11022                subStr = subStr.substring(sidx + prefix.length());
11023                if (subStr != null) {
11024                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11025                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11026                    }
11027                    try {
11028                        idx = Integer.parseInt(subStr);
11029                        if (idx <= 1) {
11030                            idx++;
11031                        } else {
11032                            idx--;
11033                        }
11034                    } catch(NumberFormatException e) {
11035                    }
11036                }
11037            }
11038        }
11039        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11040        return prefix + idxStr;
11041    }
11042
11043    private File getNextCodePath(File targetDir, String packageName) {
11044        int suffix = 1;
11045        File result;
11046        do {
11047            result = new File(targetDir, packageName + "-" + suffix);
11048            suffix++;
11049        } while (result.exists());
11050        return result;
11051    }
11052
11053    // Utility method that returns the relative package path with respect
11054    // to the installation directory. Like say for /data/data/com.test-1.apk
11055    // string com.test-1 is returned.
11056    static String deriveCodePathName(String codePath) {
11057        if (codePath == null) {
11058            return null;
11059        }
11060        final File codeFile = new File(codePath);
11061        final String name = codeFile.getName();
11062        if (codeFile.isDirectory()) {
11063            return name;
11064        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11065            final int lastDot = name.lastIndexOf('.');
11066            return name.substring(0, lastDot);
11067        } else {
11068            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11069            return null;
11070        }
11071    }
11072
11073    class PackageInstalledInfo {
11074        String name;
11075        int uid;
11076        // The set of users that originally had this package installed.
11077        int[] origUsers;
11078        // The set of users that now have this package installed.
11079        int[] newUsers;
11080        PackageParser.Package pkg;
11081        int returnCode;
11082        String returnMsg;
11083        PackageRemovedInfo removedInfo;
11084
11085        public void setError(int code, String msg) {
11086            returnCode = code;
11087            returnMsg = msg;
11088            Slog.w(TAG, msg);
11089        }
11090
11091        public void setError(String msg, PackageParserException e) {
11092            returnCode = e.error;
11093            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11094            Slog.w(TAG, msg, e);
11095        }
11096
11097        public void setError(String msg, PackageManagerException e) {
11098            returnCode = e.error;
11099            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11100            Slog.w(TAG, msg, e);
11101        }
11102
11103        // In some error cases we want to convey more info back to the observer
11104        String origPackage;
11105        String origPermission;
11106    }
11107
11108    /*
11109     * Install a non-existing package.
11110     */
11111    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11112            UserHandle user, String installerPackageName, String volumeUuid,
11113            PackageInstalledInfo res) {
11114        // Remember this for later, in case we need to rollback this install
11115        String pkgName = pkg.packageName;
11116
11117        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11118        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11119                UserHandle.USER_OWNER).exists();
11120        synchronized(mPackages) {
11121            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11122                // A package with the same name is already installed, though
11123                // it has been renamed to an older name.  The package we
11124                // are trying to install should be installed as an update to
11125                // the existing one, but that has not been requested, so bail.
11126                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11127                        + " without first uninstalling package running as "
11128                        + mSettings.mRenamedPackages.get(pkgName));
11129                return;
11130            }
11131            if (mPackages.containsKey(pkgName)) {
11132                // Don't allow installation over an existing package with the same name.
11133                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11134                        + " without first uninstalling.");
11135                return;
11136            }
11137        }
11138
11139        try {
11140            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11141                    System.currentTimeMillis(), user);
11142
11143            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11144            // delete the partially installed application. the data directory will have to be
11145            // restored if it was already existing
11146            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11147                // remove package from internal structures.  Note that we want deletePackageX to
11148                // delete the package data and cache directories that it created in
11149                // scanPackageLocked, unless those directories existed before we even tried to
11150                // install.
11151                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11152                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11153                                res.removedInfo, true);
11154            }
11155
11156        } catch (PackageManagerException e) {
11157            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11158        }
11159    }
11160
11161    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11162        // Can't rotate keys during boot or if sharedUser.
11163        if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null
11164                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11165            return false;
11166        }
11167        // app is using upgradeKeySets; make sure all are valid
11168        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11169        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11170        for (int i = 0; i < upgradeKeySets.length; i++) {
11171            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11172                Slog.wtf(TAG, "Package "
11173                         + (oldPs.name != null ? oldPs.name : "<null>")
11174                         + " contains upgrade-key-set reference to unknown key-set: "
11175                         + upgradeKeySets[i]
11176                         + " reverting to signatures check.");
11177                return false;
11178            }
11179        }
11180        return true;
11181    }
11182
11183    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11184        // Upgrade keysets are being used.  Determine if new package has a superset of the
11185        // required keys.
11186        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11187        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11188        for (int i = 0; i < upgradeKeySets.length; i++) {
11189            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11190            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11191                return true;
11192            }
11193        }
11194        return false;
11195    }
11196
11197    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11198            UserHandle user, String installerPackageName, String volumeUuid,
11199            PackageInstalledInfo res) {
11200        final PackageParser.Package oldPackage;
11201        final String pkgName = pkg.packageName;
11202        final int[] allUsers;
11203        final boolean[] perUserInstalled;
11204        final boolean weFroze;
11205
11206        // First find the old package info and check signatures
11207        synchronized(mPackages) {
11208            oldPackage = mPackages.get(pkgName);
11209            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11210            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11211            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11212                if(!checkUpgradeKeySetLP(ps, pkg)) {
11213                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11214                            "New package not signed by keys specified by upgrade-keysets: "
11215                            + pkgName);
11216                    return;
11217                }
11218            } else {
11219                // default to original signature matching
11220                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11221                    != PackageManager.SIGNATURE_MATCH) {
11222                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11223                            "New package has a different signature: " + pkgName);
11224                    return;
11225                }
11226            }
11227
11228            // In case of rollback, remember per-user/profile install state
11229            allUsers = sUserManager.getUserIds();
11230            perUserInstalled = new boolean[allUsers.length];
11231            for (int i = 0; i < allUsers.length; i++) {
11232                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11233            }
11234
11235            // Mark the app as frozen to prevent launching during the upgrade
11236            // process, and then kill all running instances
11237            if (!ps.frozen) {
11238                ps.frozen = true;
11239                weFroze = true;
11240            } else {
11241                weFroze = false;
11242            }
11243        }
11244
11245        // Now that we're guarded by frozen state, kill app during upgrade
11246        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11247
11248        try {
11249            boolean sysPkg = (isSystemApp(oldPackage));
11250            if (sysPkg) {
11251                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11252                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11253            } else {
11254                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11255                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11256            }
11257        } finally {
11258            // Regardless of success or failure of upgrade steps above, always
11259            // unfreeze the package if we froze it
11260            if (weFroze) {
11261                unfreezePackage(pkgName);
11262            }
11263        }
11264    }
11265
11266    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11267            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11268            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11269            String volumeUuid, PackageInstalledInfo res) {
11270        String pkgName = deletedPackage.packageName;
11271        boolean deletedPkg = true;
11272        boolean updatedSettings = false;
11273
11274        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11275                + deletedPackage);
11276        long origUpdateTime;
11277        if (pkg.mExtras != null) {
11278            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11279        } else {
11280            origUpdateTime = 0;
11281        }
11282
11283        // First delete the existing package while retaining the data directory
11284        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11285                res.removedInfo, true)) {
11286            // If the existing package wasn't successfully deleted
11287            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11288            deletedPkg = false;
11289        } else {
11290            // Successfully deleted the old package; proceed with replace.
11291
11292            // If deleted package lived in a container, give users a chance to
11293            // relinquish resources before killing.
11294            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11295                if (DEBUG_INSTALL) {
11296                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11297                }
11298                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11299                final ArrayList<String> pkgList = new ArrayList<String>(1);
11300                pkgList.add(deletedPackage.applicationInfo.packageName);
11301                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11302            }
11303
11304            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11305            try {
11306                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11307                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11308                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11309                        perUserInstalled, res, user);
11310                updatedSettings = true;
11311            } catch (PackageManagerException e) {
11312                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11313            }
11314        }
11315
11316        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11317            // remove package from internal structures.  Note that we want deletePackageX to
11318            // delete the package data and cache directories that it created in
11319            // scanPackageLocked, unless those directories existed before we even tried to
11320            // install.
11321            if(updatedSettings) {
11322                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11323                deletePackageLI(
11324                        pkgName, null, true, allUsers, perUserInstalled,
11325                        PackageManager.DELETE_KEEP_DATA,
11326                                res.removedInfo, true);
11327            }
11328            // Since we failed to install the new package we need to restore the old
11329            // package that we deleted.
11330            if (deletedPkg) {
11331                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11332                File restoreFile = new File(deletedPackage.codePath);
11333                // Parse old package
11334                boolean oldExternal = isExternal(deletedPackage);
11335                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11336                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11337                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11338                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11339                try {
11340                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11341                } catch (PackageManagerException e) {
11342                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11343                            + e.getMessage());
11344                    return;
11345                }
11346                // Restore of old package succeeded. Update permissions.
11347                // writer
11348                synchronized (mPackages) {
11349                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11350                            UPDATE_PERMISSIONS_ALL);
11351                    // can downgrade to reader
11352                    mSettings.writeLPr();
11353                }
11354                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11355            }
11356        }
11357    }
11358
11359    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11360            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11361            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11362            String volumeUuid, PackageInstalledInfo res) {
11363        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11364                + ", old=" + deletedPackage);
11365        boolean disabledSystem = false;
11366        boolean updatedSettings = false;
11367        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11368        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11369                != 0) {
11370            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11371        }
11372        String packageName = deletedPackage.packageName;
11373        if (packageName == null) {
11374            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11375                    "Attempt to delete null packageName.");
11376            return;
11377        }
11378        PackageParser.Package oldPkg;
11379        PackageSetting oldPkgSetting;
11380        // reader
11381        synchronized (mPackages) {
11382            oldPkg = mPackages.get(packageName);
11383            oldPkgSetting = mSettings.mPackages.get(packageName);
11384            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11385                    (oldPkgSetting == null)) {
11386                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11387                        "Couldn't find package:" + packageName + " information");
11388                return;
11389            }
11390        }
11391
11392        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11393        res.removedInfo.removedPackage = packageName;
11394        // Remove existing system package
11395        removePackageLI(oldPkgSetting, true);
11396        // writer
11397        synchronized (mPackages) {
11398            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11399            if (!disabledSystem && deletedPackage != null) {
11400                // We didn't need to disable the .apk as a current system package,
11401                // which means we are replacing another update that is already
11402                // installed.  We need to make sure to delete the older one's .apk.
11403                res.removedInfo.args = createInstallArgsForExisting(0,
11404                        deletedPackage.applicationInfo.getCodePath(),
11405                        deletedPackage.applicationInfo.getResourcePath(),
11406                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11407            } else {
11408                res.removedInfo.args = null;
11409            }
11410        }
11411
11412        // Successfully disabled the old package. Now proceed with re-installation
11413        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11414
11415        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11416        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11417
11418        PackageParser.Package newPackage = null;
11419        try {
11420            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11421            if (newPackage.mExtras != null) {
11422                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11423                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11424                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11425
11426                // is the update attempting to change shared user? that isn't going to work...
11427                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11428                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11429                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11430                            + " to " + newPkgSetting.sharedUser);
11431                    updatedSettings = true;
11432                }
11433            }
11434
11435            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11436                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11437                        perUserInstalled, res, user);
11438                updatedSettings = true;
11439            }
11440
11441        } catch (PackageManagerException e) {
11442            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11443        }
11444
11445        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11446            // Re installation failed. Restore old information
11447            // Remove new pkg information
11448            if (newPackage != null) {
11449                removeInstalledPackageLI(newPackage, true);
11450            }
11451            // Add back the old system package
11452            try {
11453                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11454            } catch (PackageManagerException e) {
11455                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11456            }
11457            // Restore the old system information in Settings
11458            synchronized (mPackages) {
11459                if (disabledSystem) {
11460                    mSettings.enableSystemPackageLPw(packageName);
11461                }
11462                if (updatedSettings) {
11463                    mSettings.setInstallerPackageName(packageName,
11464                            oldPkgSetting.installerPackageName);
11465                }
11466                mSettings.writeLPr();
11467            }
11468        }
11469    }
11470
11471    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11472            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11473            UserHandle user) {
11474        String pkgName = newPackage.packageName;
11475        synchronized (mPackages) {
11476            //write settings. the installStatus will be incomplete at this stage.
11477            //note that the new package setting would have already been
11478            //added to mPackages. It hasn't been persisted yet.
11479            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11480            mSettings.writeLPr();
11481        }
11482
11483        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11484
11485        synchronized (mPackages) {
11486            updatePermissionsLPw(newPackage.packageName, newPackage,
11487                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11488                            ? UPDATE_PERMISSIONS_ALL : 0));
11489            // For system-bundled packages, we assume that installing an upgraded version
11490            // of the package implies that the user actually wants to run that new code,
11491            // so we enable the package.
11492            PackageSetting ps = mSettings.mPackages.get(pkgName);
11493            if (ps != null) {
11494                if (isSystemApp(newPackage)) {
11495                    // NB: implicit assumption that system package upgrades apply to all users
11496                    if (DEBUG_INSTALL) {
11497                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11498                    }
11499                    if (res.origUsers != null) {
11500                        for (int userHandle : res.origUsers) {
11501                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11502                                    userHandle, installerPackageName);
11503                        }
11504                    }
11505                    // Also convey the prior install/uninstall state
11506                    if (allUsers != null && perUserInstalled != null) {
11507                        for (int i = 0; i < allUsers.length; i++) {
11508                            if (DEBUG_INSTALL) {
11509                                Slog.d(TAG, "    user " + allUsers[i]
11510                                        + " => " + perUserInstalled[i]);
11511                            }
11512                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11513                        }
11514                        // these install state changes will be persisted in the
11515                        // upcoming call to mSettings.writeLPr().
11516                    }
11517                }
11518                // It's implied that when a user requests installation, they want the app to be
11519                // installed and enabled.
11520                int userId = user.getIdentifier();
11521                if (userId != UserHandle.USER_ALL) {
11522                    ps.setInstalled(true, userId);
11523                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11524                }
11525            }
11526            res.name = pkgName;
11527            res.uid = newPackage.applicationInfo.uid;
11528            res.pkg = newPackage;
11529            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11530            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11531            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11532            //to update install status
11533            mSettings.writeLPr();
11534        }
11535    }
11536
11537    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11538        final int installFlags = args.installFlags;
11539        final String installerPackageName = args.installerPackageName;
11540        final String volumeUuid = args.volumeUuid;
11541        final File tmpPackageFile = new File(args.getCodePath());
11542        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11543        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11544                || (args.volumeUuid != null));
11545        boolean replace = false;
11546        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11547        // Result object to be returned
11548        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11549
11550        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11551        // Retrieve PackageSettings and parse package
11552        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11553                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11554                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11555        PackageParser pp = new PackageParser();
11556        pp.setSeparateProcesses(mSeparateProcesses);
11557        pp.setDisplayMetrics(mMetrics);
11558
11559        final PackageParser.Package pkg;
11560        try {
11561            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11562        } catch (PackageParserException e) {
11563            res.setError("Failed parse during installPackageLI", e);
11564            return;
11565        }
11566
11567        // Mark that we have an install time CPU ABI override.
11568        pkg.cpuAbiOverride = args.abiOverride;
11569
11570        String pkgName = res.name = pkg.packageName;
11571        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11572            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11573                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11574                return;
11575            }
11576        }
11577
11578        try {
11579            pp.collectCertificates(pkg, parseFlags);
11580            pp.collectManifestDigest(pkg);
11581        } catch (PackageParserException e) {
11582            res.setError("Failed collect during installPackageLI", e);
11583            return;
11584        }
11585
11586        /* If the installer passed in a manifest digest, compare it now. */
11587        if (args.manifestDigest != null) {
11588            if (DEBUG_INSTALL) {
11589                final String parsedManifest = pkg.manifestDigest == null ? "null"
11590                        : pkg.manifestDigest.toString();
11591                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11592                        + parsedManifest);
11593            }
11594
11595            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11596                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11597                return;
11598            }
11599        } else if (DEBUG_INSTALL) {
11600            final String parsedManifest = pkg.manifestDigest == null
11601                    ? "null" : pkg.manifestDigest.toString();
11602            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11603        }
11604
11605        // Get rid of all references to package scan path via parser.
11606        pp = null;
11607        String oldCodePath = null;
11608        boolean systemApp = false;
11609        synchronized (mPackages) {
11610            // Check if installing already existing package
11611            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11612                String oldName = mSettings.mRenamedPackages.get(pkgName);
11613                if (pkg.mOriginalPackages != null
11614                        && pkg.mOriginalPackages.contains(oldName)
11615                        && mPackages.containsKey(oldName)) {
11616                    // This package is derived from an original package,
11617                    // and this device has been updating from that original
11618                    // name.  We must continue using the original name, so
11619                    // rename the new package here.
11620                    pkg.setPackageName(oldName);
11621                    pkgName = pkg.packageName;
11622                    replace = true;
11623                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11624                            + oldName + " pkgName=" + pkgName);
11625                } else if (mPackages.containsKey(pkgName)) {
11626                    // This package, under its official name, already exists
11627                    // on the device; we should replace it.
11628                    replace = true;
11629                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11630                }
11631
11632                // Prevent apps opting out from runtime permissions
11633                if (replace) {
11634                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11635                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11636                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11637                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11638                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11639                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11640                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11641                                        + " doesn't support runtime permissions but the old"
11642                                        + " target SDK " + oldTargetSdk + " does.");
11643                        return;
11644                    }
11645                }
11646            }
11647
11648            PackageSetting ps = mSettings.mPackages.get(pkgName);
11649            if (ps != null) {
11650                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11651
11652                // Quick sanity check that we're signed correctly if updating;
11653                // we'll check this again later when scanning, but we want to
11654                // bail early here before tripping over redefined permissions.
11655                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11656                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11657                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11658                                + pkg.packageName + " upgrade keys do not match the "
11659                                + "previously installed version");
11660                        return;
11661                    }
11662                } else {
11663                    try {
11664                        verifySignaturesLP(ps, pkg);
11665                    } catch (PackageManagerException e) {
11666                        res.setError(e.error, e.getMessage());
11667                        return;
11668                    }
11669                }
11670
11671                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11672                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11673                    systemApp = (ps.pkg.applicationInfo.flags &
11674                            ApplicationInfo.FLAG_SYSTEM) != 0;
11675                }
11676                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11677            }
11678
11679            // Check whether the newly-scanned package wants to define an already-defined perm
11680            int N = pkg.permissions.size();
11681            for (int i = N-1; i >= 0; i--) {
11682                PackageParser.Permission perm = pkg.permissions.get(i);
11683                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11684                if (bp != null) {
11685                    // If the defining package is signed with our cert, it's okay.  This
11686                    // also includes the "updating the same package" case, of course.
11687                    // "updating same package" could also involve key-rotation.
11688                    final boolean sigsOk;
11689                    if (bp.sourcePackage.equals(pkg.packageName)
11690                            && (bp.packageSetting instanceof PackageSetting)
11691                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
11692                                    scanFlags))) {
11693                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11694                    } else {
11695                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11696                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11697                    }
11698                    if (!sigsOk) {
11699                        // If the owning package is the system itself, we log but allow
11700                        // install to proceed; we fail the install on all other permission
11701                        // redefinitions.
11702                        if (!bp.sourcePackage.equals("android")) {
11703                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11704                                    + pkg.packageName + " attempting to redeclare permission "
11705                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11706                            res.origPermission = perm.info.name;
11707                            res.origPackage = bp.sourcePackage;
11708                            return;
11709                        } else {
11710                            Slog.w(TAG, "Package " + pkg.packageName
11711                                    + " attempting to redeclare system permission "
11712                                    + perm.info.name + "; ignoring new declaration");
11713                            pkg.permissions.remove(i);
11714                        }
11715                    }
11716                }
11717            }
11718
11719        }
11720
11721        if (systemApp && onExternal) {
11722            // Disable updates to system apps on sdcard
11723            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11724                    "Cannot install updates to system apps on sdcard");
11725            return;
11726        }
11727
11728        if (args.move != null) {
11729            // We did an in-place move, so dex is ready to roll
11730            scanFlags |= SCAN_NO_DEX;
11731            scanFlags |= SCAN_MOVE;
11732        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11733            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11734            scanFlags |= SCAN_NO_DEX;
11735
11736            try {
11737                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
11738                        true /* extract libs */);
11739            } catch (PackageManagerException pme) {
11740                Slog.e(TAG, "Error deriving application ABI", pme);
11741                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
11742                return;
11743            }
11744
11745            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11746            int result = mPackageDexOptimizer
11747                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
11748                            false /* defer */, false /* inclDependencies */);
11749            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11750                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11751                return;
11752            }
11753        }
11754
11755        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11756            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11757            return;
11758        }
11759
11760        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11761
11762        if (replace) {
11763            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11764                    installerPackageName, volumeUuid, res);
11765        } else {
11766            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11767                    args.user, installerPackageName, volumeUuid, res);
11768        }
11769        synchronized (mPackages) {
11770            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11771            if (ps != null) {
11772                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11773            }
11774        }
11775    }
11776
11777    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11778        if (mIntentFilterVerifierComponent == null) {
11779            Slog.w(TAG, "No IntentFilter verification will not be done as "
11780                    + "there is no IntentFilterVerifier available!");
11781            return;
11782        }
11783
11784        final int verifierUid = getPackageUid(
11785                mIntentFilterVerifierComponent.getPackageName(),
11786                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11787
11788        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11789        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11790        msg.obj = pkg;
11791        msg.arg1 = userId;
11792        msg.arg2 = verifierUid;
11793
11794        mHandler.sendMessage(msg);
11795    }
11796
11797    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11798            PackageParser.Package pkg) {
11799        int size = pkg.activities.size();
11800        if (size == 0) {
11801            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11802                    "No activity, so no need to verify any IntentFilter!");
11803            return;
11804        }
11805
11806        final boolean hasDomainURLs = hasDomainURLs(pkg);
11807        if (!hasDomainURLs) {
11808            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11809                    "No domain URLs, so no need to verify any IntentFilter!");
11810            return;
11811        }
11812
11813        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
11814                + " if any IntentFilter from the " + size
11815                + " Activities needs verification ...");
11816
11817        final int verificationId = mIntentFilterVerificationToken++;
11818        int count = 0;
11819        final String packageName = pkg.packageName;
11820        boolean needToVerify = false;
11821
11822        synchronized (mPackages) {
11823            // If any filters need to be verified, then all need to be.
11824            for (PackageParser.Activity a : pkg.activities) {
11825                for (ActivityIntentInfo filter : a.intents) {
11826                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
11827                        if (DEBUG_DOMAIN_VERIFICATION) {
11828                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
11829                        }
11830                        needToVerify = true;
11831                        break;
11832                    }
11833                }
11834            }
11835            if (needToVerify) {
11836                for (PackageParser.Activity a : pkg.activities) {
11837                    for (ActivityIntentInfo filter : a.intents) {
11838                        boolean needsFilterVerification = filter.hasWebDataURI();
11839                        if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11840                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11841                                    "Verification needed for IntentFilter:" + filter.toString());
11842                            mIntentFilterVerifier.addOneIntentFilterVerification(
11843                                    verifierUid, userId, verificationId, filter, packageName);
11844                            count++;
11845                        }
11846                    }
11847                }
11848            }
11849        }
11850
11851        if (count > 0) {
11852            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
11853                    + " IntentFilter verification" + (count > 1 ? "s" : "")
11854                    +  " for userId:" + userId);
11855            mIntentFilterVerifier.startVerifications(userId);
11856        } else {
11857            if (DEBUG_DOMAIN_VERIFICATION) {
11858                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
11859            }
11860        }
11861    }
11862
11863    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11864        final ComponentName cn  = filter.activity.getComponentName();
11865        final String packageName = cn.getPackageName();
11866
11867        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11868                packageName);
11869        if (ivi == null) {
11870            return true;
11871        }
11872        int status = ivi.getStatus();
11873        switch (status) {
11874            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11875            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11876                return true;
11877
11878            default:
11879                // Nothing to do
11880                return false;
11881        }
11882    }
11883
11884    private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) {
11885        return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID
11886                || ((pkg.applicationInfo.privateFlags
11887                        & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0
11888                && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0);
11889    }
11890
11891    private static boolean isMultiArch(PackageSetting ps) {
11892        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11893    }
11894
11895    private static boolean isMultiArch(ApplicationInfo info) {
11896        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11897    }
11898
11899    private static boolean isExternal(PackageParser.Package pkg) {
11900        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11901    }
11902
11903    private static boolean isExternal(PackageSetting ps) {
11904        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11905    }
11906
11907    private static boolean isExternal(ApplicationInfo info) {
11908        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11909    }
11910
11911    private static boolean isSystemApp(PackageParser.Package pkg) {
11912        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11913    }
11914
11915    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11916        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11917    }
11918
11919    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11920        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11921    }
11922
11923    private static boolean isSystemApp(PackageSetting ps) {
11924        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11925    }
11926
11927    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11928        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11929    }
11930
11931    private int packageFlagsToInstallFlags(PackageSetting ps) {
11932        int installFlags = 0;
11933        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11934            // This existing package was an external ASEC install when we have
11935            // the external flag without a UUID
11936            installFlags |= PackageManager.INSTALL_EXTERNAL;
11937        }
11938        if (ps.isForwardLocked()) {
11939            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11940        }
11941        return installFlags;
11942    }
11943
11944    private void deleteTempPackageFiles() {
11945        final FilenameFilter filter = new FilenameFilter() {
11946            public boolean accept(File dir, String name) {
11947                return name.startsWith("vmdl") && name.endsWith(".tmp");
11948            }
11949        };
11950        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11951            file.delete();
11952        }
11953    }
11954
11955    @Override
11956    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11957            int flags) {
11958        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11959                flags);
11960    }
11961
11962    @Override
11963    public void deletePackage(final String packageName,
11964            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11965        mContext.enforceCallingOrSelfPermission(
11966                android.Manifest.permission.DELETE_PACKAGES, null);
11967        final int uid = Binder.getCallingUid();
11968        if (UserHandle.getUserId(uid) != userId) {
11969            mContext.enforceCallingPermission(
11970                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11971                    "deletePackage for user " + userId);
11972        }
11973        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11974            try {
11975                observer.onPackageDeleted(packageName,
11976                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11977            } catch (RemoteException re) {
11978            }
11979            return;
11980        }
11981
11982        boolean uninstallBlocked = false;
11983        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11984            int[] users = sUserManager.getUserIds();
11985            for (int i = 0; i < users.length; ++i) {
11986                if (getBlockUninstallForUser(packageName, users[i])) {
11987                    uninstallBlocked = true;
11988                    break;
11989                }
11990            }
11991        } else {
11992            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11993        }
11994        if (uninstallBlocked) {
11995            try {
11996                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11997                        null);
11998            } catch (RemoteException re) {
11999            }
12000            return;
12001        }
12002
12003        if (DEBUG_REMOVE) {
12004            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12005        }
12006        // Queue up an async operation since the package deletion may take a little while.
12007        mHandler.post(new Runnable() {
12008            public void run() {
12009                mHandler.removeCallbacks(this);
12010                final int returnCode = deletePackageX(packageName, userId, flags);
12011                if (observer != null) {
12012                    try {
12013                        observer.onPackageDeleted(packageName, returnCode, null);
12014                    } catch (RemoteException e) {
12015                        Log.i(TAG, "Observer no longer exists.");
12016                    } //end catch
12017                } //end if
12018            } //end run
12019        });
12020    }
12021
12022    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12023        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12024                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12025        try {
12026            if (dpm != null) {
12027                if (dpm.isDeviceOwner(packageName)) {
12028                    return true;
12029                }
12030                int[] users;
12031                if (userId == UserHandle.USER_ALL) {
12032                    users = sUserManager.getUserIds();
12033                } else {
12034                    users = new int[]{userId};
12035                }
12036                for (int i = 0; i < users.length; ++i) {
12037                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12038                        return true;
12039                    }
12040                }
12041            }
12042        } catch (RemoteException e) {
12043        }
12044        return false;
12045    }
12046
12047    /**
12048     *  This method is an internal method that could be get invoked either
12049     *  to delete an installed package or to clean up a failed installation.
12050     *  After deleting an installed package, a broadcast is sent to notify any
12051     *  listeners that the package has been installed. For cleaning up a failed
12052     *  installation, the broadcast is not necessary since the package's
12053     *  installation wouldn't have sent the initial broadcast either
12054     *  The key steps in deleting a package are
12055     *  deleting the package information in internal structures like mPackages,
12056     *  deleting the packages base directories through installd
12057     *  updating mSettings to reflect current status
12058     *  persisting settings for later use
12059     *  sending a broadcast if necessary
12060     */
12061    private int deletePackageX(String packageName, int userId, int flags) {
12062        final PackageRemovedInfo info = new PackageRemovedInfo();
12063        final boolean res;
12064
12065        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12066                ? UserHandle.ALL : new UserHandle(userId);
12067
12068        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12069            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12070            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12071        }
12072
12073        boolean removedForAllUsers = false;
12074        boolean systemUpdate = false;
12075
12076        // for the uninstall-updates case and restricted profiles, remember the per-
12077        // userhandle installed state
12078        int[] allUsers;
12079        boolean[] perUserInstalled;
12080        synchronized (mPackages) {
12081            PackageSetting ps = mSettings.mPackages.get(packageName);
12082            allUsers = sUserManager.getUserIds();
12083            perUserInstalled = new boolean[allUsers.length];
12084            for (int i = 0; i < allUsers.length; i++) {
12085                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12086            }
12087        }
12088
12089        synchronized (mInstallLock) {
12090            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12091            res = deletePackageLI(packageName, removeForUser,
12092                    true, allUsers, perUserInstalled,
12093                    flags | REMOVE_CHATTY, info, true);
12094            systemUpdate = info.isRemovedPackageSystemUpdate;
12095            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12096                removedForAllUsers = true;
12097            }
12098            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12099                    + " removedForAllUsers=" + removedForAllUsers);
12100        }
12101
12102        if (res) {
12103            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12104
12105            // If the removed package was a system update, the old system package
12106            // was re-enabled; we need to broadcast this information
12107            if (systemUpdate) {
12108                Bundle extras = new Bundle(1);
12109                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12110                        ? info.removedAppId : info.uid);
12111                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12112
12113                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12114                        extras, null, null, null);
12115                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12116                        extras, null, null, null);
12117                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12118                        null, packageName, null, null);
12119            }
12120        }
12121        // Force a gc here.
12122        Runtime.getRuntime().gc();
12123        // Delete the resources here after sending the broadcast to let
12124        // other processes clean up before deleting resources.
12125        if (info.args != null) {
12126            synchronized (mInstallLock) {
12127                info.args.doPostDeleteLI(true);
12128            }
12129        }
12130
12131        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12132    }
12133
12134    class PackageRemovedInfo {
12135        String removedPackage;
12136        int uid = -1;
12137        int removedAppId = -1;
12138        int[] removedUsers = null;
12139        boolean isRemovedPackageSystemUpdate = false;
12140        // Clean up resources deleted packages.
12141        InstallArgs args = null;
12142
12143        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12144            Bundle extras = new Bundle(1);
12145            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12146            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12147            if (replacing) {
12148                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12149            }
12150            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12151            if (removedPackage != null) {
12152                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12153                        extras, null, null, removedUsers);
12154                if (fullRemove && !replacing) {
12155                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12156                            extras, null, null, removedUsers);
12157                }
12158            }
12159            if (removedAppId >= 0) {
12160                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12161                        removedUsers);
12162            }
12163        }
12164    }
12165
12166    /*
12167     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12168     * flag is not set, the data directory is removed as well.
12169     * make sure this flag is set for partially installed apps. If not its meaningless to
12170     * delete a partially installed application.
12171     */
12172    private void removePackageDataLI(PackageSetting ps,
12173            int[] allUserHandles, boolean[] perUserInstalled,
12174            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12175        String packageName = ps.name;
12176        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12177        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12178        // Retrieve object to delete permissions for shared user later on
12179        final PackageSetting deletedPs;
12180        // reader
12181        synchronized (mPackages) {
12182            deletedPs = mSettings.mPackages.get(packageName);
12183            if (outInfo != null) {
12184                outInfo.removedPackage = packageName;
12185                outInfo.removedUsers = deletedPs != null
12186                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12187                        : null;
12188            }
12189        }
12190        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12191            removeDataDirsLI(ps.volumeUuid, packageName);
12192            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12193        }
12194        // writer
12195        synchronized (mPackages) {
12196            if (deletedPs != null) {
12197                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12198                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12199                    clearDefaultBrowserIfNeeded(packageName);
12200                    if (outInfo != null) {
12201                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12202                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12203                    }
12204                    updatePermissionsLPw(deletedPs.name, null, 0);
12205                    if (deletedPs.sharedUser != null) {
12206                        // Remove permissions associated with package. Since runtime
12207                        // permissions are per user we have to kill the removed package
12208                        // or packages running under the shared user of the removed
12209                        // package if revoking the permissions requested only by the removed
12210                        // package is successful and this causes a change in gids.
12211                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12212                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12213                                    userId);
12214                            if (userIdToKill == UserHandle.USER_ALL
12215                                    || userIdToKill >= UserHandle.USER_OWNER) {
12216                                // If gids changed for this user, kill all affected packages.
12217                                mHandler.post(new Runnable() {
12218                                    @Override
12219                                    public void run() {
12220                                        // This has to happen with no lock held.
12221                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12222                                                KILL_APP_REASON_GIDS_CHANGED);
12223                                    }
12224                                });
12225                            break;
12226                            }
12227                        }
12228                    }
12229                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12230                }
12231                // make sure to preserve per-user disabled state if this removal was just
12232                // a downgrade of a system app to the factory package
12233                if (allUserHandles != null && perUserInstalled != null) {
12234                    if (DEBUG_REMOVE) {
12235                        Slog.d(TAG, "Propagating install state across downgrade");
12236                    }
12237                    for (int i = 0; i < allUserHandles.length; i++) {
12238                        if (DEBUG_REMOVE) {
12239                            Slog.d(TAG, "    user " + allUserHandles[i]
12240                                    + " => " + perUserInstalled[i]);
12241                        }
12242                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12243                    }
12244                }
12245            }
12246            // can downgrade to reader
12247            if (writeSettings) {
12248                // Save settings now
12249                mSettings.writeLPr();
12250            }
12251        }
12252        if (outInfo != null) {
12253            // A user ID was deleted here. Go through all users and remove it
12254            // from KeyStore.
12255            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12256        }
12257    }
12258
12259    static boolean locationIsPrivileged(File path) {
12260        try {
12261            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12262                    .getCanonicalPath();
12263            return path.getCanonicalPath().startsWith(privilegedAppDir);
12264        } catch (IOException e) {
12265            Slog.e(TAG, "Unable to access code path " + path);
12266        }
12267        return false;
12268    }
12269
12270    /*
12271     * Tries to delete system package.
12272     */
12273    private boolean deleteSystemPackageLI(PackageSetting newPs,
12274            int[] allUserHandles, boolean[] perUserInstalled,
12275            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12276        final boolean applyUserRestrictions
12277                = (allUserHandles != null) && (perUserInstalled != null);
12278        PackageSetting disabledPs = null;
12279        // Confirm if the system package has been updated
12280        // An updated system app can be deleted. This will also have to restore
12281        // the system pkg from system partition
12282        // reader
12283        synchronized (mPackages) {
12284            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12285        }
12286        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12287                + " disabledPs=" + disabledPs);
12288        if (disabledPs == null) {
12289            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12290            return false;
12291        } else if (DEBUG_REMOVE) {
12292            Slog.d(TAG, "Deleting system pkg from data partition");
12293        }
12294        if (DEBUG_REMOVE) {
12295            if (applyUserRestrictions) {
12296                Slog.d(TAG, "Remembering install states:");
12297                for (int i = 0; i < allUserHandles.length; i++) {
12298                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12299                }
12300            }
12301        }
12302        // Delete the updated package
12303        outInfo.isRemovedPackageSystemUpdate = true;
12304        if (disabledPs.versionCode < newPs.versionCode) {
12305            // Delete data for downgrades
12306            flags &= ~PackageManager.DELETE_KEEP_DATA;
12307        } else {
12308            // Preserve data by setting flag
12309            flags |= PackageManager.DELETE_KEEP_DATA;
12310        }
12311        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12312                allUserHandles, perUserInstalled, outInfo, writeSettings);
12313        if (!ret) {
12314            return false;
12315        }
12316        // writer
12317        synchronized (mPackages) {
12318            // Reinstate the old system package
12319            mSettings.enableSystemPackageLPw(newPs.name);
12320            // Remove any native libraries from the upgraded package.
12321            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12322        }
12323        // Install the system package
12324        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12325        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12326        if (locationIsPrivileged(disabledPs.codePath)) {
12327            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12328        }
12329
12330        final PackageParser.Package newPkg;
12331        try {
12332            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12333        } catch (PackageManagerException e) {
12334            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12335            return false;
12336        }
12337
12338        // writer
12339        synchronized (mPackages) {
12340            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12341            updatePermissionsLPw(newPkg.packageName, newPkg,
12342                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12343            if (applyUserRestrictions) {
12344                if (DEBUG_REMOVE) {
12345                    Slog.d(TAG, "Propagating install state across reinstall");
12346                }
12347                for (int i = 0; i < allUserHandles.length; i++) {
12348                    if (DEBUG_REMOVE) {
12349                        Slog.d(TAG, "    user " + allUserHandles[i]
12350                                + " => " + perUserInstalled[i]);
12351                    }
12352                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12353                }
12354                // Regardless of writeSettings we need to ensure that this restriction
12355                // state propagation is persisted
12356                mSettings.writeAllUsersPackageRestrictionsLPr();
12357            }
12358            // can downgrade to reader here
12359            if (writeSettings) {
12360                mSettings.writeLPr();
12361            }
12362        }
12363        return true;
12364    }
12365
12366    private boolean deleteInstalledPackageLI(PackageSetting ps,
12367            boolean deleteCodeAndResources, int flags,
12368            int[] allUserHandles, boolean[] perUserInstalled,
12369            PackageRemovedInfo outInfo, boolean writeSettings) {
12370        if (outInfo != null) {
12371            outInfo.uid = ps.appId;
12372        }
12373
12374        // Delete package data from internal structures and also remove data if flag is set
12375        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12376
12377        // Delete application code and resources
12378        if (deleteCodeAndResources && (outInfo != null)) {
12379            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12380                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12381            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12382        }
12383        return true;
12384    }
12385
12386    @Override
12387    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12388            int userId) {
12389        mContext.enforceCallingOrSelfPermission(
12390                android.Manifest.permission.DELETE_PACKAGES, null);
12391        synchronized (mPackages) {
12392            PackageSetting ps = mSettings.mPackages.get(packageName);
12393            if (ps == null) {
12394                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12395                return false;
12396            }
12397            if (!ps.getInstalled(userId)) {
12398                // Can't block uninstall for an app that is not installed or enabled.
12399                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12400                return false;
12401            }
12402            ps.setBlockUninstall(blockUninstall, userId);
12403            mSettings.writePackageRestrictionsLPr(userId);
12404        }
12405        return true;
12406    }
12407
12408    @Override
12409    public boolean getBlockUninstallForUser(String packageName, int userId) {
12410        synchronized (mPackages) {
12411            PackageSetting ps = mSettings.mPackages.get(packageName);
12412            if (ps == null) {
12413                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12414                return false;
12415            }
12416            return ps.getBlockUninstall(userId);
12417        }
12418    }
12419
12420    /*
12421     * This method handles package deletion in general
12422     */
12423    private boolean deletePackageLI(String packageName, UserHandle user,
12424            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12425            int flags, PackageRemovedInfo outInfo,
12426            boolean writeSettings) {
12427        if (packageName == null) {
12428            Slog.w(TAG, "Attempt to delete null packageName.");
12429            return false;
12430        }
12431        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12432        PackageSetting ps;
12433        boolean dataOnly = false;
12434        int removeUser = -1;
12435        int appId = -1;
12436        synchronized (mPackages) {
12437            ps = mSettings.mPackages.get(packageName);
12438            if (ps == null) {
12439                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12440                return false;
12441            }
12442            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12443                    && user.getIdentifier() != UserHandle.USER_ALL) {
12444                // The caller is asking that the package only be deleted for a single
12445                // user.  To do this, we just mark its uninstalled state and delete
12446                // its data.  If this is a system app, we only allow this to happen if
12447                // they have set the special DELETE_SYSTEM_APP which requests different
12448                // semantics than normal for uninstalling system apps.
12449                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12450                ps.setUserState(user.getIdentifier(),
12451                        COMPONENT_ENABLED_STATE_DEFAULT,
12452                        false, //installed
12453                        true,  //stopped
12454                        true,  //notLaunched
12455                        false, //hidden
12456                        null, null, null,
12457                        false, // blockUninstall
12458                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12459                if (!isSystemApp(ps)) {
12460                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12461                        // Other user still have this package installed, so all
12462                        // we need to do is clear this user's data and save that
12463                        // it is uninstalled.
12464                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12465                        removeUser = user.getIdentifier();
12466                        appId = ps.appId;
12467                        scheduleWritePackageRestrictionsLocked(removeUser);
12468                    } else {
12469                        // We need to set it back to 'installed' so the uninstall
12470                        // broadcasts will be sent correctly.
12471                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12472                        ps.setInstalled(true, user.getIdentifier());
12473                    }
12474                } else {
12475                    // This is a system app, so we assume that the
12476                    // other users still have this package installed, so all
12477                    // we need to do is clear this user's data and save that
12478                    // it is uninstalled.
12479                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12480                    removeUser = user.getIdentifier();
12481                    appId = ps.appId;
12482                    scheduleWritePackageRestrictionsLocked(removeUser);
12483                }
12484            }
12485        }
12486
12487        if (removeUser >= 0) {
12488            // From above, we determined that we are deleting this only
12489            // for a single user.  Continue the work here.
12490            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12491            if (outInfo != null) {
12492                outInfo.removedPackage = packageName;
12493                outInfo.removedAppId = appId;
12494                outInfo.removedUsers = new int[] {removeUser};
12495            }
12496            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12497            removeKeystoreDataIfNeeded(removeUser, appId);
12498            schedulePackageCleaning(packageName, removeUser, false);
12499            synchronized (mPackages) {
12500                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12501                    scheduleWritePackageRestrictionsLocked(removeUser);
12502                }
12503            }
12504            return true;
12505        }
12506
12507        if (dataOnly) {
12508            // Delete application data first
12509            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12510            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12511            return true;
12512        }
12513
12514        boolean ret = false;
12515        if (isSystemApp(ps)) {
12516            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12517            // When an updated system application is deleted we delete the existing resources as well and
12518            // fall back to existing code in system partition
12519            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12520                    flags, outInfo, writeSettings);
12521        } else {
12522            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12523            // Kill application pre-emptively especially for apps on sd.
12524            killApplication(packageName, ps.appId, "uninstall pkg");
12525            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12526                    allUserHandles, perUserInstalled,
12527                    outInfo, writeSettings);
12528        }
12529
12530        return ret;
12531    }
12532
12533    private final class ClearStorageConnection implements ServiceConnection {
12534        IMediaContainerService mContainerService;
12535
12536        @Override
12537        public void onServiceConnected(ComponentName name, IBinder service) {
12538            synchronized (this) {
12539                mContainerService = IMediaContainerService.Stub.asInterface(service);
12540                notifyAll();
12541            }
12542        }
12543
12544        @Override
12545        public void onServiceDisconnected(ComponentName name) {
12546        }
12547    }
12548
12549    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12550        final boolean mounted;
12551        if (Environment.isExternalStorageEmulated()) {
12552            mounted = true;
12553        } else {
12554            final String status = Environment.getExternalStorageState();
12555
12556            mounted = status.equals(Environment.MEDIA_MOUNTED)
12557                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12558        }
12559
12560        if (!mounted) {
12561            return;
12562        }
12563
12564        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12565        int[] users;
12566        if (userId == UserHandle.USER_ALL) {
12567            users = sUserManager.getUserIds();
12568        } else {
12569            users = new int[] { userId };
12570        }
12571        final ClearStorageConnection conn = new ClearStorageConnection();
12572        if (mContext.bindServiceAsUser(
12573                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12574            try {
12575                for (int curUser : users) {
12576                    long timeout = SystemClock.uptimeMillis() + 5000;
12577                    synchronized (conn) {
12578                        long now = SystemClock.uptimeMillis();
12579                        while (conn.mContainerService == null && now < timeout) {
12580                            try {
12581                                conn.wait(timeout - now);
12582                            } catch (InterruptedException e) {
12583                            }
12584                        }
12585                    }
12586                    if (conn.mContainerService == null) {
12587                        return;
12588                    }
12589
12590                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12591                    clearDirectory(conn.mContainerService,
12592                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12593                    if (allData) {
12594                        clearDirectory(conn.mContainerService,
12595                                userEnv.buildExternalStorageAppDataDirs(packageName));
12596                        clearDirectory(conn.mContainerService,
12597                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12598                    }
12599                }
12600            } finally {
12601                mContext.unbindService(conn);
12602            }
12603        }
12604    }
12605
12606    @Override
12607    public void clearApplicationUserData(final String packageName,
12608            final IPackageDataObserver observer, final int userId) {
12609        mContext.enforceCallingOrSelfPermission(
12610                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12611        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12612        // Queue up an async operation since the package deletion may take a little while.
12613        mHandler.post(new Runnable() {
12614            public void run() {
12615                mHandler.removeCallbacks(this);
12616                final boolean succeeded;
12617                synchronized (mInstallLock) {
12618                    succeeded = clearApplicationUserDataLI(packageName, userId);
12619                }
12620                clearExternalStorageDataSync(packageName, userId, true);
12621                if (succeeded) {
12622                    // invoke DeviceStorageMonitor's update method to clear any notifications
12623                    DeviceStorageMonitorInternal
12624                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12625                    if (dsm != null) {
12626                        dsm.checkMemory();
12627                    }
12628                }
12629                if(observer != null) {
12630                    try {
12631                        observer.onRemoveCompleted(packageName, succeeded);
12632                    } catch (RemoteException e) {
12633                        Log.i(TAG, "Observer no longer exists.");
12634                    }
12635                } //end if observer
12636            } //end run
12637        });
12638    }
12639
12640    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12641        if (packageName == null) {
12642            Slog.w(TAG, "Attempt to delete null packageName.");
12643            return false;
12644        }
12645
12646        // Try finding details about the requested package
12647        PackageParser.Package pkg;
12648        synchronized (mPackages) {
12649            pkg = mPackages.get(packageName);
12650            if (pkg == null) {
12651                final PackageSetting ps = mSettings.mPackages.get(packageName);
12652                if (ps != null) {
12653                    pkg = ps.pkg;
12654                }
12655            }
12656
12657            if (pkg == null) {
12658                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12659                return false;
12660            }
12661
12662            PackageSetting ps = (PackageSetting) pkg.mExtras;
12663            PermissionsState permissionsState = ps.getPermissionsState();
12664            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
12665        }
12666
12667        // Always delete data directories for package, even if we found no other
12668        // record of app. This helps users recover from UID mismatches without
12669        // resorting to a full data wipe.
12670        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12671        if (retCode < 0) {
12672            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12673            return false;
12674        }
12675
12676        final int appId = pkg.applicationInfo.uid;
12677        removeKeystoreDataIfNeeded(userId, appId);
12678
12679        // Create a native library symlink only if we have native libraries
12680        // and if the native libraries are 32 bit libraries. We do not provide
12681        // this symlink for 64 bit libraries.
12682        if (pkg.applicationInfo.primaryCpuAbi != null &&
12683                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12684            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12685            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12686                    nativeLibPath, userId) < 0) {
12687                Slog.w(TAG, "Failed linking native library dir");
12688                return false;
12689            }
12690        }
12691
12692        return true;
12693    }
12694
12695
12696    /**
12697     * Revokes granted runtime permissions and clears resettable flags
12698     * which are flags that can be set by a user interaction.
12699     *
12700     * @param permissionsState The permission state to reset.
12701     * @param userId The device user for which to do a reset.
12702     */
12703    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
12704            PermissionsState permissionsState, int userId) {
12705        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
12706                | PackageManager.FLAG_PERMISSION_USER_FIXED
12707                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12708
12709        boolean needsWrite = false;
12710
12711        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
12712            BasePermission bp = mSettings.mPermissions.get(state.getName());
12713            if (bp != null) {
12714                permissionsState.revokeRuntimePermission(bp, userId);
12715                permissionsState.updatePermissionFlags(bp, userId, userSetFlags, 0);
12716                needsWrite = true;
12717            }
12718        }
12719
12720        if (needsWrite) {
12721            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
12722        }
12723    }
12724
12725    /**
12726     * Remove entries from the keystore daemon. Will only remove it if the
12727     * {@code appId} is valid.
12728     */
12729    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12730        if (appId < 0) {
12731            return;
12732        }
12733
12734        final KeyStore keyStore = KeyStore.getInstance();
12735        if (keyStore != null) {
12736            if (userId == UserHandle.USER_ALL) {
12737                for (final int individual : sUserManager.getUserIds()) {
12738                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12739                }
12740            } else {
12741                keyStore.clearUid(UserHandle.getUid(userId, appId));
12742            }
12743        } else {
12744            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12745        }
12746    }
12747
12748    @Override
12749    public void deleteApplicationCacheFiles(final String packageName,
12750            final IPackageDataObserver observer) {
12751        mContext.enforceCallingOrSelfPermission(
12752                android.Manifest.permission.DELETE_CACHE_FILES, null);
12753        // Queue up an async operation since the package deletion may take a little while.
12754        final int userId = UserHandle.getCallingUserId();
12755        mHandler.post(new Runnable() {
12756            public void run() {
12757                mHandler.removeCallbacks(this);
12758                final boolean succeded;
12759                synchronized (mInstallLock) {
12760                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12761                }
12762                clearExternalStorageDataSync(packageName, userId, false);
12763                if (observer != null) {
12764                    try {
12765                        observer.onRemoveCompleted(packageName, succeded);
12766                    } catch (RemoteException e) {
12767                        Log.i(TAG, "Observer no longer exists.");
12768                    }
12769                } //end if observer
12770            } //end run
12771        });
12772    }
12773
12774    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12775        if (packageName == null) {
12776            Slog.w(TAG, "Attempt to delete null packageName.");
12777            return false;
12778        }
12779        PackageParser.Package p;
12780        synchronized (mPackages) {
12781            p = mPackages.get(packageName);
12782        }
12783        if (p == null) {
12784            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12785            return false;
12786        }
12787        final ApplicationInfo applicationInfo = p.applicationInfo;
12788        if (applicationInfo == null) {
12789            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12790            return false;
12791        }
12792        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12793        if (retCode < 0) {
12794            Slog.w(TAG, "Couldn't remove cache files for package: "
12795                       + packageName + " u" + userId);
12796            return false;
12797        }
12798        return true;
12799    }
12800
12801    @Override
12802    public void getPackageSizeInfo(final String packageName, int userHandle,
12803            final IPackageStatsObserver observer) {
12804        mContext.enforceCallingOrSelfPermission(
12805                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12806        if (packageName == null) {
12807            throw new IllegalArgumentException("Attempt to get size of null packageName");
12808        }
12809
12810        PackageStats stats = new PackageStats(packageName, userHandle);
12811
12812        /*
12813         * Queue up an async operation since the package measurement may take a
12814         * little while.
12815         */
12816        Message msg = mHandler.obtainMessage(INIT_COPY);
12817        msg.obj = new MeasureParams(stats, observer);
12818        mHandler.sendMessage(msg);
12819    }
12820
12821    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12822            PackageStats pStats) {
12823        if (packageName == null) {
12824            Slog.w(TAG, "Attempt to get size of null packageName.");
12825            return false;
12826        }
12827        PackageParser.Package p;
12828        boolean dataOnly = false;
12829        String libDirRoot = null;
12830        String asecPath = null;
12831        PackageSetting ps = null;
12832        synchronized (mPackages) {
12833            p = mPackages.get(packageName);
12834            ps = mSettings.mPackages.get(packageName);
12835            if(p == null) {
12836                dataOnly = true;
12837                if((ps == null) || (ps.pkg == null)) {
12838                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12839                    return false;
12840                }
12841                p = ps.pkg;
12842            }
12843            if (ps != null) {
12844                libDirRoot = ps.legacyNativeLibraryPathString;
12845            }
12846            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12847                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12848                if (secureContainerId != null) {
12849                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12850                }
12851            }
12852        }
12853        String publicSrcDir = null;
12854        if(!dataOnly) {
12855            final ApplicationInfo applicationInfo = p.applicationInfo;
12856            if (applicationInfo == null) {
12857                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12858                return false;
12859            }
12860            if (p.isForwardLocked()) {
12861                publicSrcDir = applicationInfo.getBaseResourcePath();
12862            }
12863        }
12864        // TODO: extend to measure size of split APKs
12865        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12866        // not just the first level.
12867        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12868        // just the primary.
12869        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12870        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
12871                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12872        if (res < 0) {
12873            return false;
12874        }
12875
12876        // Fix-up for forward-locked applications in ASEC containers.
12877        if (!isExternal(p)) {
12878            pStats.codeSize += pStats.externalCodeSize;
12879            pStats.externalCodeSize = 0L;
12880        }
12881
12882        return true;
12883    }
12884
12885
12886    @Override
12887    public void addPackageToPreferred(String packageName) {
12888        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12889    }
12890
12891    @Override
12892    public void removePackageFromPreferred(String packageName) {
12893        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12894    }
12895
12896    @Override
12897    public List<PackageInfo> getPreferredPackages(int flags) {
12898        return new ArrayList<PackageInfo>();
12899    }
12900
12901    private int getUidTargetSdkVersionLockedLPr(int uid) {
12902        Object obj = mSettings.getUserIdLPr(uid);
12903        if (obj instanceof SharedUserSetting) {
12904            final SharedUserSetting sus = (SharedUserSetting) obj;
12905            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12906            final Iterator<PackageSetting> it = sus.packages.iterator();
12907            while (it.hasNext()) {
12908                final PackageSetting ps = it.next();
12909                if (ps.pkg != null) {
12910                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12911                    if (v < vers) vers = v;
12912                }
12913            }
12914            return vers;
12915        } else if (obj instanceof PackageSetting) {
12916            final PackageSetting ps = (PackageSetting) obj;
12917            if (ps.pkg != null) {
12918                return ps.pkg.applicationInfo.targetSdkVersion;
12919            }
12920        }
12921        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12922    }
12923
12924    @Override
12925    public void addPreferredActivity(IntentFilter filter, int match,
12926            ComponentName[] set, ComponentName activity, int userId) {
12927        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12928                "Adding preferred");
12929    }
12930
12931    private void addPreferredActivityInternal(IntentFilter filter, int match,
12932            ComponentName[] set, ComponentName activity, boolean always, int userId,
12933            String opname) {
12934        // writer
12935        int callingUid = Binder.getCallingUid();
12936        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12937        if (filter.countActions() == 0) {
12938            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12939            return;
12940        }
12941        synchronized (mPackages) {
12942            if (mContext.checkCallingOrSelfPermission(
12943                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12944                    != PackageManager.PERMISSION_GRANTED) {
12945                if (getUidTargetSdkVersionLockedLPr(callingUid)
12946                        < Build.VERSION_CODES.FROYO) {
12947                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12948                            + callingUid);
12949                    return;
12950                }
12951                mContext.enforceCallingOrSelfPermission(
12952                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12953            }
12954
12955            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12956            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12957                    + userId + ":");
12958            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12959            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12960            scheduleWritePackageRestrictionsLocked(userId);
12961        }
12962    }
12963
12964    @Override
12965    public void replacePreferredActivity(IntentFilter filter, int match,
12966            ComponentName[] set, ComponentName activity, int userId) {
12967        if (filter.countActions() != 1) {
12968            throw new IllegalArgumentException(
12969                    "replacePreferredActivity expects filter to have only 1 action.");
12970        }
12971        if (filter.countDataAuthorities() != 0
12972                || filter.countDataPaths() != 0
12973                || filter.countDataSchemes() > 1
12974                || filter.countDataTypes() != 0) {
12975            throw new IllegalArgumentException(
12976                    "replacePreferredActivity expects filter to have no data authorities, " +
12977                    "paths, or types; and at most one scheme.");
12978        }
12979
12980        final int callingUid = Binder.getCallingUid();
12981        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12982        synchronized (mPackages) {
12983            if (mContext.checkCallingOrSelfPermission(
12984                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12985                    != PackageManager.PERMISSION_GRANTED) {
12986                if (getUidTargetSdkVersionLockedLPr(callingUid)
12987                        < Build.VERSION_CODES.FROYO) {
12988                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12989                            + Binder.getCallingUid());
12990                    return;
12991                }
12992                mContext.enforceCallingOrSelfPermission(
12993                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12994            }
12995
12996            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12997            if (pir != null) {
12998                // Get all of the existing entries that exactly match this filter.
12999                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13000                if (existing != null && existing.size() == 1) {
13001                    PreferredActivity cur = existing.get(0);
13002                    if (DEBUG_PREFERRED) {
13003                        Slog.i(TAG, "Checking replace of preferred:");
13004                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13005                        if (!cur.mPref.mAlways) {
13006                            Slog.i(TAG, "  -- CUR; not mAlways!");
13007                        } else {
13008                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13009                            Slog.i(TAG, "  -- CUR: mSet="
13010                                    + Arrays.toString(cur.mPref.mSetComponents));
13011                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13012                            Slog.i(TAG, "  -- NEW: mMatch="
13013                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13014                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13015                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13016                        }
13017                    }
13018                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13019                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13020                            && cur.mPref.sameSet(set)) {
13021                        // Setting the preferred activity to what it happens to be already
13022                        if (DEBUG_PREFERRED) {
13023                            Slog.i(TAG, "Replacing with same preferred activity "
13024                                    + cur.mPref.mShortComponent + " for user "
13025                                    + userId + ":");
13026                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13027                        }
13028                        return;
13029                    }
13030                }
13031
13032                if (existing != null) {
13033                    if (DEBUG_PREFERRED) {
13034                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13035                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13036                    }
13037                    for (int i = 0; i < existing.size(); i++) {
13038                        PreferredActivity pa = existing.get(i);
13039                        if (DEBUG_PREFERRED) {
13040                            Slog.i(TAG, "Removing existing preferred activity "
13041                                    + pa.mPref.mComponent + ":");
13042                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13043                        }
13044                        pir.removeFilter(pa);
13045                    }
13046                }
13047            }
13048            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13049                    "Replacing preferred");
13050        }
13051    }
13052
13053    @Override
13054    public void clearPackagePreferredActivities(String packageName) {
13055        final int uid = Binder.getCallingUid();
13056        // writer
13057        synchronized (mPackages) {
13058            PackageParser.Package pkg = mPackages.get(packageName);
13059            if (pkg == null || pkg.applicationInfo.uid != uid) {
13060                if (mContext.checkCallingOrSelfPermission(
13061                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13062                        != PackageManager.PERMISSION_GRANTED) {
13063                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13064                            < Build.VERSION_CODES.FROYO) {
13065                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13066                                + Binder.getCallingUid());
13067                        return;
13068                    }
13069                    mContext.enforceCallingOrSelfPermission(
13070                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13071                }
13072            }
13073
13074            int user = UserHandle.getCallingUserId();
13075            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13076                scheduleWritePackageRestrictionsLocked(user);
13077            }
13078        }
13079    }
13080
13081    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13082    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13083        ArrayList<PreferredActivity> removed = null;
13084        boolean changed = false;
13085        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13086            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13087            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13088            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13089                continue;
13090            }
13091            Iterator<PreferredActivity> it = pir.filterIterator();
13092            while (it.hasNext()) {
13093                PreferredActivity pa = it.next();
13094                // Mark entry for removal only if it matches the package name
13095                // and the entry is of type "always".
13096                if (packageName == null ||
13097                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13098                                && pa.mPref.mAlways)) {
13099                    if (removed == null) {
13100                        removed = new ArrayList<PreferredActivity>();
13101                    }
13102                    removed.add(pa);
13103                }
13104            }
13105            if (removed != null) {
13106                for (int j=0; j<removed.size(); j++) {
13107                    PreferredActivity pa = removed.get(j);
13108                    pir.removeFilter(pa);
13109                }
13110                changed = true;
13111            }
13112        }
13113        return changed;
13114    }
13115
13116    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13117    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13118        if (userId == UserHandle.USER_ALL) {
13119            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13120                    sUserManager.getUserIds())) {
13121                for (int oneUserId : sUserManager.getUserIds()) {
13122                    scheduleWritePackageRestrictionsLocked(oneUserId);
13123                }
13124            }
13125        } else {
13126            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13127                scheduleWritePackageRestrictionsLocked(userId);
13128            }
13129        }
13130    }
13131
13132
13133    void clearDefaultBrowserIfNeeded(String packageName) {
13134        for (int oneUserId : sUserManager.getUserIds()) {
13135            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13136            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13137            if (packageName.equals(defaultBrowserPackageName)) {
13138                setDefaultBrowserPackageName(null, oneUserId);
13139            }
13140        }
13141    }
13142
13143    @Override
13144    public void resetPreferredActivities(int userId) {
13145        /* TODO: Actually use userId. Why is it being passed in? */
13146        mContext.enforceCallingOrSelfPermission(
13147                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13148        // writer
13149        synchronized (mPackages) {
13150            int user = UserHandle.getCallingUserId();
13151            clearPackagePreferredActivitiesLPw(null, user);
13152            mSettings.readDefaultPreferredAppsLPw(this, user);
13153            scheduleWritePackageRestrictionsLocked(user);
13154        }
13155    }
13156
13157    @Override
13158    public int getPreferredActivities(List<IntentFilter> outFilters,
13159            List<ComponentName> outActivities, String packageName) {
13160
13161        int num = 0;
13162        final int userId = UserHandle.getCallingUserId();
13163        // reader
13164        synchronized (mPackages) {
13165            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13166            if (pir != null) {
13167                final Iterator<PreferredActivity> it = pir.filterIterator();
13168                while (it.hasNext()) {
13169                    final PreferredActivity pa = it.next();
13170                    if (packageName == null
13171                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13172                                    && pa.mPref.mAlways)) {
13173                        if (outFilters != null) {
13174                            outFilters.add(new IntentFilter(pa));
13175                        }
13176                        if (outActivities != null) {
13177                            outActivities.add(pa.mPref.mComponent);
13178                        }
13179                    }
13180                }
13181            }
13182        }
13183
13184        return num;
13185    }
13186
13187    @Override
13188    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13189            int userId) {
13190        int callingUid = Binder.getCallingUid();
13191        if (callingUid != Process.SYSTEM_UID) {
13192            throw new SecurityException(
13193                    "addPersistentPreferredActivity can only be run by the system");
13194        }
13195        if (filter.countActions() == 0) {
13196            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13197            return;
13198        }
13199        synchronized (mPackages) {
13200            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13201                    " :");
13202            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13203            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13204                    new PersistentPreferredActivity(filter, activity));
13205            scheduleWritePackageRestrictionsLocked(userId);
13206        }
13207    }
13208
13209    @Override
13210    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13211        int callingUid = Binder.getCallingUid();
13212        if (callingUid != Process.SYSTEM_UID) {
13213            throw new SecurityException(
13214                    "clearPackagePersistentPreferredActivities can only be run by the system");
13215        }
13216        ArrayList<PersistentPreferredActivity> removed = null;
13217        boolean changed = false;
13218        synchronized (mPackages) {
13219            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13220                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13221                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13222                        .valueAt(i);
13223                if (userId != thisUserId) {
13224                    continue;
13225                }
13226                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13227                while (it.hasNext()) {
13228                    PersistentPreferredActivity ppa = it.next();
13229                    // Mark entry for removal only if it matches the package name.
13230                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13231                        if (removed == null) {
13232                            removed = new ArrayList<PersistentPreferredActivity>();
13233                        }
13234                        removed.add(ppa);
13235                    }
13236                }
13237                if (removed != null) {
13238                    for (int j=0; j<removed.size(); j++) {
13239                        PersistentPreferredActivity ppa = removed.get(j);
13240                        ppir.removeFilter(ppa);
13241                    }
13242                    changed = true;
13243                }
13244            }
13245
13246            if (changed) {
13247                scheduleWritePackageRestrictionsLocked(userId);
13248            }
13249        }
13250    }
13251
13252    /**
13253     * Non-Binder method, support for the backup/restore mechanism: write the
13254     * full set of preferred activities in its canonical XML format.  Returns true
13255     * on success; false otherwise.
13256     */
13257    @Override
13258    public byte[] getPreferredActivityBackup(int userId) {
13259        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13260            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13261        }
13262
13263        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13264        try {
13265            final XmlSerializer serializer = new FastXmlSerializer();
13266            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13267            serializer.startDocument(null, true);
13268            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13269
13270            synchronized (mPackages) {
13271                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13272            }
13273
13274            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13275            serializer.endDocument();
13276            serializer.flush();
13277        } catch (Exception e) {
13278            if (DEBUG_BACKUP) {
13279                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13280            }
13281            return null;
13282        }
13283
13284        return dataStream.toByteArray();
13285    }
13286
13287    @Override
13288    public void restorePreferredActivities(byte[] backup, int userId) {
13289        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13290            throw new SecurityException("Only the system may call restorePreferredActivities()");
13291        }
13292
13293        try {
13294            final XmlPullParser parser = Xml.newPullParser();
13295            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13296
13297            int type;
13298            while ((type = parser.next()) != XmlPullParser.START_TAG
13299                    && type != XmlPullParser.END_DOCUMENT) {
13300            }
13301            if (type != XmlPullParser.START_TAG) {
13302                // oops didn't find a start tag?!
13303                if (DEBUG_BACKUP) {
13304                    Slog.e(TAG, "Didn't find start tag during restore");
13305                }
13306                return;
13307            }
13308
13309            // this is supposed to be TAG_PREFERRED_BACKUP
13310            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
13311                if (DEBUG_BACKUP) {
13312                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
13313                }
13314                return;
13315            }
13316
13317            // skip interfering stuff, then we're aligned with the backing implementation
13318            while ((type = parser.next()) == XmlPullParser.TEXT) { }
13319            synchronized (mPackages) {
13320                mSettings.readPreferredActivitiesLPw(parser, userId);
13321            }
13322        } catch (Exception e) {
13323            if (DEBUG_BACKUP) {
13324                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13325            }
13326        }
13327    }
13328
13329    @Override
13330    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13331            int sourceUserId, int targetUserId, int flags) {
13332        mContext.enforceCallingOrSelfPermission(
13333                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13334        int callingUid = Binder.getCallingUid();
13335        enforceOwnerRights(ownerPackage, callingUid);
13336        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13337        if (intentFilter.countActions() == 0) {
13338            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13339            return;
13340        }
13341        synchronized (mPackages) {
13342            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13343                    ownerPackage, targetUserId, flags);
13344            CrossProfileIntentResolver resolver =
13345                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13346            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13347            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13348            if (existing != null) {
13349                int size = existing.size();
13350                for (int i = 0; i < size; i++) {
13351                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13352                        return;
13353                    }
13354                }
13355            }
13356            resolver.addFilter(newFilter);
13357            scheduleWritePackageRestrictionsLocked(sourceUserId);
13358        }
13359    }
13360
13361    @Override
13362    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13363        mContext.enforceCallingOrSelfPermission(
13364                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13365        int callingUid = Binder.getCallingUid();
13366        enforceOwnerRights(ownerPackage, callingUid);
13367        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13368        synchronized (mPackages) {
13369            CrossProfileIntentResolver resolver =
13370                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13371            ArraySet<CrossProfileIntentFilter> set =
13372                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13373            for (CrossProfileIntentFilter filter : set) {
13374                if (filter.getOwnerPackage().equals(ownerPackage)) {
13375                    resolver.removeFilter(filter);
13376                }
13377            }
13378            scheduleWritePackageRestrictionsLocked(sourceUserId);
13379        }
13380    }
13381
13382    // Enforcing that callingUid is owning pkg on userId
13383    private void enforceOwnerRights(String pkg, int callingUid) {
13384        // The system owns everything.
13385        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13386            return;
13387        }
13388        int callingUserId = UserHandle.getUserId(callingUid);
13389        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13390        if (pi == null) {
13391            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13392                    + callingUserId);
13393        }
13394        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13395            throw new SecurityException("Calling uid " + callingUid
13396                    + " does not own package " + pkg);
13397        }
13398    }
13399
13400    @Override
13401    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13402        Intent intent = new Intent(Intent.ACTION_MAIN);
13403        intent.addCategory(Intent.CATEGORY_HOME);
13404
13405        final int callingUserId = UserHandle.getCallingUserId();
13406        List<ResolveInfo> list = queryIntentActivities(intent, null,
13407                PackageManager.GET_META_DATA, callingUserId);
13408        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13409                true, false, false, callingUserId);
13410
13411        allHomeCandidates.clear();
13412        if (list != null) {
13413            for (ResolveInfo ri : list) {
13414                allHomeCandidates.add(ri);
13415            }
13416        }
13417        return (preferred == null || preferred.activityInfo == null)
13418                ? null
13419                : new ComponentName(preferred.activityInfo.packageName,
13420                        preferred.activityInfo.name);
13421    }
13422
13423    @Override
13424    public void setApplicationEnabledSetting(String appPackageName,
13425            int newState, int flags, int userId, String callingPackage) {
13426        if (!sUserManager.exists(userId)) return;
13427        if (callingPackage == null) {
13428            callingPackage = Integer.toString(Binder.getCallingUid());
13429        }
13430        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13431    }
13432
13433    @Override
13434    public void setComponentEnabledSetting(ComponentName componentName,
13435            int newState, int flags, int userId) {
13436        if (!sUserManager.exists(userId)) return;
13437        setEnabledSetting(componentName.getPackageName(),
13438                componentName.getClassName(), newState, flags, userId, null);
13439    }
13440
13441    private void setEnabledSetting(final String packageName, String className, int newState,
13442            final int flags, int userId, String callingPackage) {
13443        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13444              || newState == COMPONENT_ENABLED_STATE_ENABLED
13445              || newState == COMPONENT_ENABLED_STATE_DISABLED
13446              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13447              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13448            throw new IllegalArgumentException("Invalid new component state: "
13449                    + newState);
13450        }
13451        PackageSetting pkgSetting;
13452        final int uid = Binder.getCallingUid();
13453        final int permission = mContext.checkCallingOrSelfPermission(
13454                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13455        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13456        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13457        boolean sendNow = false;
13458        boolean isApp = (className == null);
13459        String componentName = isApp ? packageName : className;
13460        int packageUid = -1;
13461        ArrayList<String> components;
13462
13463        // writer
13464        synchronized (mPackages) {
13465            pkgSetting = mSettings.mPackages.get(packageName);
13466            if (pkgSetting == null) {
13467                if (className == null) {
13468                    throw new IllegalArgumentException(
13469                            "Unknown package: " + packageName);
13470                }
13471                throw new IllegalArgumentException(
13472                        "Unknown component: " + packageName
13473                        + "/" + className);
13474            }
13475            // Allow root and verify that userId is not being specified by a different user
13476            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13477                throw new SecurityException(
13478                        "Permission Denial: attempt to change component state from pid="
13479                        + Binder.getCallingPid()
13480                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13481            }
13482            if (className == null) {
13483                // We're dealing with an application/package level state change
13484                if (pkgSetting.getEnabled(userId) == newState) {
13485                    // Nothing to do
13486                    return;
13487                }
13488                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13489                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13490                    // Don't care about who enables an app.
13491                    callingPackage = null;
13492                }
13493                pkgSetting.setEnabled(newState, userId, callingPackage);
13494                // pkgSetting.pkg.mSetEnabled = newState;
13495            } else {
13496                // We're dealing with a component level state change
13497                // First, verify that this is a valid class name.
13498                PackageParser.Package pkg = pkgSetting.pkg;
13499                if (pkg == null || !pkg.hasComponentClassName(className)) {
13500                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13501                        throw new IllegalArgumentException("Component class " + className
13502                                + " does not exist in " + packageName);
13503                    } else {
13504                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13505                                + className + " does not exist in " + packageName);
13506                    }
13507                }
13508                switch (newState) {
13509                case COMPONENT_ENABLED_STATE_ENABLED:
13510                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13511                        return;
13512                    }
13513                    break;
13514                case COMPONENT_ENABLED_STATE_DISABLED:
13515                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13516                        return;
13517                    }
13518                    break;
13519                case COMPONENT_ENABLED_STATE_DEFAULT:
13520                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13521                        return;
13522                    }
13523                    break;
13524                default:
13525                    Slog.e(TAG, "Invalid new component state: " + newState);
13526                    return;
13527                }
13528            }
13529            scheduleWritePackageRestrictionsLocked(userId);
13530            components = mPendingBroadcasts.get(userId, packageName);
13531            final boolean newPackage = components == null;
13532            if (newPackage) {
13533                components = new ArrayList<String>();
13534            }
13535            if (!components.contains(componentName)) {
13536                components.add(componentName);
13537            }
13538            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13539                sendNow = true;
13540                // Purge entry from pending broadcast list if another one exists already
13541                // since we are sending one right away.
13542                mPendingBroadcasts.remove(userId, packageName);
13543            } else {
13544                if (newPackage) {
13545                    mPendingBroadcasts.put(userId, packageName, components);
13546                }
13547                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13548                    // Schedule a message
13549                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13550                }
13551            }
13552        }
13553
13554        long callingId = Binder.clearCallingIdentity();
13555        try {
13556            if (sendNow) {
13557                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13558                sendPackageChangedBroadcast(packageName,
13559                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13560            }
13561        } finally {
13562            Binder.restoreCallingIdentity(callingId);
13563        }
13564    }
13565
13566    private void sendPackageChangedBroadcast(String packageName,
13567            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13568        if (DEBUG_INSTALL)
13569            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13570                    + componentNames);
13571        Bundle extras = new Bundle(4);
13572        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13573        String nameList[] = new String[componentNames.size()];
13574        componentNames.toArray(nameList);
13575        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13576        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13577        extras.putInt(Intent.EXTRA_UID, packageUid);
13578        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13579                new int[] {UserHandle.getUserId(packageUid)});
13580    }
13581
13582    @Override
13583    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13584        if (!sUserManager.exists(userId)) return;
13585        final int uid = Binder.getCallingUid();
13586        final int permission = mContext.checkCallingOrSelfPermission(
13587                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13588        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13589        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13590        // writer
13591        synchronized (mPackages) {
13592            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13593                    allowedByPermission, uid, userId)) {
13594                scheduleWritePackageRestrictionsLocked(userId);
13595            }
13596        }
13597    }
13598
13599    @Override
13600    public String getInstallerPackageName(String packageName) {
13601        // reader
13602        synchronized (mPackages) {
13603            return mSettings.getInstallerPackageNameLPr(packageName);
13604        }
13605    }
13606
13607    @Override
13608    public int getApplicationEnabledSetting(String packageName, int userId) {
13609        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13610        int uid = Binder.getCallingUid();
13611        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13612        // reader
13613        synchronized (mPackages) {
13614            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13615        }
13616    }
13617
13618    @Override
13619    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13620        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13621        int uid = Binder.getCallingUid();
13622        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13623        // reader
13624        synchronized (mPackages) {
13625            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13626        }
13627    }
13628
13629    @Override
13630    public void enterSafeMode() {
13631        enforceSystemOrRoot("Only the system can request entering safe mode");
13632
13633        if (!mSystemReady) {
13634            mSafeMode = true;
13635        }
13636    }
13637
13638    @Override
13639    public void systemReady() {
13640        mSystemReady = true;
13641
13642        // Read the compatibilty setting when the system is ready.
13643        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13644                mContext.getContentResolver(),
13645                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13646        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13647        if (DEBUG_SETTINGS) {
13648            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13649        }
13650
13651        synchronized (mPackages) {
13652            // Verify that all of the preferred activity components actually
13653            // exist.  It is possible for applications to be updated and at
13654            // that point remove a previously declared activity component that
13655            // had been set as a preferred activity.  We try to clean this up
13656            // the next time we encounter that preferred activity, but it is
13657            // possible for the user flow to never be able to return to that
13658            // situation so here we do a sanity check to make sure we haven't
13659            // left any junk around.
13660            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13661            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13662                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13663                removed.clear();
13664                for (PreferredActivity pa : pir.filterSet()) {
13665                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13666                        removed.add(pa);
13667                    }
13668                }
13669                if (removed.size() > 0) {
13670                    for (int r=0; r<removed.size(); r++) {
13671                        PreferredActivity pa = removed.get(r);
13672                        Slog.w(TAG, "Removing dangling preferred activity: "
13673                                + pa.mPref.mComponent);
13674                        pir.removeFilter(pa);
13675                    }
13676                    mSettings.writePackageRestrictionsLPr(
13677                            mSettings.mPreferredActivities.keyAt(i));
13678                }
13679            }
13680        }
13681        sUserManager.systemReady();
13682
13683        // Kick off any messages waiting for system ready
13684        if (mPostSystemReadyMessages != null) {
13685            for (Message msg : mPostSystemReadyMessages) {
13686                msg.sendToTarget();
13687            }
13688            mPostSystemReadyMessages = null;
13689        }
13690
13691        // Watch for external volumes that come and go over time
13692        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13693        storage.registerListener(mStorageListener);
13694
13695        mInstallerService.systemReady();
13696        mPackageDexOptimizer.systemReady();
13697    }
13698
13699    @Override
13700    public boolean isSafeMode() {
13701        return mSafeMode;
13702    }
13703
13704    @Override
13705    public boolean hasSystemUidErrors() {
13706        return mHasSystemUidErrors;
13707    }
13708
13709    static String arrayToString(int[] array) {
13710        StringBuffer buf = new StringBuffer(128);
13711        buf.append('[');
13712        if (array != null) {
13713            for (int i=0; i<array.length; i++) {
13714                if (i > 0) buf.append(", ");
13715                buf.append(array[i]);
13716            }
13717        }
13718        buf.append(']');
13719        return buf.toString();
13720    }
13721
13722    static class DumpState {
13723        public static final int DUMP_LIBS = 1 << 0;
13724        public static final int DUMP_FEATURES = 1 << 1;
13725        public static final int DUMP_RESOLVERS = 1 << 2;
13726        public static final int DUMP_PERMISSIONS = 1 << 3;
13727        public static final int DUMP_PACKAGES = 1 << 4;
13728        public static final int DUMP_SHARED_USERS = 1 << 5;
13729        public static final int DUMP_MESSAGES = 1 << 6;
13730        public static final int DUMP_PROVIDERS = 1 << 7;
13731        public static final int DUMP_VERIFIERS = 1 << 8;
13732        public static final int DUMP_PREFERRED = 1 << 9;
13733        public static final int DUMP_PREFERRED_XML = 1 << 10;
13734        public static final int DUMP_KEYSETS = 1 << 11;
13735        public static final int DUMP_VERSION = 1 << 12;
13736        public static final int DUMP_INSTALLS = 1 << 13;
13737        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13738        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13739
13740        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13741
13742        private int mTypes;
13743
13744        private int mOptions;
13745
13746        private boolean mTitlePrinted;
13747
13748        private SharedUserSetting mSharedUser;
13749
13750        public boolean isDumping(int type) {
13751            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13752                return true;
13753            }
13754
13755            return (mTypes & type) != 0;
13756        }
13757
13758        public void setDump(int type) {
13759            mTypes |= type;
13760        }
13761
13762        public boolean isOptionEnabled(int option) {
13763            return (mOptions & option) != 0;
13764        }
13765
13766        public void setOptionEnabled(int option) {
13767            mOptions |= option;
13768        }
13769
13770        public boolean onTitlePrinted() {
13771            final boolean printed = mTitlePrinted;
13772            mTitlePrinted = true;
13773            return printed;
13774        }
13775
13776        public boolean getTitlePrinted() {
13777            return mTitlePrinted;
13778        }
13779
13780        public void setTitlePrinted(boolean enabled) {
13781            mTitlePrinted = enabled;
13782        }
13783
13784        public SharedUserSetting getSharedUser() {
13785            return mSharedUser;
13786        }
13787
13788        public void setSharedUser(SharedUserSetting user) {
13789            mSharedUser = user;
13790        }
13791    }
13792
13793    @Override
13794    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13795        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13796                != PackageManager.PERMISSION_GRANTED) {
13797            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13798                    + Binder.getCallingPid()
13799                    + ", uid=" + Binder.getCallingUid()
13800                    + " without permission "
13801                    + android.Manifest.permission.DUMP);
13802            return;
13803        }
13804
13805        DumpState dumpState = new DumpState();
13806        boolean fullPreferred = false;
13807        boolean checkin = false;
13808
13809        String packageName = null;
13810
13811        int opti = 0;
13812        while (opti < args.length) {
13813            String opt = args[opti];
13814            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13815                break;
13816            }
13817            opti++;
13818
13819            if ("-a".equals(opt)) {
13820                // Right now we only know how to print all.
13821            } else if ("-h".equals(opt)) {
13822                pw.println("Package manager dump options:");
13823                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13824                pw.println("    --checkin: dump for a checkin");
13825                pw.println("    -f: print details of intent filters");
13826                pw.println("    -h: print this help");
13827                pw.println("  cmd may be one of:");
13828                pw.println("    l[ibraries]: list known shared libraries");
13829                pw.println("    f[ibraries]: list device features");
13830                pw.println("    k[eysets]: print known keysets");
13831                pw.println("    r[esolvers]: dump intent resolvers");
13832                pw.println("    perm[issions]: dump permissions");
13833                pw.println("    pref[erred]: print preferred package settings");
13834                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13835                pw.println("    prov[iders]: dump content providers");
13836                pw.println("    p[ackages]: dump installed packages");
13837                pw.println("    s[hared-users]: dump shared user IDs");
13838                pw.println("    m[essages]: print collected runtime messages");
13839                pw.println("    v[erifiers]: print package verifier info");
13840                pw.println("    version: print database version info");
13841                pw.println("    write: write current settings now");
13842                pw.println("    <package.name>: info about given package");
13843                pw.println("    installs: details about install sessions");
13844                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13845                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13846                return;
13847            } else if ("--checkin".equals(opt)) {
13848                checkin = true;
13849            } else if ("-f".equals(opt)) {
13850                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13851            } else {
13852                pw.println("Unknown argument: " + opt + "; use -h for help");
13853            }
13854        }
13855
13856        // Is the caller requesting to dump a particular piece of data?
13857        if (opti < args.length) {
13858            String cmd = args[opti];
13859            opti++;
13860            // Is this a package name?
13861            if ("android".equals(cmd) || cmd.contains(".")) {
13862                packageName = cmd;
13863                // When dumping a single package, we always dump all of its
13864                // filter information since the amount of data will be reasonable.
13865                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13866            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13867                dumpState.setDump(DumpState.DUMP_LIBS);
13868            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13869                dumpState.setDump(DumpState.DUMP_FEATURES);
13870            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13871                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13872            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13873                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13874            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13875                dumpState.setDump(DumpState.DUMP_PREFERRED);
13876            } else if ("preferred-xml".equals(cmd)) {
13877                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13878                if (opti < args.length && "--full".equals(args[opti])) {
13879                    fullPreferred = true;
13880                    opti++;
13881                }
13882            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13883                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13884            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13885                dumpState.setDump(DumpState.DUMP_PACKAGES);
13886            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13887                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13888            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13889                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13890            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13891                dumpState.setDump(DumpState.DUMP_MESSAGES);
13892            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13893                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13894            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13895                    || "intent-filter-verifiers".equals(cmd)) {
13896                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13897            } else if ("version".equals(cmd)) {
13898                dumpState.setDump(DumpState.DUMP_VERSION);
13899            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13900                dumpState.setDump(DumpState.DUMP_KEYSETS);
13901            } else if ("installs".equals(cmd)) {
13902                dumpState.setDump(DumpState.DUMP_INSTALLS);
13903            } else if ("write".equals(cmd)) {
13904                synchronized (mPackages) {
13905                    mSettings.writeLPr();
13906                    pw.println("Settings written.");
13907                    return;
13908                }
13909            }
13910        }
13911
13912        if (checkin) {
13913            pw.println("vers,1");
13914        }
13915
13916        // reader
13917        synchronized (mPackages) {
13918            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13919                if (!checkin) {
13920                    if (dumpState.onTitlePrinted())
13921                        pw.println();
13922                    pw.println("Database versions:");
13923                    pw.print("  SDK Version:");
13924                    pw.print(" internal=");
13925                    pw.print(mSettings.mInternalSdkPlatform);
13926                    pw.print(" external=");
13927                    pw.println(mSettings.mExternalSdkPlatform);
13928                    pw.print("  DB Version:");
13929                    pw.print(" internal=");
13930                    pw.print(mSettings.mInternalDatabaseVersion);
13931                    pw.print(" external=");
13932                    pw.println(mSettings.mExternalDatabaseVersion);
13933                }
13934            }
13935
13936            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13937                if (!checkin) {
13938                    if (dumpState.onTitlePrinted())
13939                        pw.println();
13940                    pw.println("Verifiers:");
13941                    pw.print("  Required: ");
13942                    pw.print(mRequiredVerifierPackage);
13943                    pw.print(" (uid=");
13944                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13945                    pw.println(")");
13946                } else if (mRequiredVerifierPackage != null) {
13947                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13948                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13949                }
13950            }
13951
13952            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13953                    packageName == null) {
13954                if (mIntentFilterVerifierComponent != null) {
13955                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13956                    if (!checkin) {
13957                        if (dumpState.onTitlePrinted())
13958                            pw.println();
13959                        pw.println("Intent Filter Verifier:");
13960                        pw.print("  Using: ");
13961                        pw.print(verifierPackageName);
13962                        pw.print(" (uid=");
13963                        pw.print(getPackageUid(verifierPackageName, 0));
13964                        pw.println(")");
13965                    } else if (verifierPackageName != null) {
13966                        pw.print("ifv,"); pw.print(verifierPackageName);
13967                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13968                    }
13969                } else {
13970                    pw.println();
13971                    pw.println("No Intent Filter Verifier available!");
13972                }
13973            }
13974
13975            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13976                boolean printedHeader = false;
13977                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13978                while (it.hasNext()) {
13979                    String name = it.next();
13980                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13981                    if (!checkin) {
13982                        if (!printedHeader) {
13983                            if (dumpState.onTitlePrinted())
13984                                pw.println();
13985                            pw.println("Libraries:");
13986                            printedHeader = true;
13987                        }
13988                        pw.print("  ");
13989                    } else {
13990                        pw.print("lib,");
13991                    }
13992                    pw.print(name);
13993                    if (!checkin) {
13994                        pw.print(" -> ");
13995                    }
13996                    if (ent.path != null) {
13997                        if (!checkin) {
13998                            pw.print("(jar) ");
13999                            pw.print(ent.path);
14000                        } else {
14001                            pw.print(",jar,");
14002                            pw.print(ent.path);
14003                        }
14004                    } else {
14005                        if (!checkin) {
14006                            pw.print("(apk) ");
14007                            pw.print(ent.apk);
14008                        } else {
14009                            pw.print(",apk,");
14010                            pw.print(ent.apk);
14011                        }
14012                    }
14013                    pw.println();
14014                }
14015            }
14016
14017            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14018                if (dumpState.onTitlePrinted())
14019                    pw.println();
14020                if (!checkin) {
14021                    pw.println("Features:");
14022                }
14023                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14024                while (it.hasNext()) {
14025                    String name = it.next();
14026                    if (!checkin) {
14027                        pw.print("  ");
14028                    } else {
14029                        pw.print("feat,");
14030                    }
14031                    pw.println(name);
14032                }
14033            }
14034
14035            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14036                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14037                        : "Activity Resolver Table:", "  ", packageName,
14038                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14039                    dumpState.setTitlePrinted(true);
14040                }
14041                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14042                        : "Receiver Resolver Table:", "  ", packageName,
14043                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14044                    dumpState.setTitlePrinted(true);
14045                }
14046                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14047                        : "Service Resolver Table:", "  ", packageName,
14048                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14049                    dumpState.setTitlePrinted(true);
14050                }
14051                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14052                        : "Provider Resolver Table:", "  ", packageName,
14053                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14054                    dumpState.setTitlePrinted(true);
14055                }
14056            }
14057
14058            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14059                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14060                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14061                    int user = mSettings.mPreferredActivities.keyAt(i);
14062                    if (pir.dump(pw,
14063                            dumpState.getTitlePrinted()
14064                                ? "\nPreferred Activities User " + user + ":"
14065                                : "Preferred Activities User " + user + ":", "  ",
14066                            packageName, true, false)) {
14067                        dumpState.setTitlePrinted(true);
14068                    }
14069                }
14070            }
14071
14072            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14073                pw.flush();
14074                FileOutputStream fout = new FileOutputStream(fd);
14075                BufferedOutputStream str = new BufferedOutputStream(fout);
14076                XmlSerializer serializer = new FastXmlSerializer();
14077                try {
14078                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14079                    serializer.startDocument(null, true);
14080                    serializer.setFeature(
14081                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14082                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14083                    serializer.endDocument();
14084                    serializer.flush();
14085                } catch (IllegalArgumentException e) {
14086                    pw.println("Failed writing: " + e);
14087                } catch (IllegalStateException e) {
14088                    pw.println("Failed writing: " + e);
14089                } catch (IOException e) {
14090                    pw.println("Failed writing: " + e);
14091                }
14092            }
14093
14094            if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) {
14095                pw.println();
14096                int count = mSettings.mPackages.size();
14097                if (count == 0) {
14098                    pw.println("No domain preferred apps!");
14099                    pw.println();
14100                } else {
14101                    final String prefix = "  ";
14102                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14103                    if (allPackageSettings.size() == 0) {
14104                        pw.println("No domain preferred apps!");
14105                        pw.println();
14106                    } else {
14107                        pw.println("Domain preferred apps status:");
14108                        pw.println();
14109                        count = 0;
14110                        for (PackageSetting ps : allPackageSettings) {
14111                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14112                            if (ivi == null || ivi.getPackageName() == null) continue;
14113                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14114                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14115                            pw.println(prefix + "Status: " + ivi.getStatusString());
14116                            pw.println();
14117                            count++;
14118                        }
14119                        if (count == 0) {
14120                            pw.println(prefix + "No domain preferred app status!");
14121                            pw.println();
14122                        }
14123                        for (int userId : sUserManager.getUserIds()) {
14124                            pw.println("Domain preferred apps for User " + userId + ":");
14125                            pw.println();
14126                            count = 0;
14127                            for (PackageSetting ps : allPackageSettings) {
14128                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14129                                if (ivi == null || ivi.getPackageName() == null) {
14130                                    continue;
14131                                }
14132                                final int status = ps.getDomainVerificationStatusForUser(userId);
14133                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14134                                    continue;
14135                                }
14136                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14137                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14138                                String statusStr = IntentFilterVerificationInfo.
14139                                        getStatusStringFromValue(status);
14140                                pw.println(prefix + "Status: " + statusStr);
14141                                pw.println();
14142                                count++;
14143                            }
14144                            if (count == 0) {
14145                                pw.println(prefix + "No domain preferred apps!");
14146                                pw.println();
14147                            }
14148                        }
14149                    }
14150                }
14151            }
14152
14153            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14154                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
14155                if (packageName == null) {
14156                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14157                        if (iperm == 0) {
14158                            if (dumpState.onTitlePrinted())
14159                                pw.println();
14160                            pw.println("AppOp Permissions:");
14161                        }
14162                        pw.print("  AppOp Permission ");
14163                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14164                        pw.println(":");
14165                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14166                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14167                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14168                        }
14169                    }
14170                }
14171            }
14172
14173            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14174                boolean printedSomething = false;
14175                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14176                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14177                        continue;
14178                    }
14179                    if (!printedSomething) {
14180                        if (dumpState.onTitlePrinted())
14181                            pw.println();
14182                        pw.println("Registered ContentProviders:");
14183                        printedSomething = true;
14184                    }
14185                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14186                    pw.print("    "); pw.println(p.toString());
14187                }
14188                printedSomething = false;
14189                for (Map.Entry<String, PackageParser.Provider> entry :
14190                        mProvidersByAuthority.entrySet()) {
14191                    PackageParser.Provider p = entry.getValue();
14192                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14193                        continue;
14194                    }
14195                    if (!printedSomething) {
14196                        if (dumpState.onTitlePrinted())
14197                            pw.println();
14198                        pw.println("ContentProvider Authorities:");
14199                        printedSomething = true;
14200                    }
14201                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14202                    pw.print("    "); pw.println(p.toString());
14203                    if (p.info != null && p.info.applicationInfo != null) {
14204                        final String appInfo = p.info.applicationInfo.toString();
14205                        pw.print("      applicationInfo="); pw.println(appInfo);
14206                    }
14207                }
14208            }
14209
14210            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14211                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14212            }
14213
14214            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14215                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
14216            }
14217
14218            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14219                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
14220            }
14221
14222            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14223                // XXX should handle packageName != null by dumping only install data that
14224                // the given package is involved with.
14225                if (dumpState.onTitlePrinted()) pw.println();
14226                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14227            }
14228
14229            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14230                if (dumpState.onTitlePrinted()) pw.println();
14231                mSettings.dumpReadMessagesLPr(pw, dumpState);
14232
14233                pw.println();
14234                pw.println("Package warning messages:");
14235                BufferedReader in = null;
14236                String line = null;
14237                try {
14238                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14239                    while ((line = in.readLine()) != null) {
14240                        if (line.contains("ignored: updated version")) continue;
14241                        pw.println(line);
14242                    }
14243                } catch (IOException ignored) {
14244                } finally {
14245                    IoUtils.closeQuietly(in);
14246                }
14247            }
14248
14249            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14250                BufferedReader in = null;
14251                String line = null;
14252                try {
14253                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14254                    while ((line = in.readLine()) != null) {
14255                        if (line.contains("ignored: updated version")) continue;
14256                        pw.print("msg,");
14257                        pw.println(line);
14258                    }
14259                } catch (IOException ignored) {
14260                } finally {
14261                    IoUtils.closeQuietly(in);
14262                }
14263            }
14264        }
14265    }
14266
14267    // ------- apps on sdcard specific code -------
14268    static final boolean DEBUG_SD_INSTALL = false;
14269
14270    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14271
14272    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14273
14274    private boolean mMediaMounted = false;
14275
14276    static String getEncryptKey() {
14277        try {
14278            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14279                    SD_ENCRYPTION_KEYSTORE_NAME);
14280            if (sdEncKey == null) {
14281                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14282                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14283                if (sdEncKey == null) {
14284                    Slog.e(TAG, "Failed to create encryption keys");
14285                    return null;
14286                }
14287            }
14288            return sdEncKey;
14289        } catch (NoSuchAlgorithmException nsae) {
14290            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14291            return null;
14292        } catch (IOException ioe) {
14293            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14294            return null;
14295        }
14296    }
14297
14298    /*
14299     * Update media status on PackageManager.
14300     */
14301    @Override
14302    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14303        int callingUid = Binder.getCallingUid();
14304        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14305            throw new SecurityException("Media status can only be updated by the system");
14306        }
14307        // reader; this apparently protects mMediaMounted, but should probably
14308        // be a different lock in that case.
14309        synchronized (mPackages) {
14310            Log.i(TAG, "Updating external media status from "
14311                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14312                    + (mediaStatus ? "mounted" : "unmounted"));
14313            if (DEBUG_SD_INSTALL)
14314                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14315                        + ", mMediaMounted=" + mMediaMounted);
14316            if (mediaStatus == mMediaMounted) {
14317                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14318                        : 0, -1);
14319                mHandler.sendMessage(msg);
14320                return;
14321            }
14322            mMediaMounted = mediaStatus;
14323        }
14324        // Queue up an async operation since the package installation may take a
14325        // little while.
14326        mHandler.post(new Runnable() {
14327            public void run() {
14328                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14329            }
14330        });
14331    }
14332
14333    /**
14334     * Called by MountService when the initial ASECs to scan are available.
14335     * Should block until all the ASEC containers are finished being scanned.
14336     */
14337    public void scanAvailableAsecs() {
14338        updateExternalMediaStatusInner(true, false, false);
14339        if (mShouldRestoreconData) {
14340            SELinuxMMAC.setRestoreconDone();
14341            mShouldRestoreconData = false;
14342        }
14343    }
14344
14345    /*
14346     * Collect information of applications on external media, map them against
14347     * existing containers and update information based on current mount status.
14348     * Please note that we always have to report status if reportStatus has been
14349     * set to true especially when unloading packages.
14350     */
14351    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14352            boolean externalStorage) {
14353        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14354        int[] uidArr = EmptyArray.INT;
14355
14356        final String[] list = PackageHelper.getSecureContainerList();
14357        if (ArrayUtils.isEmpty(list)) {
14358            Log.i(TAG, "No secure containers found");
14359        } else {
14360            // Process list of secure containers and categorize them
14361            // as active or stale based on their package internal state.
14362
14363            // reader
14364            synchronized (mPackages) {
14365                for (String cid : list) {
14366                    // Leave stages untouched for now; installer service owns them
14367                    if (PackageInstallerService.isStageName(cid)) continue;
14368
14369                    if (DEBUG_SD_INSTALL)
14370                        Log.i(TAG, "Processing container " + cid);
14371                    String pkgName = getAsecPackageName(cid);
14372                    if (pkgName == null) {
14373                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14374                        continue;
14375                    }
14376                    if (DEBUG_SD_INSTALL)
14377                        Log.i(TAG, "Looking for pkg : " + pkgName);
14378
14379                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14380                    if (ps == null) {
14381                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14382                        continue;
14383                    }
14384
14385                    /*
14386                     * Skip packages that are not external if we're unmounting
14387                     * external storage.
14388                     */
14389                    if (externalStorage && !isMounted && !isExternal(ps)) {
14390                        continue;
14391                    }
14392
14393                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14394                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14395                    // The package status is changed only if the code path
14396                    // matches between settings and the container id.
14397                    if (ps.codePathString != null
14398                            && ps.codePathString.startsWith(args.getCodePath())) {
14399                        if (DEBUG_SD_INSTALL) {
14400                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14401                                    + " at code path: " + ps.codePathString);
14402                        }
14403
14404                        // We do have a valid package installed on sdcard
14405                        processCids.put(args, ps.codePathString);
14406                        final int uid = ps.appId;
14407                        if (uid != -1) {
14408                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14409                        }
14410                    } else {
14411                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14412                                + ps.codePathString);
14413                    }
14414                }
14415            }
14416
14417            Arrays.sort(uidArr);
14418        }
14419
14420        // Process packages with valid entries.
14421        if (isMounted) {
14422            if (DEBUG_SD_INSTALL)
14423                Log.i(TAG, "Loading packages");
14424            loadMediaPackages(processCids, uidArr);
14425            startCleaningPackages();
14426            mInstallerService.onSecureContainersAvailable();
14427        } else {
14428            if (DEBUG_SD_INSTALL)
14429                Log.i(TAG, "Unloading packages");
14430            unloadMediaPackages(processCids, uidArr, reportStatus);
14431        }
14432    }
14433
14434    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14435            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14436        final int size = infos.size();
14437        final String[] packageNames = new String[size];
14438        final int[] packageUids = new int[size];
14439        for (int i = 0; i < size; i++) {
14440            final ApplicationInfo info = infos.get(i);
14441            packageNames[i] = info.packageName;
14442            packageUids[i] = info.uid;
14443        }
14444        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14445                finishedReceiver);
14446    }
14447
14448    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14449            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14450        sendResourcesChangedBroadcast(mediaStatus, replacing,
14451                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14452    }
14453
14454    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14455            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14456        int size = pkgList.length;
14457        if (size > 0) {
14458            // Send broadcasts here
14459            Bundle extras = new Bundle();
14460            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14461            if (uidArr != null) {
14462                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14463            }
14464            if (replacing) {
14465                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14466            }
14467            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14468                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14469            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14470        }
14471    }
14472
14473   /*
14474     * Look at potentially valid container ids from processCids If package
14475     * information doesn't match the one on record or package scanning fails,
14476     * the cid is added to list of removeCids. We currently don't delete stale
14477     * containers.
14478     */
14479    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14480        ArrayList<String> pkgList = new ArrayList<String>();
14481        Set<AsecInstallArgs> keys = processCids.keySet();
14482
14483        for (AsecInstallArgs args : keys) {
14484            String codePath = processCids.get(args);
14485            if (DEBUG_SD_INSTALL)
14486                Log.i(TAG, "Loading container : " + args.cid);
14487            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14488            try {
14489                // Make sure there are no container errors first.
14490                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14491                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14492                            + " when installing from sdcard");
14493                    continue;
14494                }
14495                // Check code path here.
14496                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14497                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14498                            + " does not match one in settings " + codePath);
14499                    continue;
14500                }
14501                // Parse package
14502                int parseFlags = mDefParseFlags;
14503                if (args.isExternalAsec()) {
14504                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14505                }
14506                if (args.isFwdLocked()) {
14507                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14508                }
14509
14510                synchronized (mInstallLock) {
14511                    PackageParser.Package pkg = null;
14512                    try {
14513                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14514                    } catch (PackageManagerException e) {
14515                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14516                    }
14517                    // Scan the package
14518                    if (pkg != null) {
14519                        /*
14520                         * TODO why is the lock being held? doPostInstall is
14521                         * called in other places without the lock. This needs
14522                         * to be straightened out.
14523                         */
14524                        // writer
14525                        synchronized (mPackages) {
14526                            retCode = PackageManager.INSTALL_SUCCEEDED;
14527                            pkgList.add(pkg.packageName);
14528                            // Post process args
14529                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14530                                    pkg.applicationInfo.uid);
14531                        }
14532                    } else {
14533                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14534                    }
14535                }
14536
14537            } finally {
14538                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14539                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14540                }
14541            }
14542        }
14543        // writer
14544        synchronized (mPackages) {
14545            // If the platform SDK has changed since the last time we booted,
14546            // we need to re-grant app permission to catch any new ones that
14547            // appear. This is really a hack, and means that apps can in some
14548            // cases get permissions that the user didn't initially explicitly
14549            // allow... it would be nice to have some better way to handle
14550            // this situation.
14551            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14552            if (regrantPermissions)
14553                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14554                        + mSdkVersion + "; regranting permissions for external storage");
14555            mSettings.mExternalSdkPlatform = mSdkVersion;
14556
14557            // Make sure group IDs have been assigned, and any permission
14558            // changes in other apps are accounted for
14559            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14560                    | (regrantPermissions
14561                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14562                            : 0));
14563
14564            mSettings.updateExternalDatabaseVersion();
14565
14566            // can downgrade to reader
14567            // Persist settings
14568            mSettings.writeLPr();
14569        }
14570        // Send a broadcast to let everyone know we are done processing
14571        if (pkgList.size() > 0) {
14572            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14573        }
14574    }
14575
14576   /*
14577     * Utility method to unload a list of specified containers
14578     */
14579    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14580        // Just unmount all valid containers.
14581        for (AsecInstallArgs arg : cidArgs) {
14582            synchronized (mInstallLock) {
14583                arg.doPostDeleteLI(false);
14584           }
14585       }
14586   }
14587
14588    /*
14589     * Unload packages mounted on external media. This involves deleting package
14590     * data from internal structures, sending broadcasts about diabled packages,
14591     * gc'ing to free up references, unmounting all secure containers
14592     * corresponding to packages on external media, and posting a
14593     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14594     * that we always have to post this message if status has been requested no
14595     * matter what.
14596     */
14597    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14598            final boolean reportStatus) {
14599        if (DEBUG_SD_INSTALL)
14600            Log.i(TAG, "unloading media packages");
14601        ArrayList<String> pkgList = new ArrayList<String>();
14602        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14603        final Set<AsecInstallArgs> keys = processCids.keySet();
14604        for (AsecInstallArgs args : keys) {
14605            String pkgName = args.getPackageName();
14606            if (DEBUG_SD_INSTALL)
14607                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14608            // Delete package internally
14609            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14610            synchronized (mInstallLock) {
14611                boolean res = deletePackageLI(pkgName, null, false, null, null,
14612                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14613                if (res) {
14614                    pkgList.add(pkgName);
14615                } else {
14616                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14617                    failedList.add(args);
14618                }
14619            }
14620        }
14621
14622        // reader
14623        synchronized (mPackages) {
14624            // We didn't update the settings after removing each package;
14625            // write them now for all packages.
14626            mSettings.writeLPr();
14627        }
14628
14629        // We have to absolutely send UPDATED_MEDIA_STATUS only
14630        // after confirming that all the receivers processed the ordered
14631        // broadcast when packages get disabled, force a gc to clean things up.
14632        // and unload all the containers.
14633        if (pkgList.size() > 0) {
14634            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14635                    new IIntentReceiver.Stub() {
14636                public void performReceive(Intent intent, int resultCode, String data,
14637                        Bundle extras, boolean ordered, boolean sticky,
14638                        int sendingUser) throws RemoteException {
14639                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14640                            reportStatus ? 1 : 0, 1, keys);
14641                    mHandler.sendMessage(msg);
14642                }
14643            });
14644        } else {
14645            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14646                    keys);
14647            mHandler.sendMessage(msg);
14648        }
14649    }
14650
14651    private void loadPrivatePackages(VolumeInfo vol) {
14652        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14653        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14654        synchronized (mInstallLock) {
14655        synchronized (mPackages) {
14656            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14657            for (PackageSetting ps : packages) {
14658                final PackageParser.Package pkg;
14659                try {
14660                    pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14661                    loaded.add(pkg.applicationInfo);
14662                } catch (PackageManagerException e) {
14663                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14664                }
14665            }
14666
14667            // TODO: regrant any permissions that changed based since original install
14668
14669            mSettings.writeLPr();
14670        }
14671        }
14672
14673        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
14674        sendResourcesChangedBroadcast(true, false, loaded, null);
14675    }
14676
14677    private void unloadPrivatePackages(VolumeInfo vol) {
14678        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14679        synchronized (mInstallLock) {
14680        synchronized (mPackages) {
14681            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14682            for (PackageSetting ps : packages) {
14683                if (ps.pkg == null) continue;
14684
14685                final ApplicationInfo info = ps.pkg.applicationInfo;
14686                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14687                if (deletePackageLI(ps.name, null, false, null, null,
14688                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14689                    unloaded.add(info);
14690                } else {
14691                    Slog.w(TAG, "Failed to unload " + ps.codePath);
14692                }
14693            }
14694
14695            mSettings.writeLPr();
14696        }
14697        }
14698
14699        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
14700        sendResourcesChangedBroadcast(false, false, unloaded, null);
14701    }
14702
14703    private void unfreezePackage(String packageName) {
14704        synchronized (mPackages) {
14705            final PackageSetting ps = mSettings.mPackages.get(packageName);
14706            if (ps != null) {
14707                ps.frozen = false;
14708            }
14709        }
14710    }
14711
14712    @Override
14713    public int movePackage(final String packageName, final String volumeUuid) {
14714        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14715
14716        final int moveId = mNextMoveId.getAndIncrement();
14717        try {
14718            movePackageInternal(packageName, volumeUuid, moveId);
14719        } catch (PackageManagerException e) {
14720            Slog.w(TAG, "Failed to move " + packageName, e);
14721            mMoveCallbacks.notifyStatusChanged(moveId,
14722                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14723        }
14724        return moveId;
14725    }
14726
14727    private void movePackageInternal(final String packageName, final String volumeUuid,
14728            final int moveId) throws PackageManagerException {
14729        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14730        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14731        final PackageManager pm = mContext.getPackageManager();
14732
14733        final boolean currentAsec;
14734        final String currentVolumeUuid;
14735        final File codeFile;
14736        final String installerPackageName;
14737        final String packageAbiOverride;
14738        final int appId;
14739        final String seinfo;
14740        final String label;
14741
14742        // reader
14743        synchronized (mPackages) {
14744            final PackageParser.Package pkg = mPackages.get(packageName);
14745            final PackageSetting ps = mSettings.mPackages.get(packageName);
14746            if (pkg == null || ps == null) {
14747                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14748            }
14749
14750            if (pkg.applicationInfo.isSystemApp()) {
14751                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14752                        "Cannot move system application");
14753            }
14754
14755            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
14756                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14757                        "Package already moved to " + volumeUuid);
14758            }
14759
14760            final File probe = new File(pkg.codePath);
14761            final File probeOat = new File(probe, "oat");
14762            if (!probe.isDirectory() || !probeOat.isDirectory()) {
14763                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14764                        "Move only supported for modern cluster style installs");
14765            }
14766
14767            if (ps.frozen) {
14768                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14769                        "Failed to move already frozen package");
14770            }
14771            ps.frozen = true;
14772
14773            currentAsec = pkg.applicationInfo.isForwardLocked()
14774                    || pkg.applicationInfo.isExternalAsec();
14775            currentVolumeUuid = ps.volumeUuid;
14776            codeFile = new File(pkg.codePath);
14777            installerPackageName = ps.installerPackageName;
14778            packageAbiOverride = ps.cpuAbiOverrideString;
14779            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14780            seinfo = pkg.applicationInfo.seinfo;
14781            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
14782        }
14783
14784        // Now that we're guarded by frozen state, kill app during move
14785        killApplication(packageName, appId, "move pkg");
14786
14787        final Bundle extras = new Bundle();
14788        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
14789        extras.putString(Intent.EXTRA_TITLE, label);
14790        mMoveCallbacks.notifyCreated(moveId, extras);
14791
14792        int installFlags;
14793        final boolean moveCompleteApp;
14794        final File measurePath;
14795
14796        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
14797            installFlags = INSTALL_INTERNAL;
14798            moveCompleteApp = !currentAsec;
14799            measurePath = Environment.getDataAppDirectory(volumeUuid);
14800        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
14801            installFlags = INSTALL_EXTERNAL;
14802            moveCompleteApp = false;
14803            measurePath = storage.getPrimaryPhysicalVolume().getPath();
14804        } else {
14805            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
14806            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
14807                    || !volume.isMountedWritable()) {
14808                unfreezePackage(packageName);
14809                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14810                        "Move location not mounted private volume");
14811            }
14812
14813            Preconditions.checkState(!currentAsec);
14814
14815            installFlags = INSTALL_INTERNAL;
14816            moveCompleteApp = true;
14817            measurePath = Environment.getDataAppDirectory(volumeUuid);
14818        }
14819
14820        final PackageStats stats = new PackageStats(null, -1);
14821        synchronized (mInstaller) {
14822            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
14823                unfreezePackage(packageName);
14824                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14825                        "Failed to measure package size");
14826            }
14827        }
14828
14829        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
14830                + stats.dataSize);
14831
14832        final long startFreeBytes = measurePath.getFreeSpace();
14833        final long sizeBytes;
14834        if (moveCompleteApp) {
14835            sizeBytes = stats.codeSize + stats.dataSize;
14836        } else {
14837            sizeBytes = stats.codeSize;
14838        }
14839
14840        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
14841            unfreezePackage(packageName);
14842            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14843                    "Not enough free space to move");
14844        }
14845
14846        mMoveCallbacks.notifyStatusChanged(moveId, 10);
14847
14848        final CountDownLatch installedLatch = new CountDownLatch(1);
14849        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14850            @Override
14851            public void onUserActionRequired(Intent intent) throws RemoteException {
14852                throw new IllegalStateException();
14853            }
14854
14855            @Override
14856            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14857                    Bundle extras) throws RemoteException {
14858                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
14859                        + PackageManager.installStatusToString(returnCode, msg));
14860
14861                installedLatch.countDown();
14862
14863                // Regardless of success or failure of the move operation,
14864                // always unfreeze the package
14865                unfreezePackage(packageName);
14866
14867                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14868                switch (status) {
14869                    case PackageInstaller.STATUS_SUCCESS:
14870                        mMoveCallbacks.notifyStatusChanged(moveId,
14871                                PackageManager.MOVE_SUCCEEDED);
14872                        break;
14873                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14874                        mMoveCallbacks.notifyStatusChanged(moveId,
14875                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14876                        break;
14877                    default:
14878                        mMoveCallbacks.notifyStatusChanged(moveId,
14879                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14880                        break;
14881                }
14882            }
14883        };
14884
14885        final MoveInfo move;
14886        if (moveCompleteApp) {
14887            // Kick off a thread to report progress estimates
14888            new Thread() {
14889                @Override
14890                public void run() {
14891                    while (true) {
14892                        try {
14893                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
14894                                break;
14895                            }
14896                        } catch (InterruptedException ignored) {
14897                        }
14898
14899                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
14900                        final int progress = 10 + (int) MathUtils.constrain(
14901                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
14902                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
14903                    }
14904                }
14905            }.start();
14906
14907            final String dataAppName = codeFile.getName();
14908            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
14909                    dataAppName, appId, seinfo);
14910        } else {
14911            move = null;
14912        }
14913
14914        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14915
14916        final Message msg = mHandler.obtainMessage(INIT_COPY);
14917        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14918        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
14919                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14920        mHandler.sendMessage(msg);
14921    }
14922
14923    @Override
14924    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
14925        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14926
14927        final int realMoveId = mNextMoveId.getAndIncrement();
14928        final Bundle extras = new Bundle();
14929        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
14930        mMoveCallbacks.notifyCreated(realMoveId, extras);
14931
14932        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
14933            @Override
14934            public void onCreated(int moveId, Bundle extras) {
14935                // Ignored
14936            }
14937
14938            @Override
14939            public void onStatusChanged(int moveId, int status, long estMillis) {
14940                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
14941            }
14942        };
14943
14944        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14945        storage.setPrimaryStorageUuid(volumeUuid, callback);
14946        return realMoveId;
14947    }
14948
14949    @Override
14950    public int getMoveStatus(int moveId) {
14951        mContext.enforceCallingOrSelfPermission(
14952                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14953        return mMoveCallbacks.mLastStatus.get(moveId);
14954    }
14955
14956    @Override
14957    public void registerMoveCallback(IPackageMoveObserver callback) {
14958        mContext.enforceCallingOrSelfPermission(
14959                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14960        mMoveCallbacks.register(callback);
14961    }
14962
14963    @Override
14964    public void unregisterMoveCallback(IPackageMoveObserver callback) {
14965        mContext.enforceCallingOrSelfPermission(
14966                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14967        mMoveCallbacks.unregister(callback);
14968    }
14969
14970    @Override
14971    public boolean setInstallLocation(int loc) {
14972        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14973                null);
14974        if (getInstallLocation() == loc) {
14975            return true;
14976        }
14977        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14978                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14979            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14980                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14981            return true;
14982        }
14983        return false;
14984   }
14985
14986    @Override
14987    public int getInstallLocation() {
14988        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14989                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14990                PackageHelper.APP_INSTALL_AUTO);
14991    }
14992
14993    /** Called by UserManagerService */
14994    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14995        mDirtyUsers.remove(userHandle);
14996        mSettings.removeUserLPw(userHandle);
14997        mPendingBroadcasts.remove(userHandle);
14998        if (mInstaller != null) {
14999            // Technically, we shouldn't be doing this with the package lock
15000            // held.  However, this is very rare, and there is already so much
15001            // other disk I/O going on, that we'll let it slide for now.
15002            final StorageManager storage = StorageManager.from(mContext);
15003            final List<VolumeInfo> vols = storage.getVolumes();
15004            for (VolumeInfo vol : vols) {
15005                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
15006                    final String volumeUuid = vol.getFsUuid();
15007                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15008                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15009                }
15010            }
15011        }
15012        mUserNeedsBadging.delete(userHandle);
15013        removeUnusedPackagesLILPw(userManager, userHandle);
15014    }
15015
15016    /**
15017     * We're removing userHandle and would like to remove any downloaded packages
15018     * that are no longer in use by any other user.
15019     * @param userHandle the user being removed
15020     */
15021    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15022        final boolean DEBUG_CLEAN_APKS = false;
15023        int [] users = userManager.getUserIdsLPr();
15024        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15025        while (psit.hasNext()) {
15026            PackageSetting ps = psit.next();
15027            if (ps.pkg == null) {
15028                continue;
15029            }
15030            final String packageName = ps.pkg.packageName;
15031            // Skip over if system app
15032            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15033                continue;
15034            }
15035            if (DEBUG_CLEAN_APKS) {
15036                Slog.i(TAG, "Checking package " + packageName);
15037            }
15038            boolean keep = false;
15039            for (int i = 0; i < users.length; i++) {
15040                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15041                    keep = true;
15042                    if (DEBUG_CLEAN_APKS) {
15043                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15044                                + users[i]);
15045                    }
15046                    break;
15047                }
15048            }
15049            if (!keep) {
15050                if (DEBUG_CLEAN_APKS) {
15051                    Slog.i(TAG, "  Removing package " + packageName);
15052                }
15053                mHandler.post(new Runnable() {
15054                    public void run() {
15055                        deletePackageX(packageName, userHandle, 0);
15056                    } //end run
15057                });
15058            }
15059        }
15060    }
15061
15062    /** Called by UserManagerService */
15063    void createNewUserLILPw(int userHandle, File path) {
15064        if (mInstaller != null) {
15065            mInstaller.createUserConfig(userHandle);
15066            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
15067        }
15068    }
15069
15070    void newUserCreatedLILPw(int userHandle) {
15071        // Adding a user requires updating runtime permissions for system apps.
15072        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
15073    }
15074
15075    @Override
15076    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15077        mContext.enforceCallingOrSelfPermission(
15078                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15079                "Only package verification agents can read the verifier device identity");
15080
15081        synchronized (mPackages) {
15082            return mSettings.getVerifierDeviceIdentityLPw();
15083        }
15084    }
15085
15086    @Override
15087    public void setPermissionEnforced(String permission, boolean enforced) {
15088        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15089        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15090            synchronized (mPackages) {
15091                if (mSettings.mReadExternalStorageEnforced == null
15092                        || mSettings.mReadExternalStorageEnforced != enforced) {
15093                    mSettings.mReadExternalStorageEnforced = enforced;
15094                    mSettings.writeLPr();
15095                }
15096            }
15097            // kill any non-foreground processes so we restart them and
15098            // grant/revoke the GID.
15099            final IActivityManager am = ActivityManagerNative.getDefault();
15100            if (am != null) {
15101                final long token = Binder.clearCallingIdentity();
15102                try {
15103                    am.killProcessesBelowForeground("setPermissionEnforcement");
15104                } catch (RemoteException e) {
15105                } finally {
15106                    Binder.restoreCallingIdentity(token);
15107                }
15108            }
15109        } else {
15110            throw new IllegalArgumentException("No selective enforcement for " + permission);
15111        }
15112    }
15113
15114    @Override
15115    @Deprecated
15116    public boolean isPermissionEnforced(String permission) {
15117        return true;
15118    }
15119
15120    @Override
15121    public boolean isStorageLow() {
15122        final long token = Binder.clearCallingIdentity();
15123        try {
15124            final DeviceStorageMonitorInternal
15125                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15126            if (dsm != null) {
15127                return dsm.isMemoryLow();
15128            } else {
15129                return false;
15130            }
15131        } finally {
15132            Binder.restoreCallingIdentity(token);
15133        }
15134    }
15135
15136    @Override
15137    public IPackageInstaller getPackageInstaller() {
15138        return mInstallerService;
15139    }
15140
15141    private boolean userNeedsBadging(int userId) {
15142        int index = mUserNeedsBadging.indexOfKey(userId);
15143        if (index < 0) {
15144            final UserInfo userInfo;
15145            final long token = Binder.clearCallingIdentity();
15146            try {
15147                userInfo = sUserManager.getUserInfo(userId);
15148            } finally {
15149                Binder.restoreCallingIdentity(token);
15150            }
15151            final boolean b;
15152            if (userInfo != null && userInfo.isManagedProfile()) {
15153                b = true;
15154            } else {
15155                b = false;
15156            }
15157            mUserNeedsBadging.put(userId, b);
15158            return b;
15159        }
15160        return mUserNeedsBadging.valueAt(index);
15161    }
15162
15163    @Override
15164    public KeySet getKeySetByAlias(String packageName, String alias) {
15165        if (packageName == null || alias == null) {
15166            return null;
15167        }
15168        synchronized(mPackages) {
15169            final PackageParser.Package pkg = mPackages.get(packageName);
15170            if (pkg == null) {
15171                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15172                throw new IllegalArgumentException("Unknown package: " + packageName);
15173            }
15174            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15175            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15176        }
15177    }
15178
15179    @Override
15180    public KeySet getSigningKeySet(String packageName) {
15181        if (packageName == null) {
15182            return null;
15183        }
15184        synchronized(mPackages) {
15185            final PackageParser.Package pkg = mPackages.get(packageName);
15186            if (pkg == null) {
15187                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15188                throw new IllegalArgumentException("Unknown package: " + packageName);
15189            }
15190            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15191                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15192                throw new SecurityException("May not access signing KeySet of other apps.");
15193            }
15194            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15195            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15196        }
15197    }
15198
15199    @Override
15200    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15201        if (packageName == null || ks == null) {
15202            return false;
15203        }
15204        synchronized(mPackages) {
15205            final PackageParser.Package pkg = mPackages.get(packageName);
15206            if (pkg == null) {
15207                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15208                throw new IllegalArgumentException("Unknown package: " + packageName);
15209            }
15210            IBinder ksh = ks.getToken();
15211            if (ksh instanceof KeySetHandle) {
15212                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15213                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15214            }
15215            return false;
15216        }
15217    }
15218
15219    @Override
15220    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15221        if (packageName == null || ks == null) {
15222            return false;
15223        }
15224        synchronized(mPackages) {
15225            final PackageParser.Package pkg = mPackages.get(packageName);
15226            if (pkg == null) {
15227                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15228                throw new IllegalArgumentException("Unknown package: " + packageName);
15229            }
15230            IBinder ksh = ks.getToken();
15231            if (ksh instanceof KeySetHandle) {
15232                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15233                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15234            }
15235            return false;
15236        }
15237    }
15238
15239    public void getUsageStatsIfNoPackageUsageInfo() {
15240        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15241            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15242            if (usm == null) {
15243                throw new IllegalStateException("UsageStatsManager must be initialized");
15244            }
15245            long now = System.currentTimeMillis();
15246            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15247            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15248                String packageName = entry.getKey();
15249                PackageParser.Package pkg = mPackages.get(packageName);
15250                if (pkg == null) {
15251                    continue;
15252                }
15253                UsageStats usage = entry.getValue();
15254                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15255                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15256            }
15257        }
15258    }
15259
15260    /**
15261     * Check and throw if the given before/after packages would be considered a
15262     * downgrade.
15263     */
15264    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15265            throws PackageManagerException {
15266        if (after.versionCode < before.mVersionCode) {
15267            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15268                    "Update version code " + after.versionCode + " is older than current "
15269                    + before.mVersionCode);
15270        } else if (after.versionCode == before.mVersionCode) {
15271            if (after.baseRevisionCode < before.baseRevisionCode) {
15272                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15273                        "Update base revision code " + after.baseRevisionCode
15274                        + " is older than current " + before.baseRevisionCode);
15275            }
15276
15277            if (!ArrayUtils.isEmpty(after.splitNames)) {
15278                for (int i = 0; i < after.splitNames.length; i++) {
15279                    final String splitName = after.splitNames[i];
15280                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15281                    if (j != -1) {
15282                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15283                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15284                                    "Update split " + splitName + " revision code "
15285                                    + after.splitRevisionCodes[i] + " is older than current "
15286                                    + before.splitRevisionCodes[j]);
15287                        }
15288                    }
15289                }
15290            }
15291        }
15292    }
15293
15294    private static class MoveCallbacks extends Handler {
15295        private static final int MSG_CREATED = 1;
15296        private static final int MSG_STATUS_CHANGED = 2;
15297
15298        private final RemoteCallbackList<IPackageMoveObserver>
15299                mCallbacks = new RemoteCallbackList<>();
15300
15301        private final SparseIntArray mLastStatus = new SparseIntArray();
15302
15303        public MoveCallbacks(Looper looper) {
15304            super(looper);
15305        }
15306
15307        public void register(IPackageMoveObserver callback) {
15308            mCallbacks.register(callback);
15309        }
15310
15311        public void unregister(IPackageMoveObserver callback) {
15312            mCallbacks.unregister(callback);
15313        }
15314
15315        @Override
15316        public void handleMessage(Message msg) {
15317            final SomeArgs args = (SomeArgs) msg.obj;
15318            final int n = mCallbacks.beginBroadcast();
15319            for (int i = 0; i < n; i++) {
15320                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15321                try {
15322                    invokeCallback(callback, msg.what, args);
15323                } catch (RemoteException ignored) {
15324                }
15325            }
15326            mCallbacks.finishBroadcast();
15327            args.recycle();
15328        }
15329
15330        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15331                throws RemoteException {
15332            switch (what) {
15333                case MSG_CREATED: {
15334                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15335                    break;
15336                }
15337                case MSG_STATUS_CHANGED: {
15338                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15339                    break;
15340                }
15341            }
15342        }
15343
15344        private void notifyCreated(int moveId, Bundle extras) {
15345            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15346
15347            final SomeArgs args = SomeArgs.obtain();
15348            args.argi1 = moveId;
15349            args.arg2 = extras;
15350            obtainMessage(MSG_CREATED, args).sendToTarget();
15351        }
15352
15353        private void notifyStatusChanged(int moveId, int status) {
15354            notifyStatusChanged(moveId, status, -1);
15355        }
15356
15357        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15358            Slog.v(TAG, "Move " + moveId + " status " + status);
15359
15360            final SomeArgs args = SomeArgs.obtain();
15361            args.argi1 = moveId;
15362            args.argi2 = status;
15363            args.arg3 = estMillis;
15364            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15365
15366            synchronized (mLastStatus) {
15367                mLastStatus.put(moveId, status);
15368            }
15369        }
15370    }
15371
15372    private final class OnPermissionChangeListeners extends Handler {
15373        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
15374
15375        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
15376                new RemoteCallbackList<>();
15377
15378        public OnPermissionChangeListeners(Looper looper) {
15379            super(looper);
15380        }
15381
15382        @Override
15383        public void handleMessage(Message msg) {
15384            switch (msg.what) {
15385                case MSG_ON_PERMISSIONS_CHANGED: {
15386                    final int uid = msg.arg1;
15387                    handleOnPermissionsChanged(uid);
15388                } break;
15389            }
15390        }
15391
15392        public void addListenerLocked(IOnPermissionsChangeListener listener) {
15393            mPermissionListeners.register(listener);
15394
15395        }
15396
15397        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
15398            mPermissionListeners.unregister(listener);
15399        }
15400
15401        public void onPermissionsChanged(int uid) {
15402            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
15403                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
15404            }
15405        }
15406
15407        private void handleOnPermissionsChanged(int uid) {
15408            final int count = mPermissionListeners.beginBroadcast();
15409            try {
15410                for (int i = 0; i < count; i++) {
15411                    IOnPermissionsChangeListener callback = mPermissionListeners
15412                            .getBroadcastItem(i);
15413                    try {
15414                        callback.onPermissionsChanged(uid);
15415                    } catch (RemoteException e) {
15416                        Log.e(TAG, "Permission listener is dead", e);
15417                    }
15418                }
15419            } finally {
15420                mPermissionListeners.finishBroadcast();
15421            }
15422        }
15423    }
15424}
15425