PackageManagerService.java revision 9edbda18df025527e18614cf0c45d538a27af30f
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
46import static android.content.pm.PackageManager.INSTALL_INTERNAL;
47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
52import static android.content.pm.PackageManager.MATCH_ALL;
53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
57import static android.content.pm.PackageParser.isApkFile;
58import static android.os.Process.FIRST_APPLICATION_UID;
59import static android.os.Process.PACKAGE_INFO_GID;
60import static android.os.Process.SYSTEM_UID;
61import static android.system.OsConstants.O_CREAT;
62import static android.system.OsConstants.O_RDWR;
63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
65import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
66import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
67import static com.android.internal.util.ArrayUtils.appendInt;
68import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
71import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
72import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
73
74import android.Manifest;
75import android.app.ActivityManager;
76import android.app.ActivityManagerNative;
77import android.app.AppGlobals;
78import android.app.IActivityManager;
79import android.app.admin.IDevicePolicyManager;
80import android.app.backup.IBackupManager;
81import android.app.usage.UsageStats;
82import android.app.usage.UsageStatsManager;
83import android.content.BroadcastReceiver;
84import android.content.ComponentName;
85import android.content.Context;
86import android.content.IIntentReceiver;
87import android.content.Intent;
88import android.content.IntentFilter;
89import android.content.IntentSender;
90import android.content.IntentSender.SendIntentException;
91import android.content.ServiceConnection;
92import android.content.pm.ActivityInfo;
93import android.content.pm.ApplicationInfo;
94import android.content.pm.FeatureInfo;
95import android.content.pm.IOnPermissionsChangeListener;
96import android.content.pm.IPackageDataObserver;
97import android.content.pm.IPackageDeleteObserver;
98import android.content.pm.IPackageDeleteObserver2;
99import android.content.pm.IPackageInstallObserver2;
100import android.content.pm.IPackageInstaller;
101import android.content.pm.IPackageManager;
102import android.content.pm.IPackageMoveObserver;
103import android.content.pm.IPackageStatsObserver;
104import android.content.pm.InstrumentationInfo;
105import android.content.pm.IntentFilterVerificationInfo;
106import android.content.pm.KeySet;
107import android.content.pm.ManifestDigest;
108import android.content.pm.PackageCleanItem;
109import android.content.pm.PackageInfo;
110import android.content.pm.PackageInfoLite;
111import android.content.pm.PackageInstaller;
112import android.content.pm.PackageManager;
113import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
114import android.content.pm.PackageParser;
115import android.content.pm.PackageParser.ActivityIntentInfo;
116import android.content.pm.PackageParser.PackageLite;
117import android.content.pm.PackageParser.PackageParserException;
118import android.content.pm.PackageStats;
119import android.content.pm.PackageUserState;
120import android.content.pm.ParceledListSlice;
121import android.content.pm.PermissionGroupInfo;
122import android.content.pm.PermissionInfo;
123import android.content.pm.ProviderInfo;
124import android.content.pm.ResolveInfo;
125import android.content.pm.ServiceInfo;
126import android.content.pm.Signature;
127import android.content.pm.UserInfo;
128import android.content.pm.VerificationParams;
129import android.content.pm.VerifierDeviceIdentity;
130import android.content.pm.VerifierInfo;
131import android.content.res.Resources;
132import android.hardware.display.DisplayManager;
133import android.net.Uri;
134import android.os.Binder;
135import android.os.Build;
136import android.os.Bundle;
137import android.os.Debug;
138import android.os.Environment;
139import android.os.Environment.UserEnvironment;
140import android.os.FileUtils;
141import android.os.Handler;
142import android.os.IBinder;
143import android.os.Looper;
144import android.os.Message;
145import android.os.Parcel;
146import android.os.ParcelFileDescriptor;
147import android.os.Process;
148import android.os.RemoteCallbackList;
149import android.os.RemoteException;
150import android.os.SELinux;
151import android.os.ServiceManager;
152import android.os.SystemClock;
153import android.os.SystemProperties;
154import android.os.UserHandle;
155import android.os.UserManager;
156import android.os.storage.IMountService;
157import android.os.storage.StorageEventListener;
158import android.os.storage.StorageManager;
159import android.os.storage.VolumeInfo;
160import android.os.storage.VolumeRecord;
161import android.security.KeyStore;
162import android.security.SystemKeyStore;
163import android.system.ErrnoException;
164import android.system.Os;
165import android.system.StructStat;
166import android.text.TextUtils;
167import android.text.format.DateUtils;
168import android.util.ArrayMap;
169import android.util.ArraySet;
170import android.util.AtomicFile;
171import android.util.DisplayMetrics;
172import android.util.EventLog;
173import android.util.ExceptionUtils;
174import android.util.Log;
175import android.util.LogPrinter;
176import android.util.MathUtils;
177import android.util.PrintStreamPrinter;
178import android.util.Slog;
179import android.util.SparseArray;
180import android.util.SparseBooleanArray;
181import android.util.SparseIntArray;
182import android.util.Xml;
183import android.view.Display;
184
185import dalvik.system.DexFile;
186import dalvik.system.VMRuntime;
187
188import libcore.io.IoUtils;
189import libcore.util.EmptyArray;
190
191import com.android.internal.R;
192import com.android.internal.app.IMediaContainerService;
193import com.android.internal.app.ResolverActivity;
194import com.android.internal.content.NativeLibraryHelper;
195import com.android.internal.content.PackageHelper;
196import com.android.internal.os.IParcelFileDescriptorFactory;
197import com.android.internal.os.SomeArgs;
198import com.android.internal.util.ArrayUtils;
199import com.android.internal.util.FastPrintWriter;
200import com.android.internal.util.FastXmlSerializer;
201import com.android.internal.util.IndentingPrintWriter;
202import com.android.internal.util.Preconditions;
203import com.android.server.EventLogTags;
204import com.android.server.FgThread;
205import com.android.server.IntentResolver;
206import com.android.server.LocalServices;
207import com.android.server.ServiceThread;
208import com.android.server.SystemConfig;
209import com.android.server.Watchdog;
210import com.android.server.pm.Settings.DatabaseVersion;
211import com.android.server.pm.PermissionsState.PermissionState;
212import com.android.server.storage.DeviceStorageMonitorInternal;
213
214import org.xmlpull.v1.XmlPullParser;
215import org.xmlpull.v1.XmlSerializer;
216
217import java.io.BufferedInputStream;
218import java.io.BufferedOutputStream;
219import java.io.BufferedReader;
220import java.io.ByteArrayInputStream;
221import java.io.ByteArrayOutputStream;
222import java.io.File;
223import java.io.FileDescriptor;
224import java.io.FileNotFoundException;
225import java.io.FileOutputStream;
226import java.io.FileReader;
227import java.io.FilenameFilter;
228import java.io.IOException;
229import java.io.InputStream;
230import java.io.PrintWriter;
231import java.nio.charset.StandardCharsets;
232import java.security.NoSuchAlgorithmException;
233import java.security.PublicKey;
234import java.security.cert.CertificateEncodingException;
235import java.security.cert.CertificateException;
236import java.text.SimpleDateFormat;
237import java.util.ArrayList;
238import java.util.Arrays;
239import java.util.Collection;
240import java.util.Collections;
241import java.util.Comparator;
242import java.util.Date;
243import java.util.Iterator;
244import java.util.List;
245import java.util.Map;
246import java.util.Objects;
247import java.util.Set;
248import java.util.concurrent.CountDownLatch;
249import java.util.concurrent.TimeUnit;
250import java.util.concurrent.atomic.AtomicBoolean;
251import java.util.concurrent.atomic.AtomicInteger;
252import java.util.concurrent.atomic.AtomicLong;
253
254/**
255 * Keep track of all those .apks everywhere.
256 *
257 * This is very central to the platform's security; please run the unit
258 * tests whenever making modifications here:
259 *
260mmm frameworks/base/tests/AndroidTests
261adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
262adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
263 *
264 * {@hide}
265 */
266public class PackageManagerService extends IPackageManager.Stub {
267    static final String TAG = "PackageManager";
268    static final boolean DEBUG_SETTINGS = false;
269    static final boolean DEBUG_PREFERRED = false;
270    static final boolean DEBUG_UPGRADE = false;
271    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
272    private static final boolean DEBUG_BACKUP = true;
273    private static final boolean DEBUG_INSTALL = false;
274    private static final boolean DEBUG_REMOVE = false;
275    private static final boolean DEBUG_BROADCASTS = false;
276    private static final boolean DEBUG_SHOW_INFO = false;
277    private static final boolean DEBUG_PACKAGE_INFO = false;
278    private static final boolean DEBUG_INTENT_MATCHING = false;
279    private static final boolean DEBUG_PACKAGE_SCANNING = false;
280    private static final boolean DEBUG_VERIFY = false;
281    private static final boolean DEBUG_DEXOPT = false;
282    private static final boolean DEBUG_ABI_SELECTION = false;
283
284    private static final int RADIO_UID = Process.PHONE_UID;
285    private static final int LOG_UID = Process.LOG_UID;
286    private static final int NFC_UID = Process.NFC_UID;
287    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
288    private static final int SHELL_UID = Process.SHELL_UID;
289
290    // Cap the size of permission trees that 3rd party apps can define
291    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
292
293    // Suffix used during package installation when copying/moving
294    // package apks to install directory.
295    private static final String INSTALL_PACKAGE_SUFFIX = "-";
296
297    static final int SCAN_NO_DEX = 1<<1;
298    static final int SCAN_FORCE_DEX = 1<<2;
299    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
300    static final int SCAN_NEW_INSTALL = 1<<4;
301    static final int SCAN_NO_PATHS = 1<<5;
302    static final int SCAN_UPDATE_TIME = 1<<6;
303    static final int SCAN_DEFER_DEX = 1<<7;
304    static final int SCAN_BOOTING = 1<<8;
305    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
306    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
307    static final int SCAN_REQUIRE_KNOWN = 1<<12;
308    static final int SCAN_MOVE = 1<<13;
309
310    static final int REMOVE_CHATTY = 1<<16;
311
312    private static final int[] EMPTY_INT_ARRAY = new int[0];
313
314    /**
315     * Timeout (in milliseconds) after which the watchdog should declare that
316     * our handler thread is wedged.  The usual default for such things is one
317     * minute but we sometimes do very lengthy I/O operations on this thread,
318     * such as installing multi-gigabyte applications, so ours needs to be longer.
319     */
320    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
321
322    /**
323     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
324     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
325     * settings entry if available, otherwise we use the hardcoded default.  If it's been
326     * more than this long since the last fstrim, we force one during the boot sequence.
327     *
328     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
329     * one gets run at the next available charging+idle time.  This final mandatory
330     * no-fstrim check kicks in only of the other scheduling criteria is never met.
331     */
332    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
333
334    /**
335     * Whether verification is enabled by default.
336     */
337    private static final boolean DEFAULT_VERIFY_ENABLE = true;
338
339    /**
340     * The default maximum time to wait for the verification agent to return in
341     * milliseconds.
342     */
343    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
344
345    /**
346     * The default response for package verification timeout.
347     *
348     * This can be either PackageManager.VERIFICATION_ALLOW or
349     * PackageManager.VERIFICATION_REJECT.
350     */
351    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
352
353    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
354
355    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
356            DEFAULT_CONTAINER_PACKAGE,
357            "com.android.defcontainer.DefaultContainerService");
358
359    private static final String KILL_APP_REASON_GIDS_CHANGED =
360            "permission grant or revoke changed gids";
361
362    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
363            "permissions revoked";
364
365    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
366
367    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
368
369    /** Permission grant: not grant the permission. */
370    private static final int GRANT_DENIED = 1;
371
372    /** Permission grant: grant the permission as an install permission. */
373    private static final int GRANT_INSTALL = 2;
374
375    /** Permission grant: grant the permission as an install permission for a legacy app. */
376    private static final int GRANT_INSTALL_LEGACY = 3;
377
378    /** Permission grant: grant the permission as a runtime one. */
379    private static final int GRANT_RUNTIME = 4;
380
381    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
382    private static final int GRANT_UPGRADE = 5;
383
384    final ServiceThread mHandlerThread;
385
386    final PackageHandler mHandler;
387
388    /**
389     * Messages for {@link #mHandler} that need to wait for system ready before
390     * being dispatched.
391     */
392    private ArrayList<Message> mPostSystemReadyMessages;
393
394    final int mSdkVersion = Build.VERSION.SDK_INT;
395
396    final Context mContext;
397    final boolean mFactoryTest;
398    final boolean mOnlyCore;
399    final boolean mLazyDexOpt;
400    final long mDexOptLRUThresholdInMills;
401    final DisplayMetrics mMetrics;
402    final int mDefParseFlags;
403    final String[] mSeparateProcesses;
404    final boolean mIsUpgrade;
405
406    // This is where all application persistent data goes.
407    final File mAppDataDir;
408
409    // This is where all application persistent data goes for secondary users.
410    final File mUserAppDataDir;
411
412    /** The location for ASEC container files on internal storage. */
413    final String mAsecInternalPath;
414
415    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
416    // LOCK HELD.  Can be called with mInstallLock held.
417    final Installer mInstaller;
418
419    /** Directory where installed third-party apps stored */
420    final File mAppInstallDir;
421
422    /**
423     * Directory to which applications installed internally have their
424     * 32 bit native libraries copied.
425     */
426    private File mAppLib32InstallDir;
427
428    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
429    // apps.
430    final File mDrmAppPrivateInstallDir;
431
432    // ----------------------------------------------------------------
433
434    // Lock for state used when installing and doing other long running
435    // operations.  Methods that must be called with this lock held have
436    // the suffix "LI".
437    final Object mInstallLock = new Object();
438
439    // ----------------------------------------------------------------
440
441    // Keys are String (package name), values are Package.  This also serves
442    // as the lock for the global state.  Methods that must be called with
443    // this lock held have the prefix "LP".
444    final ArrayMap<String, PackageParser.Package> mPackages =
445            new ArrayMap<String, PackageParser.Package>();
446
447    // Tracks available target package names -> overlay package paths.
448    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
449        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
450
451    final Settings mSettings;
452    boolean mRestoredSettings;
453
454    // System configuration read by SystemConfig.
455    final int[] mGlobalGids;
456    final SparseArray<ArraySet<String>> mSystemPermissions;
457    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
458
459    // If mac_permissions.xml was found for seinfo labeling.
460    boolean mFoundPolicyFile;
461
462    // If a recursive restorecon of /data/data/<pkg> is needed.
463    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
464
465    public static final class SharedLibraryEntry {
466        public final String path;
467        public final String apk;
468
469        SharedLibraryEntry(String _path, String _apk) {
470            path = _path;
471            apk = _apk;
472        }
473    }
474
475    // Currently known shared libraries.
476    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
477            new ArrayMap<String, SharedLibraryEntry>();
478
479    // All available activities, for your resolving pleasure.
480    final ActivityIntentResolver mActivities =
481            new ActivityIntentResolver();
482
483    // All available receivers, for your resolving pleasure.
484    final ActivityIntentResolver mReceivers =
485            new ActivityIntentResolver();
486
487    // All available services, for your resolving pleasure.
488    final ServiceIntentResolver mServices = new ServiceIntentResolver();
489
490    // All available providers, for your resolving pleasure.
491    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
492
493    // Mapping from provider base names (first directory in content URI codePath)
494    // to the provider information.
495    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
496            new ArrayMap<String, PackageParser.Provider>();
497
498    // Mapping from instrumentation class names to info about them.
499    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
500            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
501
502    // Mapping from permission names to info about them.
503    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
504            new ArrayMap<String, PackageParser.PermissionGroup>();
505
506    // Packages whose data we have transfered into another package, thus
507    // should no longer exist.
508    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
509
510    // Broadcast actions that are only available to the system.
511    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
512
513    /** List of packages waiting for verification. */
514    final SparseArray<PackageVerificationState> mPendingVerification
515            = new SparseArray<PackageVerificationState>();
516
517    /** Set of packages associated with each app op permission. */
518    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
519
520    final PackageInstallerService mInstallerService;
521
522    private final PackageDexOptimizer mPackageDexOptimizer;
523
524    private AtomicInteger mNextMoveId = new AtomicInteger();
525    private final MoveCallbacks mMoveCallbacks;
526
527    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
528
529    // Cache of users who need badging.
530    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
531
532    /** Token for keys in mPendingVerification. */
533    private int mPendingVerificationToken = 0;
534
535    volatile boolean mSystemReady;
536    volatile boolean mSafeMode;
537    volatile boolean mHasSystemUidErrors;
538
539    ApplicationInfo mAndroidApplication;
540    final ActivityInfo mResolveActivity = new ActivityInfo();
541    final ResolveInfo mResolveInfo = new ResolveInfo();
542    ComponentName mResolveComponentName;
543    PackageParser.Package mPlatformPackage;
544    ComponentName mCustomResolverComponentName;
545
546    boolean mResolverReplaced = false;
547
548    private final ComponentName mIntentFilterVerifierComponent;
549    private int mIntentFilterVerificationToken = 0;
550
551    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
552            = new SparseArray<IntentFilterVerificationState>();
553
554    private interface IntentFilterVerifier<T extends IntentFilter> {
555        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
556                                               T filter, String packageName);
557        void startVerifications(int userId);
558        void receiveVerificationResponse(int verificationId);
559    }
560
561    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
562        private Context mContext;
563        private ComponentName mIntentFilterVerifierComponent;
564        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
565
566        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
567            mContext = context;
568            mIntentFilterVerifierComponent = verifierComponent;
569        }
570
571        private String getDefaultScheme() {
572            return IntentFilter.SCHEME_HTTPS;
573        }
574
575        @Override
576        public void startVerifications(int userId) {
577            // Launch verifications requests
578            int count = mCurrentIntentFilterVerifications.size();
579            for (int n=0; n<count; n++) {
580                int verificationId = mCurrentIntentFilterVerifications.get(n);
581                final IntentFilterVerificationState ivs =
582                        mIntentFilterVerificationStates.get(verificationId);
583
584                String packageName = ivs.getPackageName();
585
586                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
587                final int filterCount = filters.size();
588                ArraySet<String> domainsSet = new ArraySet<>();
589                for (int m=0; m<filterCount; m++) {
590                    PackageParser.ActivityIntentInfo filter = filters.get(m);
591                    domainsSet.addAll(filter.getHostsList());
592                }
593                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
594                synchronized (mPackages) {
595                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
596                            packageName, domainsList) != null) {
597                        scheduleWriteSettingsLocked();
598                    }
599                }
600                sendVerificationRequest(userId, verificationId, ivs);
601            }
602            mCurrentIntentFilterVerifications.clear();
603        }
604
605        private void sendVerificationRequest(int userId, int verificationId,
606                IntentFilterVerificationState ivs) {
607
608            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
609            verificationIntent.putExtra(
610                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
611                    verificationId);
612            verificationIntent.putExtra(
613                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
614                    getDefaultScheme());
615            verificationIntent.putExtra(
616                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
617                    ivs.getHostsString());
618            verificationIntent.putExtra(
619                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
620                    ivs.getPackageName());
621            verificationIntent.setComponent(mIntentFilterVerifierComponent);
622            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
623
624            UserHandle user = new UserHandle(userId);
625            mContext.sendBroadcastAsUser(verificationIntent, user);
626            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
627                    "Sending IntenFilter verification broadcast");
628        }
629
630        public void receiveVerificationResponse(int verificationId) {
631            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
632
633            final boolean verified = ivs.isVerified();
634
635            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
636            final int count = filters.size();
637            for (int n=0; n<count; n++) {
638                PackageParser.ActivityIntentInfo filter = filters.get(n);
639                filter.setVerified(verified);
640
641                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
642                        + " verified with result:" + verified + " and hosts:"
643                        + ivs.getHostsString());
644            }
645
646            mIntentFilterVerificationStates.remove(verificationId);
647
648            final String packageName = ivs.getPackageName();
649            IntentFilterVerificationInfo ivi = null;
650
651            synchronized (mPackages) {
652                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
653            }
654            if (ivi == null) {
655                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
656                        + verificationId + " packageName:" + packageName);
657                return;
658            }
659            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
660                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
661
662            synchronized (mPackages) {
663                if (verified) {
664                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
665                } else {
666                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
667                }
668                scheduleWriteSettingsLocked();
669
670                final int userId = ivs.getUserId();
671                if (userId != UserHandle.USER_ALL) {
672                    final int userStatus =
673                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
674
675                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
676                    boolean needUpdate = false;
677
678                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
679                    // already been set by the User thru the Disambiguation dialog
680                    switch (userStatus) {
681                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
682                            if (verified) {
683                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
684                            } else {
685                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
686                            }
687                            needUpdate = true;
688                            break;
689
690                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
691                            if (verified) {
692                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
693                                needUpdate = true;
694                            }
695                            break;
696
697                        default:
698                            // Nothing to do
699                    }
700
701                    if (needUpdate) {
702                        mSettings.updateIntentFilterVerificationStatusLPw(
703                                packageName, updatedStatus, userId);
704                        scheduleWritePackageRestrictionsLocked(userId);
705                    }
706                }
707            }
708        }
709
710        @Override
711        public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
712                    ActivityIntentInfo filter, String packageName) {
713            if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
714                    filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
715                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
716                        "IntentFilter does not contain HTTP nor HTTPS data scheme");
717                return false;
718            }
719            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
720            if (ivs == null) {
721                ivs = createDomainVerificationState(verifierId, userId, verificationId,
722                        packageName);
723            }
724            if (!hasValidDomains(filter)) {
725                return false;
726            }
727            ivs.addFilter(filter);
728            return true;
729        }
730
731        private IntentFilterVerificationState createDomainVerificationState(int verifierId,
732                int userId, int verificationId, String packageName) {
733            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
734                    verifierId, userId, packageName);
735            ivs.setPendingState();
736            synchronized (mPackages) {
737                mIntentFilterVerificationStates.append(verificationId, ivs);
738                mCurrentIntentFilterVerifications.add(verificationId);
739            }
740            return ivs;
741        }
742    }
743
744    private static boolean hasValidDomains(ActivityIntentInfo filter) {
745        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
746                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
747        if (!hasHTTPorHTTPS) {
748            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
749                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
750            return false;
751        }
752        return true;
753    }
754
755    private IntentFilterVerifier mIntentFilterVerifier;
756
757    // Set of pending broadcasts for aggregating enable/disable of components.
758    static class PendingPackageBroadcasts {
759        // for each user id, a map of <package name -> components within that package>
760        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
761
762        public PendingPackageBroadcasts() {
763            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
764        }
765
766        public ArrayList<String> get(int userId, String packageName) {
767            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
768            return packages.get(packageName);
769        }
770
771        public void put(int userId, String packageName, ArrayList<String> components) {
772            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
773            packages.put(packageName, components);
774        }
775
776        public void remove(int userId, String packageName) {
777            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
778            if (packages != null) {
779                packages.remove(packageName);
780            }
781        }
782
783        public void remove(int userId) {
784            mUidMap.remove(userId);
785        }
786
787        public int userIdCount() {
788            return mUidMap.size();
789        }
790
791        public int userIdAt(int n) {
792            return mUidMap.keyAt(n);
793        }
794
795        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
796            return mUidMap.get(userId);
797        }
798
799        public int size() {
800            // total number of pending broadcast entries across all userIds
801            int num = 0;
802            for (int i = 0; i< mUidMap.size(); i++) {
803                num += mUidMap.valueAt(i).size();
804            }
805            return num;
806        }
807
808        public void clear() {
809            mUidMap.clear();
810        }
811
812        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
813            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
814            if (map == null) {
815                map = new ArrayMap<String, ArrayList<String>>();
816                mUidMap.put(userId, map);
817            }
818            return map;
819        }
820    }
821    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
822
823    // Service Connection to remote media container service to copy
824    // package uri's from external media onto secure containers
825    // or internal storage.
826    private IMediaContainerService mContainerService = null;
827
828    static final int SEND_PENDING_BROADCAST = 1;
829    static final int MCS_BOUND = 3;
830    static final int END_COPY = 4;
831    static final int INIT_COPY = 5;
832    static final int MCS_UNBIND = 6;
833    static final int START_CLEANING_PACKAGE = 7;
834    static final int FIND_INSTALL_LOC = 8;
835    static final int POST_INSTALL = 9;
836    static final int MCS_RECONNECT = 10;
837    static final int MCS_GIVE_UP = 11;
838    static final int UPDATED_MEDIA_STATUS = 12;
839    static final int WRITE_SETTINGS = 13;
840    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
841    static final int PACKAGE_VERIFIED = 15;
842    static final int CHECK_PENDING_VERIFICATION = 16;
843    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
844    static final int INTENT_FILTER_VERIFIED = 18;
845
846    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
847
848    // Delay time in millisecs
849    static final int BROADCAST_DELAY = 10 * 1000;
850
851    static UserManagerService sUserManager;
852
853    // Stores a list of users whose package restrictions file needs to be updated
854    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
855
856    final private DefaultContainerConnection mDefContainerConn =
857            new DefaultContainerConnection();
858    class DefaultContainerConnection implements ServiceConnection {
859        public void onServiceConnected(ComponentName name, IBinder service) {
860            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
861            IMediaContainerService imcs =
862                IMediaContainerService.Stub.asInterface(service);
863            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
864        }
865
866        public void onServiceDisconnected(ComponentName name) {
867            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
868        }
869    };
870
871    // Recordkeeping of restore-after-install operations that are currently in flight
872    // between the Package Manager and the Backup Manager
873    class PostInstallData {
874        public InstallArgs args;
875        public PackageInstalledInfo res;
876
877        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
878            args = _a;
879            res = _r;
880        }
881    };
882    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
883    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
884
885    // backup/restore of preferred activity state
886    private static final String TAG_PREFERRED_BACKUP = "pa";
887
888    private final String mRequiredVerifierPackage;
889
890    private final PackageUsage mPackageUsage = new PackageUsage();
891
892    private class PackageUsage {
893        private static final int WRITE_INTERVAL
894            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
895
896        private final Object mFileLock = new Object();
897        private final AtomicLong mLastWritten = new AtomicLong(0);
898        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
899
900        private boolean mIsHistoricalPackageUsageAvailable = true;
901
902        boolean isHistoricalPackageUsageAvailable() {
903            return mIsHistoricalPackageUsageAvailable;
904        }
905
906        void write(boolean force) {
907            if (force) {
908                writeInternal();
909                return;
910            }
911            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
912                && !DEBUG_DEXOPT) {
913                return;
914            }
915            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
916                new Thread("PackageUsage_DiskWriter") {
917                    @Override
918                    public void run() {
919                        try {
920                            writeInternal();
921                        } finally {
922                            mBackgroundWriteRunning.set(false);
923                        }
924                    }
925                }.start();
926            }
927        }
928
929        private void writeInternal() {
930            synchronized (mPackages) {
931                synchronized (mFileLock) {
932                    AtomicFile file = getFile();
933                    FileOutputStream f = null;
934                    try {
935                        f = file.startWrite();
936                        BufferedOutputStream out = new BufferedOutputStream(f);
937                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
938                        StringBuilder sb = new StringBuilder();
939                        for (PackageParser.Package pkg : mPackages.values()) {
940                            if (pkg.mLastPackageUsageTimeInMills == 0) {
941                                continue;
942                            }
943                            sb.setLength(0);
944                            sb.append(pkg.packageName);
945                            sb.append(' ');
946                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
947                            sb.append('\n');
948                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
949                        }
950                        out.flush();
951                        file.finishWrite(f);
952                    } catch (IOException e) {
953                        if (f != null) {
954                            file.failWrite(f);
955                        }
956                        Log.e(TAG, "Failed to write package usage times", e);
957                    }
958                }
959            }
960            mLastWritten.set(SystemClock.elapsedRealtime());
961        }
962
963        void readLP() {
964            synchronized (mFileLock) {
965                AtomicFile file = getFile();
966                BufferedInputStream in = null;
967                try {
968                    in = new BufferedInputStream(file.openRead());
969                    StringBuffer sb = new StringBuffer();
970                    while (true) {
971                        String packageName = readToken(in, sb, ' ');
972                        if (packageName == null) {
973                            break;
974                        }
975                        String timeInMillisString = readToken(in, sb, '\n');
976                        if (timeInMillisString == null) {
977                            throw new IOException("Failed to find last usage time for package "
978                                                  + packageName);
979                        }
980                        PackageParser.Package pkg = mPackages.get(packageName);
981                        if (pkg == null) {
982                            continue;
983                        }
984                        long timeInMillis;
985                        try {
986                            timeInMillis = Long.parseLong(timeInMillisString.toString());
987                        } catch (NumberFormatException e) {
988                            throw new IOException("Failed to parse " + timeInMillisString
989                                                  + " as a long.", e);
990                        }
991                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
992                    }
993                } catch (FileNotFoundException expected) {
994                    mIsHistoricalPackageUsageAvailable = false;
995                } catch (IOException e) {
996                    Log.w(TAG, "Failed to read package usage times", e);
997                } finally {
998                    IoUtils.closeQuietly(in);
999                }
1000            }
1001            mLastWritten.set(SystemClock.elapsedRealtime());
1002        }
1003
1004        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1005                throws IOException {
1006            sb.setLength(0);
1007            while (true) {
1008                int ch = in.read();
1009                if (ch == -1) {
1010                    if (sb.length() == 0) {
1011                        return null;
1012                    }
1013                    throw new IOException("Unexpected EOF");
1014                }
1015                if (ch == endOfToken) {
1016                    return sb.toString();
1017                }
1018                sb.append((char)ch);
1019            }
1020        }
1021
1022        private AtomicFile getFile() {
1023            File dataDir = Environment.getDataDirectory();
1024            File systemDir = new File(dataDir, "system");
1025            File fname = new File(systemDir, "package-usage.list");
1026            return new AtomicFile(fname);
1027        }
1028    }
1029
1030    class PackageHandler extends Handler {
1031        private boolean mBound = false;
1032        final ArrayList<HandlerParams> mPendingInstalls =
1033            new ArrayList<HandlerParams>();
1034
1035        private boolean connectToService() {
1036            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1037                    " DefaultContainerService");
1038            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1039            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1040            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1041                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1042                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1043                mBound = true;
1044                return true;
1045            }
1046            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1047            return false;
1048        }
1049
1050        private void disconnectService() {
1051            mContainerService = null;
1052            mBound = false;
1053            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1054            mContext.unbindService(mDefContainerConn);
1055            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1056        }
1057
1058        PackageHandler(Looper looper) {
1059            super(looper);
1060        }
1061
1062        public void handleMessage(Message msg) {
1063            try {
1064                doHandleMessage(msg);
1065            } finally {
1066                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1067            }
1068        }
1069
1070        void doHandleMessage(Message msg) {
1071            switch (msg.what) {
1072                case INIT_COPY: {
1073                    HandlerParams params = (HandlerParams) msg.obj;
1074                    int idx = mPendingInstalls.size();
1075                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1076                    // If a bind was already initiated we dont really
1077                    // need to do anything. The pending install
1078                    // will be processed later on.
1079                    if (!mBound) {
1080                        // If this is the only one pending we might
1081                        // have to bind to the service again.
1082                        if (!connectToService()) {
1083                            Slog.e(TAG, "Failed to bind to media container service");
1084                            params.serviceError();
1085                            return;
1086                        } else {
1087                            // Once we bind to the service, the first
1088                            // pending request will be processed.
1089                            mPendingInstalls.add(idx, params);
1090                        }
1091                    } else {
1092                        mPendingInstalls.add(idx, params);
1093                        // Already bound to the service. Just make
1094                        // sure we trigger off processing the first request.
1095                        if (idx == 0) {
1096                            mHandler.sendEmptyMessage(MCS_BOUND);
1097                        }
1098                    }
1099                    break;
1100                }
1101                case MCS_BOUND: {
1102                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1103                    if (msg.obj != null) {
1104                        mContainerService = (IMediaContainerService) msg.obj;
1105                    }
1106                    if (mContainerService == null) {
1107                        // Something seriously wrong. Bail out
1108                        Slog.e(TAG, "Cannot bind to media container service");
1109                        for (HandlerParams params : mPendingInstalls) {
1110                            // Indicate service bind error
1111                            params.serviceError();
1112                        }
1113                        mPendingInstalls.clear();
1114                    } else if (mPendingInstalls.size() > 0) {
1115                        HandlerParams params = mPendingInstalls.get(0);
1116                        if (params != null) {
1117                            if (params.startCopy()) {
1118                                // We are done...  look for more work or to
1119                                // go idle.
1120                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1121                                        "Checking for more work or unbind...");
1122                                // Delete pending install
1123                                if (mPendingInstalls.size() > 0) {
1124                                    mPendingInstalls.remove(0);
1125                                }
1126                                if (mPendingInstalls.size() == 0) {
1127                                    if (mBound) {
1128                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1129                                                "Posting delayed MCS_UNBIND");
1130                                        removeMessages(MCS_UNBIND);
1131                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1132                                        // Unbind after a little delay, to avoid
1133                                        // continual thrashing.
1134                                        sendMessageDelayed(ubmsg, 10000);
1135                                    }
1136                                } else {
1137                                    // There are more pending requests in queue.
1138                                    // Just post MCS_BOUND message to trigger processing
1139                                    // of next pending install.
1140                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1141                                            "Posting MCS_BOUND for next work");
1142                                    mHandler.sendEmptyMessage(MCS_BOUND);
1143                                }
1144                            }
1145                        }
1146                    } else {
1147                        // Should never happen ideally.
1148                        Slog.w(TAG, "Empty queue");
1149                    }
1150                    break;
1151                }
1152                case MCS_RECONNECT: {
1153                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1154                    if (mPendingInstalls.size() > 0) {
1155                        if (mBound) {
1156                            disconnectService();
1157                        }
1158                        if (!connectToService()) {
1159                            Slog.e(TAG, "Failed to bind to media container service");
1160                            for (HandlerParams params : mPendingInstalls) {
1161                                // Indicate service bind error
1162                                params.serviceError();
1163                            }
1164                            mPendingInstalls.clear();
1165                        }
1166                    }
1167                    break;
1168                }
1169                case MCS_UNBIND: {
1170                    // If there is no actual work left, then time to unbind.
1171                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1172
1173                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1174                        if (mBound) {
1175                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1176
1177                            disconnectService();
1178                        }
1179                    } else if (mPendingInstalls.size() > 0) {
1180                        // There are more pending requests in queue.
1181                        // Just post MCS_BOUND message to trigger processing
1182                        // of next pending install.
1183                        mHandler.sendEmptyMessage(MCS_BOUND);
1184                    }
1185
1186                    break;
1187                }
1188                case MCS_GIVE_UP: {
1189                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1190                    mPendingInstalls.remove(0);
1191                    break;
1192                }
1193                case SEND_PENDING_BROADCAST: {
1194                    String packages[];
1195                    ArrayList<String> components[];
1196                    int size = 0;
1197                    int uids[];
1198                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1199                    synchronized (mPackages) {
1200                        if (mPendingBroadcasts == null) {
1201                            return;
1202                        }
1203                        size = mPendingBroadcasts.size();
1204                        if (size <= 0) {
1205                            // Nothing to be done. Just return
1206                            return;
1207                        }
1208                        packages = new String[size];
1209                        components = new ArrayList[size];
1210                        uids = new int[size];
1211                        int i = 0;  // filling out the above arrays
1212
1213                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1214                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1215                            Iterator<Map.Entry<String, ArrayList<String>>> it
1216                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1217                                            .entrySet().iterator();
1218                            while (it.hasNext() && i < size) {
1219                                Map.Entry<String, ArrayList<String>> ent = it.next();
1220                                packages[i] = ent.getKey();
1221                                components[i] = ent.getValue();
1222                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1223                                uids[i] = (ps != null)
1224                                        ? UserHandle.getUid(packageUserId, ps.appId)
1225                                        : -1;
1226                                i++;
1227                            }
1228                        }
1229                        size = i;
1230                        mPendingBroadcasts.clear();
1231                    }
1232                    // Send broadcasts
1233                    for (int i = 0; i < size; i++) {
1234                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1235                    }
1236                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1237                    break;
1238                }
1239                case START_CLEANING_PACKAGE: {
1240                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1241                    final String packageName = (String)msg.obj;
1242                    final int userId = msg.arg1;
1243                    final boolean andCode = msg.arg2 != 0;
1244                    synchronized (mPackages) {
1245                        if (userId == UserHandle.USER_ALL) {
1246                            int[] users = sUserManager.getUserIds();
1247                            for (int user : users) {
1248                                mSettings.addPackageToCleanLPw(
1249                                        new PackageCleanItem(user, packageName, andCode));
1250                            }
1251                        } else {
1252                            mSettings.addPackageToCleanLPw(
1253                                    new PackageCleanItem(userId, packageName, andCode));
1254                        }
1255                    }
1256                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1257                    startCleaningPackages();
1258                } break;
1259                case POST_INSTALL: {
1260                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1261                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1262                    mRunningInstalls.delete(msg.arg1);
1263                    boolean deleteOld = false;
1264
1265                    if (data != null) {
1266                        InstallArgs args = data.args;
1267                        PackageInstalledInfo res = data.res;
1268
1269                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1270                            res.removedInfo.sendBroadcast(false, true, false);
1271                            Bundle extras = new Bundle(1);
1272                            extras.putInt(Intent.EXTRA_UID, res.uid);
1273
1274                            // Now that we successfully installed the package, grant runtime
1275                            // permissions if requested before broadcasting the install.
1276                            if ((args.installFlags
1277                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1278                                grantRequestedRuntimePermissions(res.pkg,
1279                                        args.user.getIdentifier());
1280                            }
1281
1282                            // Determine the set of users who are adding this
1283                            // package for the first time vs. those who are seeing
1284                            // an update.
1285                            int[] firstUsers;
1286                            int[] updateUsers = new int[0];
1287                            if (res.origUsers == null || res.origUsers.length == 0) {
1288                                firstUsers = res.newUsers;
1289                            } else {
1290                                firstUsers = new int[0];
1291                                for (int i=0; i<res.newUsers.length; i++) {
1292                                    int user = res.newUsers[i];
1293                                    boolean isNew = true;
1294                                    for (int j=0; j<res.origUsers.length; j++) {
1295                                        if (res.origUsers[j] == user) {
1296                                            isNew = false;
1297                                            break;
1298                                        }
1299                                    }
1300                                    if (isNew) {
1301                                        int[] newFirst = new int[firstUsers.length+1];
1302                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1303                                                firstUsers.length);
1304                                        newFirst[firstUsers.length] = user;
1305                                        firstUsers = newFirst;
1306                                    } else {
1307                                        int[] newUpdate = new int[updateUsers.length+1];
1308                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1309                                                updateUsers.length);
1310                                        newUpdate[updateUsers.length] = user;
1311                                        updateUsers = newUpdate;
1312                                    }
1313                                }
1314                            }
1315                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1316                                    res.pkg.applicationInfo.packageName,
1317                                    extras, null, null, firstUsers);
1318                            final boolean update = res.removedInfo.removedPackage != null;
1319                            if (update) {
1320                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1321                            }
1322                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1323                                    res.pkg.applicationInfo.packageName,
1324                                    extras, null, null, updateUsers);
1325                            if (update) {
1326                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1327                                        res.pkg.applicationInfo.packageName,
1328                                        extras, null, null, updateUsers);
1329                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1330                                        null, null,
1331                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1332
1333                                // treat asec-hosted packages like removable media on upgrade
1334                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1335                                    if (DEBUG_INSTALL) {
1336                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1337                                                + " is ASEC-hosted -> AVAILABLE");
1338                                    }
1339                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1340                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1341                                    pkgList.add(res.pkg.applicationInfo.packageName);
1342                                    sendResourcesChangedBroadcast(true, true,
1343                                            pkgList,uidArray, null);
1344                                }
1345                            }
1346                            if (res.removedInfo.args != null) {
1347                                // Remove the replaced package's older resources safely now
1348                                deleteOld = true;
1349                            }
1350
1351                            // Log current value of "unknown sources" setting
1352                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1353                                getUnknownSourcesSettings());
1354                        }
1355                        // Force a gc to clear up things
1356                        Runtime.getRuntime().gc();
1357                        // We delete after a gc for applications  on sdcard.
1358                        if (deleteOld) {
1359                            synchronized (mInstallLock) {
1360                                res.removedInfo.args.doPostDeleteLI(true);
1361                            }
1362                        }
1363                        if (args.observer != null) {
1364                            try {
1365                                Bundle extras = extrasForInstallResult(res);
1366                                args.observer.onPackageInstalled(res.name, res.returnCode,
1367                                        res.returnMsg, extras);
1368                            } catch (RemoteException e) {
1369                                Slog.i(TAG, "Observer no longer exists.");
1370                            }
1371                        }
1372                    } else {
1373                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1374                    }
1375                } break;
1376                case UPDATED_MEDIA_STATUS: {
1377                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1378                    boolean reportStatus = msg.arg1 == 1;
1379                    boolean doGc = msg.arg2 == 1;
1380                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1381                    if (doGc) {
1382                        // Force a gc to clear up stale containers.
1383                        Runtime.getRuntime().gc();
1384                    }
1385                    if (msg.obj != null) {
1386                        @SuppressWarnings("unchecked")
1387                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1388                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1389                        // Unload containers
1390                        unloadAllContainers(args);
1391                    }
1392                    if (reportStatus) {
1393                        try {
1394                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1395                            PackageHelper.getMountService().finishMediaUpdate();
1396                        } catch (RemoteException e) {
1397                            Log.e(TAG, "MountService not running?");
1398                        }
1399                    }
1400                } break;
1401                case WRITE_SETTINGS: {
1402                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1403                    synchronized (mPackages) {
1404                        removeMessages(WRITE_SETTINGS);
1405                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1406                        mSettings.writeLPr();
1407                        mDirtyUsers.clear();
1408                    }
1409                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1410                } break;
1411                case WRITE_PACKAGE_RESTRICTIONS: {
1412                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1413                    synchronized (mPackages) {
1414                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1415                        for (int userId : mDirtyUsers) {
1416                            mSettings.writePackageRestrictionsLPr(userId);
1417                        }
1418                        mDirtyUsers.clear();
1419                    }
1420                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1421                } break;
1422                case CHECK_PENDING_VERIFICATION: {
1423                    final int verificationId = msg.arg1;
1424                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1425
1426                    if ((state != null) && !state.timeoutExtended()) {
1427                        final InstallArgs args = state.getInstallArgs();
1428                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1429
1430                        Slog.i(TAG, "Verification timed out for " + originUri);
1431                        mPendingVerification.remove(verificationId);
1432
1433                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1434
1435                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1436                            Slog.i(TAG, "Continuing with installation of " + originUri);
1437                            state.setVerifierResponse(Binder.getCallingUid(),
1438                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1439                            broadcastPackageVerified(verificationId, originUri,
1440                                    PackageManager.VERIFICATION_ALLOW,
1441                                    state.getInstallArgs().getUser());
1442                            try {
1443                                ret = args.copyApk(mContainerService, true);
1444                            } catch (RemoteException e) {
1445                                Slog.e(TAG, "Could not contact the ContainerService");
1446                            }
1447                        } else {
1448                            broadcastPackageVerified(verificationId, originUri,
1449                                    PackageManager.VERIFICATION_REJECT,
1450                                    state.getInstallArgs().getUser());
1451                        }
1452
1453                        processPendingInstall(args, ret);
1454                        mHandler.sendEmptyMessage(MCS_UNBIND);
1455                    }
1456                    break;
1457                }
1458                case PACKAGE_VERIFIED: {
1459                    final int verificationId = msg.arg1;
1460
1461                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1462                    if (state == null) {
1463                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1464                        break;
1465                    }
1466
1467                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1468
1469                    state.setVerifierResponse(response.callerUid, response.code);
1470
1471                    if (state.isVerificationComplete()) {
1472                        mPendingVerification.remove(verificationId);
1473
1474                        final InstallArgs args = state.getInstallArgs();
1475                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1476
1477                        int ret;
1478                        if (state.isInstallAllowed()) {
1479                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1480                            broadcastPackageVerified(verificationId, originUri,
1481                                    response.code, state.getInstallArgs().getUser());
1482                            try {
1483                                ret = args.copyApk(mContainerService, true);
1484                            } catch (RemoteException e) {
1485                                Slog.e(TAG, "Could not contact the ContainerService");
1486                            }
1487                        } else {
1488                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1489                        }
1490
1491                        processPendingInstall(args, ret);
1492
1493                        mHandler.sendEmptyMessage(MCS_UNBIND);
1494                    }
1495
1496                    break;
1497                }
1498                case START_INTENT_FILTER_VERIFICATIONS: {
1499                    int userId = msg.arg1;
1500                    int verifierUid = msg.arg2;
1501                    PackageParser.Package pkg = (PackageParser.Package)msg.obj;
1502
1503                    verifyIntentFiltersIfNeeded(userId, verifierUid, pkg);
1504                    break;
1505                }
1506                case INTENT_FILTER_VERIFIED: {
1507                    final int verificationId = msg.arg1;
1508
1509                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1510                            verificationId);
1511                    if (state == null) {
1512                        Slog.w(TAG, "Invalid IntentFilter verification token "
1513                                + verificationId + " received");
1514                        break;
1515                    }
1516
1517                    final int userId = state.getUserId();
1518
1519                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1520                            "Processing IntentFilter verification with token:"
1521                            + verificationId + " and userId:" + userId);
1522
1523                    final IntentFilterVerificationResponse response =
1524                            (IntentFilterVerificationResponse) msg.obj;
1525
1526                    state.setVerifierResponse(response.callerUid, response.code);
1527
1528                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1529                            "IntentFilter verification with token:" + verificationId
1530                            + " and userId:" + userId
1531                            + " is settings verifier response with response code:"
1532                            + response.code);
1533
1534                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1535                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1536                                + response.getFailedDomainsString());
1537                    }
1538
1539                    if (state.isVerificationComplete()) {
1540                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1541                    } else {
1542                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1543                                "IntentFilter verification with token:" + verificationId
1544                                + " was not said to be complete");
1545                    }
1546
1547                    break;
1548                }
1549            }
1550        }
1551    }
1552
1553    private StorageEventListener mStorageListener = new StorageEventListener() {
1554        @Override
1555        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1556            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1557                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1558                    // TODO: ensure that private directories exist for all active users
1559                    // TODO: remove user data whose serial number doesn't match
1560                    loadPrivatePackages(vol);
1561                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1562                    unloadPrivatePackages(vol);
1563                }
1564            }
1565
1566            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1567                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1568                    updateExternalMediaStatus(true, false);
1569                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1570                    updateExternalMediaStatus(false, false);
1571                }
1572            }
1573        }
1574
1575        @Override
1576        public void onVolumeForgotten(String fsUuid) {
1577            // TODO: remove all packages hosted on this uuid
1578        }
1579    };
1580
1581    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1582        if (userId >= UserHandle.USER_OWNER) {
1583            grantRequestedRuntimePermissionsForUser(pkg, userId);
1584        } else if (userId == UserHandle.USER_ALL) {
1585            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1586                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1587            }
1588        }
1589    }
1590
1591    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1592        SettingBase sb = (SettingBase) pkg.mExtras;
1593        if (sb == null) {
1594            return;
1595        }
1596
1597        PermissionsState permissionsState = sb.getPermissionsState();
1598
1599        for (String permission : pkg.requestedPermissions) {
1600            BasePermission bp = mSettings.mPermissions.get(permission);
1601            if (bp != null && bp.isRuntime()) {
1602                permissionsState.grantRuntimePermission(bp, userId);
1603            }
1604        }
1605    }
1606
1607    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1608        Bundle extras = null;
1609        switch (res.returnCode) {
1610            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1611                extras = new Bundle();
1612                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1613                        res.origPermission);
1614                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1615                        res.origPackage);
1616                break;
1617            }
1618            case PackageManager.INSTALL_SUCCEEDED: {
1619                extras = new Bundle();
1620                extras.putBoolean(Intent.EXTRA_REPLACING,
1621                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1622                break;
1623            }
1624        }
1625        return extras;
1626    }
1627
1628    void scheduleWriteSettingsLocked() {
1629        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1630            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1631        }
1632    }
1633
1634    void scheduleWritePackageRestrictionsLocked(int userId) {
1635        if (!sUserManager.exists(userId)) return;
1636        mDirtyUsers.add(userId);
1637        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1638            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1639        }
1640    }
1641
1642    public static PackageManagerService main(Context context, Installer installer,
1643            boolean factoryTest, boolean onlyCore) {
1644        PackageManagerService m = new PackageManagerService(context, installer,
1645                factoryTest, onlyCore);
1646        ServiceManager.addService("package", m);
1647        return m;
1648    }
1649
1650    static String[] splitString(String str, char sep) {
1651        int count = 1;
1652        int i = 0;
1653        while ((i=str.indexOf(sep, i)) >= 0) {
1654            count++;
1655            i++;
1656        }
1657
1658        String[] res = new String[count];
1659        i=0;
1660        count = 0;
1661        int lastI=0;
1662        while ((i=str.indexOf(sep, i)) >= 0) {
1663            res[count] = str.substring(lastI, i);
1664            count++;
1665            i++;
1666            lastI = i;
1667        }
1668        res[count] = str.substring(lastI, str.length());
1669        return res;
1670    }
1671
1672    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1673        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1674                Context.DISPLAY_SERVICE);
1675        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1676    }
1677
1678    public PackageManagerService(Context context, Installer installer,
1679            boolean factoryTest, boolean onlyCore) {
1680        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1681                SystemClock.uptimeMillis());
1682
1683        if (mSdkVersion <= 0) {
1684            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1685        }
1686
1687        mContext = context;
1688        mFactoryTest = factoryTest;
1689        mOnlyCore = onlyCore;
1690        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1691        mMetrics = new DisplayMetrics();
1692        mSettings = new Settings(mPackages);
1693        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1694                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1695        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1696                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1697        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1698                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1699        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1700                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1701        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1702                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1703        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1704                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1705
1706        // TODO: add a property to control this?
1707        long dexOptLRUThresholdInMinutes;
1708        if (mLazyDexOpt) {
1709            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1710        } else {
1711            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1712        }
1713        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1714
1715        String separateProcesses = SystemProperties.get("debug.separate_processes");
1716        if (separateProcesses != null && separateProcesses.length() > 0) {
1717            if ("*".equals(separateProcesses)) {
1718                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1719                mSeparateProcesses = null;
1720                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1721            } else {
1722                mDefParseFlags = 0;
1723                mSeparateProcesses = separateProcesses.split(",");
1724                Slog.w(TAG, "Running with debug.separate_processes: "
1725                        + separateProcesses);
1726            }
1727        } else {
1728            mDefParseFlags = 0;
1729            mSeparateProcesses = null;
1730        }
1731
1732        mInstaller = installer;
1733        mPackageDexOptimizer = new PackageDexOptimizer(this);
1734        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1735
1736        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1737                FgThread.get().getLooper());
1738
1739        getDefaultDisplayMetrics(context, mMetrics);
1740
1741        SystemConfig systemConfig = SystemConfig.getInstance();
1742        mGlobalGids = systemConfig.getGlobalGids();
1743        mSystemPermissions = systemConfig.getSystemPermissions();
1744        mAvailableFeatures = systemConfig.getAvailableFeatures();
1745
1746        synchronized (mInstallLock) {
1747        // writer
1748        synchronized (mPackages) {
1749            mHandlerThread = new ServiceThread(TAG,
1750                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1751            mHandlerThread.start();
1752            mHandler = new PackageHandler(mHandlerThread.getLooper());
1753            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1754
1755            File dataDir = Environment.getDataDirectory();
1756            mAppDataDir = new File(dataDir, "data");
1757            mAppInstallDir = new File(dataDir, "app");
1758            mAppLib32InstallDir = new File(dataDir, "app-lib");
1759            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1760            mUserAppDataDir = new File(dataDir, "user");
1761            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1762
1763            sUserManager = new UserManagerService(context, this,
1764                    mInstallLock, mPackages);
1765
1766            // Propagate permission configuration in to package manager.
1767            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1768                    = systemConfig.getPermissions();
1769            for (int i=0; i<permConfig.size(); i++) {
1770                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1771                BasePermission bp = mSettings.mPermissions.get(perm.name);
1772                if (bp == null) {
1773                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1774                    mSettings.mPermissions.put(perm.name, bp);
1775                }
1776                if (perm.gids != null) {
1777                    bp.setGids(perm.gids, perm.perUser);
1778                }
1779            }
1780
1781            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1782            for (int i=0; i<libConfig.size(); i++) {
1783                mSharedLibraries.put(libConfig.keyAt(i),
1784                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1785            }
1786
1787            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1788
1789            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1790                    mSdkVersion, mOnlyCore);
1791
1792            String customResolverActivity = Resources.getSystem().getString(
1793                    R.string.config_customResolverActivity);
1794            if (TextUtils.isEmpty(customResolverActivity)) {
1795                customResolverActivity = null;
1796            } else {
1797                mCustomResolverComponentName = ComponentName.unflattenFromString(
1798                        customResolverActivity);
1799            }
1800
1801            long startTime = SystemClock.uptimeMillis();
1802
1803            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1804                    startTime);
1805
1806            // Set flag to monitor and not change apk file paths when
1807            // scanning install directories.
1808            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1809
1810            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1811
1812            /**
1813             * Add everything in the in the boot class path to the
1814             * list of process files because dexopt will have been run
1815             * if necessary during zygote startup.
1816             */
1817            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1818            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1819
1820            if (bootClassPath != null) {
1821                String[] bootClassPathElements = splitString(bootClassPath, ':');
1822                for (String element : bootClassPathElements) {
1823                    alreadyDexOpted.add(element);
1824                }
1825            } else {
1826                Slog.w(TAG, "No BOOTCLASSPATH found!");
1827            }
1828
1829            if (systemServerClassPath != null) {
1830                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1831                for (String element : systemServerClassPathElements) {
1832                    alreadyDexOpted.add(element);
1833                }
1834            } else {
1835                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1836            }
1837
1838            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1839            final String[] dexCodeInstructionSets =
1840                    getDexCodeInstructionSets(
1841                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1842
1843            /**
1844             * Ensure all external libraries have had dexopt run on them.
1845             */
1846            if (mSharedLibraries.size() > 0) {
1847                // NOTE: For now, we're compiling these system "shared libraries"
1848                // (and framework jars) into all available architectures. It's possible
1849                // to compile them only when we come across an app that uses them (there's
1850                // already logic for that in scanPackageLI) but that adds some complexity.
1851                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1852                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1853                        final String lib = libEntry.path;
1854                        if (lib == null) {
1855                            continue;
1856                        }
1857
1858                        try {
1859                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1860                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1861                                alreadyDexOpted.add(lib);
1862                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1863                            }
1864                        } catch (FileNotFoundException e) {
1865                            Slog.w(TAG, "Library not found: " + lib);
1866                        } catch (IOException e) {
1867                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1868                                    + e.getMessage());
1869                        }
1870                    }
1871                }
1872            }
1873
1874            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1875
1876            // Gross hack for now: we know this file doesn't contain any
1877            // code, so don't dexopt it to avoid the resulting log spew.
1878            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1879
1880            // Gross hack for now: we know this file is only part of
1881            // the boot class path for art, so don't dexopt it to
1882            // avoid the resulting log spew.
1883            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1884
1885            /**
1886             * There are a number of commands implemented in Java, which
1887             * we currently need to do the dexopt on so that they can be
1888             * run from a non-root shell.
1889             */
1890            String[] frameworkFiles = frameworkDir.list();
1891            if (frameworkFiles != null) {
1892                // TODO: We could compile these only for the most preferred ABI. We should
1893                // first double check that the dex files for these commands are not referenced
1894                // by other system apps.
1895                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1896                    for (int i=0; i<frameworkFiles.length; i++) {
1897                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1898                        String path = libPath.getPath();
1899                        // Skip the file if we already did it.
1900                        if (alreadyDexOpted.contains(path)) {
1901                            continue;
1902                        }
1903                        // Skip the file if it is not a type we want to dexopt.
1904                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1905                            continue;
1906                        }
1907                        try {
1908                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1909                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1910                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1911                            }
1912                        } catch (FileNotFoundException e) {
1913                            Slog.w(TAG, "Jar not found: " + path);
1914                        } catch (IOException e) {
1915                            Slog.w(TAG, "Exception reading jar: " + path, e);
1916                        }
1917                    }
1918                }
1919            }
1920
1921            // Collect vendor overlay packages.
1922            // (Do this before scanning any apps.)
1923            // For security and version matching reason, only consider
1924            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1925            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1926            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1927                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1928
1929            // Find base frameworks (resource packages without code).
1930            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1931                    | PackageParser.PARSE_IS_SYSTEM_DIR
1932                    | PackageParser.PARSE_IS_PRIVILEGED,
1933                    scanFlags | SCAN_NO_DEX, 0);
1934
1935            // Collected privileged system packages.
1936            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1937            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1938                    | PackageParser.PARSE_IS_SYSTEM_DIR
1939                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1940
1941            // Collect ordinary system packages.
1942            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1943            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1944                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1945
1946            // Collect all vendor packages.
1947            File vendorAppDir = new File("/vendor/app");
1948            try {
1949                vendorAppDir = vendorAppDir.getCanonicalFile();
1950            } catch (IOException e) {
1951                // failed to look up canonical path, continue with original one
1952            }
1953            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1954                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1955
1956            // Collect all OEM packages.
1957            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1958            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1959                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1960
1961            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1962            mInstaller.moveFiles();
1963
1964            // Prune any system packages that no longer exist.
1965            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1966            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1967            if (!mOnlyCore) {
1968                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1969                while (psit.hasNext()) {
1970                    PackageSetting ps = psit.next();
1971
1972                    /*
1973                     * If this is not a system app, it can't be a
1974                     * disable system app.
1975                     */
1976                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1977                        continue;
1978                    }
1979
1980                    /*
1981                     * If the package is scanned, it's not erased.
1982                     */
1983                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1984                    if (scannedPkg != null) {
1985                        /*
1986                         * If the system app is both scanned and in the
1987                         * disabled packages list, then it must have been
1988                         * added via OTA. Remove it from the currently
1989                         * scanned package so the previously user-installed
1990                         * application can be scanned.
1991                         */
1992                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1993                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1994                                    + ps.name + "; removing system app.  Last known codePath="
1995                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1996                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1997                                    + scannedPkg.mVersionCode);
1998                            removePackageLI(ps, true);
1999                            expectingBetter.put(ps.name, ps.codePath);
2000                        }
2001
2002                        continue;
2003                    }
2004
2005                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2006                        psit.remove();
2007                        logCriticalInfo(Log.WARN, "System package " + ps.name
2008                                + " no longer exists; wiping its data");
2009                        removeDataDirsLI(null, ps.name);
2010                    } else {
2011                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2012                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2013                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2014                        }
2015                    }
2016                }
2017            }
2018
2019            //look for any incomplete package installations
2020            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2021            //clean up list
2022            for(int i = 0; i < deletePkgsList.size(); i++) {
2023                //clean up here
2024                cleanupInstallFailedPackage(deletePkgsList.get(i));
2025            }
2026            //delete tmp files
2027            deleteTempPackageFiles();
2028
2029            // Remove any shared userIDs that have no associated packages
2030            mSettings.pruneSharedUsersLPw();
2031
2032            if (!mOnlyCore) {
2033                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2034                        SystemClock.uptimeMillis());
2035                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2036
2037                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2038                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2039
2040                /**
2041                 * Remove disable package settings for any updated system
2042                 * apps that were removed via an OTA. If they're not a
2043                 * previously-updated app, remove them completely.
2044                 * Otherwise, just revoke their system-level permissions.
2045                 */
2046                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2047                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2048                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2049
2050                    String msg;
2051                    if (deletedPkg == null) {
2052                        msg = "Updated system package " + deletedAppName
2053                                + " no longer exists; wiping its data";
2054                        removeDataDirsLI(null, deletedAppName);
2055                    } else {
2056                        msg = "Updated system app + " + deletedAppName
2057                                + " no longer present; removing system privileges for "
2058                                + deletedAppName;
2059
2060                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2061
2062                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2063                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2064                    }
2065                    logCriticalInfo(Log.WARN, msg);
2066                }
2067
2068                /**
2069                 * Make sure all system apps that we expected to appear on
2070                 * the userdata partition actually showed up. If they never
2071                 * appeared, crawl back and revive the system version.
2072                 */
2073                for (int i = 0; i < expectingBetter.size(); i++) {
2074                    final String packageName = expectingBetter.keyAt(i);
2075                    if (!mPackages.containsKey(packageName)) {
2076                        final File scanFile = expectingBetter.valueAt(i);
2077
2078                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2079                                + " but never showed up; reverting to system");
2080
2081                        final int reparseFlags;
2082                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2083                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2084                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2085                                    | PackageParser.PARSE_IS_PRIVILEGED;
2086                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2087                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2088                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2089                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2090                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2091                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2092                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2093                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2094                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2095                        } else {
2096                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2097                            continue;
2098                        }
2099
2100                        mSettings.enableSystemPackageLPw(packageName);
2101
2102                        try {
2103                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2104                        } catch (PackageManagerException e) {
2105                            Slog.e(TAG, "Failed to parse original system package: "
2106                                    + e.getMessage());
2107                        }
2108                    }
2109                }
2110            }
2111
2112            // Now that we know all of the shared libraries, update all clients to have
2113            // the correct library paths.
2114            updateAllSharedLibrariesLPw();
2115
2116            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2117                // NOTE: We ignore potential failures here during a system scan (like
2118                // the rest of the commands above) because there's precious little we
2119                // can do about it. A settings error is reported, though.
2120                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2121                        false /* force dexopt */, false /* defer dexopt */);
2122            }
2123
2124            // Now that we know all the packages we are keeping,
2125            // read and update their last usage times.
2126            mPackageUsage.readLP();
2127
2128            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2129                    SystemClock.uptimeMillis());
2130            Slog.i(TAG, "Time to scan packages: "
2131                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2132                    + " seconds");
2133
2134            // If the platform SDK has changed since the last time we booted,
2135            // we need to re-grant app permission to catch any new ones that
2136            // appear.  This is really a hack, and means that apps can in some
2137            // cases get permissions that the user didn't initially explicitly
2138            // allow...  it would be nice to have some better way to handle
2139            // this situation.
2140            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2141                    != mSdkVersion;
2142            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2143                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2144                    + "; regranting permissions for internal storage");
2145            mSettings.mInternalSdkPlatform = mSdkVersion;
2146
2147            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2148                    | (regrantPermissions
2149                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2150                            : 0));
2151
2152            // If this is the first boot, and it is a normal boot, then
2153            // we need to initialize the default preferred apps.
2154            if (!mRestoredSettings && !onlyCore) {
2155                mSettings.readDefaultPreferredAppsLPw(this, 0);
2156            }
2157
2158            // If this is first boot after an OTA, and a normal boot, then
2159            // we need to clear code cache directories.
2160            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2161            if (mIsUpgrade && !onlyCore) {
2162                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2163                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2164                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2165                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2166                }
2167                mSettings.mFingerprint = Build.FINGERPRINT;
2168            }
2169
2170            primeDomainVerificationsLPw();
2171            checkDefaultBrowser();
2172
2173            // All the changes are done during package scanning.
2174            mSettings.updateInternalDatabaseVersion();
2175
2176            // can downgrade to reader
2177            mSettings.writeLPr();
2178
2179            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2180                    SystemClock.uptimeMillis());
2181
2182            mRequiredVerifierPackage = getRequiredVerifierLPr();
2183
2184            mInstallerService = new PackageInstallerService(context, this);
2185
2186            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2187            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2188                    mIntentFilterVerifierComponent);
2189
2190        } // synchronized (mPackages)
2191        } // synchronized (mInstallLock)
2192
2193        // Now after opening every single application zip, make sure they
2194        // are all flushed.  Not really needed, but keeps things nice and
2195        // tidy.
2196        Runtime.getRuntime().gc();
2197    }
2198
2199    @Override
2200    public boolean isFirstBoot() {
2201        return !mRestoredSettings;
2202    }
2203
2204    @Override
2205    public boolean isOnlyCoreApps() {
2206        return mOnlyCore;
2207    }
2208
2209    @Override
2210    public boolean isUpgrade() {
2211        return mIsUpgrade;
2212    }
2213
2214    private String getRequiredVerifierLPr() {
2215        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2216        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2217                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2218
2219        String requiredVerifier = null;
2220
2221        final int N = receivers.size();
2222        for (int i = 0; i < N; i++) {
2223            final ResolveInfo info = receivers.get(i);
2224
2225            if (info.activityInfo == null) {
2226                continue;
2227            }
2228
2229            final String packageName = info.activityInfo.packageName;
2230
2231            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2232                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2233                continue;
2234            }
2235
2236            if (requiredVerifier != null) {
2237                throw new RuntimeException("There can be only one required verifier");
2238            }
2239
2240            requiredVerifier = packageName;
2241        }
2242
2243        return requiredVerifier;
2244    }
2245
2246    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2247        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2248        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2249                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2250
2251        ComponentName verifierComponentName = null;
2252
2253        int priority = -1000;
2254        final int N = receivers.size();
2255        for (int i = 0; i < N; i++) {
2256            final ResolveInfo info = receivers.get(i);
2257
2258            if (info.activityInfo == null) {
2259                continue;
2260            }
2261
2262            final String packageName = info.activityInfo.packageName;
2263
2264            final PackageSetting ps = mSettings.mPackages.get(packageName);
2265            if (ps == null) {
2266                continue;
2267            }
2268
2269            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2270                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2271                continue;
2272            }
2273
2274            // Select the IntentFilterVerifier with the highest priority
2275            if (priority < info.priority) {
2276                priority = info.priority;
2277                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2278                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2279                        + verifierComponentName + " with priority: " + info.priority);
2280            }
2281        }
2282
2283        return verifierComponentName;
2284    }
2285
2286    private void primeDomainVerificationsLPw() {
2287        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2288        boolean updated = false;
2289        ArraySet<String> allHostsSet = new ArraySet<>();
2290        for (PackageParser.Package pkg : mPackages.values()) {
2291            final String packageName = pkg.packageName;
2292            if (!hasDomainURLs(pkg)) {
2293                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2294                            "package with no domain URLs: " + packageName);
2295                continue;
2296            }
2297            if (!pkg.isSystemApp()) {
2298                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2299                        "No priming domain verifications for a non system package : " +
2300                                packageName);
2301                continue;
2302            }
2303            for (PackageParser.Activity a : pkg.activities) {
2304                for (ActivityIntentInfo filter : a.intents) {
2305                    if (hasValidDomains(filter)) {
2306                        allHostsSet.addAll(filter.getHostsList());
2307                    }
2308                }
2309            }
2310            if (allHostsSet.size() == 0) {
2311                allHostsSet.add("*");
2312            }
2313            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2314            IntentFilterVerificationInfo ivi =
2315                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2316            if (ivi != null) {
2317                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2318                        "Priming domain verifications for package: " + packageName +
2319                        " with hosts:" + ivi.getDomainsString());
2320                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2321                updated = true;
2322            }
2323            else {
2324                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2325                        "No priming domain verifications for package: " + packageName);
2326            }
2327            allHostsSet.clear();
2328        }
2329        if (updated) {
2330            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2331                    "Will need to write primed domain verifications");
2332        }
2333        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2334    }
2335
2336    private void checkDefaultBrowser() {
2337        final int myUserId = UserHandle.myUserId();
2338        final String packageName = getDefaultBrowserPackageName(myUserId);
2339        PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2340        if (info == null) {
2341            Slog.w(TAG, "Clearing default Browser as its package is no more installed: " +
2342                    packageName);
2343            setDefaultBrowserPackageName(null, myUserId);
2344        }
2345    }
2346
2347    @Override
2348    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2349            throws RemoteException {
2350        try {
2351            return super.onTransact(code, data, reply, flags);
2352        } catch (RuntimeException e) {
2353            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2354                Slog.wtf(TAG, "Package Manager Crash", e);
2355            }
2356            throw e;
2357        }
2358    }
2359
2360    void cleanupInstallFailedPackage(PackageSetting ps) {
2361        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2362
2363        removeDataDirsLI(ps.volumeUuid, ps.name);
2364        if (ps.codePath != null) {
2365            if (ps.codePath.isDirectory()) {
2366                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2367            } else {
2368                ps.codePath.delete();
2369            }
2370        }
2371        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2372            if (ps.resourcePath.isDirectory()) {
2373                FileUtils.deleteContents(ps.resourcePath);
2374            }
2375            ps.resourcePath.delete();
2376        }
2377        mSettings.removePackageLPw(ps.name);
2378    }
2379
2380    static int[] appendInts(int[] cur, int[] add) {
2381        if (add == null) return cur;
2382        if (cur == null) return add;
2383        final int N = add.length;
2384        for (int i=0; i<N; i++) {
2385            cur = appendInt(cur, add[i]);
2386        }
2387        return cur;
2388    }
2389
2390    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2391        if (!sUserManager.exists(userId)) return null;
2392        final PackageSetting ps = (PackageSetting) p.mExtras;
2393        if (ps == null) {
2394            return null;
2395        }
2396
2397        final PermissionsState permissionsState = ps.getPermissionsState();
2398
2399        final int[] gids = permissionsState.computeGids(userId);
2400        final Set<String> permissions = permissionsState.getPermissions(userId);
2401        final PackageUserState state = ps.readUserState(userId);
2402
2403        return PackageParser.generatePackageInfo(p, gids, flags,
2404                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2405    }
2406
2407    @Override
2408    public boolean isPackageFrozen(String packageName) {
2409        synchronized (mPackages) {
2410            final PackageSetting ps = mSettings.mPackages.get(packageName);
2411            if (ps != null) {
2412                return ps.frozen;
2413            }
2414        }
2415        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2416        return true;
2417    }
2418
2419    @Override
2420    public boolean isPackageAvailable(String packageName, int userId) {
2421        if (!sUserManager.exists(userId)) return false;
2422        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2423        synchronized (mPackages) {
2424            PackageParser.Package p = mPackages.get(packageName);
2425            if (p != null) {
2426                final PackageSetting ps = (PackageSetting) p.mExtras;
2427                if (ps != null) {
2428                    final PackageUserState state = ps.readUserState(userId);
2429                    if (state != null) {
2430                        return PackageParser.isAvailable(state);
2431                    }
2432                }
2433            }
2434        }
2435        return false;
2436    }
2437
2438    @Override
2439    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2440        if (!sUserManager.exists(userId)) return null;
2441        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2442        // reader
2443        synchronized (mPackages) {
2444            PackageParser.Package p = mPackages.get(packageName);
2445            if (DEBUG_PACKAGE_INFO)
2446                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2447            if (p != null) {
2448                return generatePackageInfo(p, flags, userId);
2449            }
2450            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2451                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2452            }
2453        }
2454        return null;
2455    }
2456
2457    @Override
2458    public String[] currentToCanonicalPackageNames(String[] names) {
2459        String[] out = new String[names.length];
2460        // reader
2461        synchronized (mPackages) {
2462            for (int i=names.length-1; i>=0; i--) {
2463                PackageSetting ps = mSettings.mPackages.get(names[i]);
2464                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2465            }
2466        }
2467        return out;
2468    }
2469
2470    @Override
2471    public String[] canonicalToCurrentPackageNames(String[] names) {
2472        String[] out = new String[names.length];
2473        // reader
2474        synchronized (mPackages) {
2475            for (int i=names.length-1; i>=0; i--) {
2476                String cur = mSettings.mRenamedPackages.get(names[i]);
2477                out[i] = cur != null ? cur : names[i];
2478            }
2479        }
2480        return out;
2481    }
2482
2483    @Override
2484    public int getPackageUid(String packageName, int userId) {
2485        if (!sUserManager.exists(userId)) return -1;
2486        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2487
2488        // reader
2489        synchronized (mPackages) {
2490            PackageParser.Package p = mPackages.get(packageName);
2491            if(p != null) {
2492                return UserHandle.getUid(userId, p.applicationInfo.uid);
2493            }
2494            PackageSetting ps = mSettings.mPackages.get(packageName);
2495            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2496                return -1;
2497            }
2498            p = ps.pkg;
2499            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2500        }
2501    }
2502
2503    @Override
2504    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2505        if (!sUserManager.exists(userId)) {
2506            return null;
2507        }
2508
2509        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2510                "getPackageGids");
2511
2512        // reader
2513        synchronized (mPackages) {
2514            PackageParser.Package p = mPackages.get(packageName);
2515            if (DEBUG_PACKAGE_INFO) {
2516                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2517            }
2518            if (p != null) {
2519                PackageSetting ps = (PackageSetting) p.mExtras;
2520                return ps.getPermissionsState().computeGids(userId);
2521            }
2522        }
2523
2524        return null;
2525    }
2526
2527    static PermissionInfo generatePermissionInfo(
2528            BasePermission bp, int flags) {
2529        if (bp.perm != null) {
2530            return PackageParser.generatePermissionInfo(bp.perm, flags);
2531        }
2532        PermissionInfo pi = new PermissionInfo();
2533        pi.name = bp.name;
2534        pi.packageName = bp.sourcePackage;
2535        pi.nonLocalizedLabel = bp.name;
2536        pi.protectionLevel = bp.protectionLevel;
2537        return pi;
2538    }
2539
2540    @Override
2541    public PermissionInfo getPermissionInfo(String name, int flags) {
2542        // reader
2543        synchronized (mPackages) {
2544            final BasePermission p = mSettings.mPermissions.get(name);
2545            if (p != null) {
2546                return generatePermissionInfo(p, flags);
2547            }
2548            return null;
2549        }
2550    }
2551
2552    @Override
2553    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2554        // reader
2555        synchronized (mPackages) {
2556            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2557            for (BasePermission p : mSettings.mPermissions.values()) {
2558                if (group == null) {
2559                    if (p.perm == null || p.perm.info.group == null) {
2560                        out.add(generatePermissionInfo(p, flags));
2561                    }
2562                } else {
2563                    if (p.perm != null && group.equals(p.perm.info.group)) {
2564                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2565                    }
2566                }
2567            }
2568
2569            if (out.size() > 0) {
2570                return out;
2571            }
2572            return mPermissionGroups.containsKey(group) ? out : null;
2573        }
2574    }
2575
2576    @Override
2577    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2578        // reader
2579        synchronized (mPackages) {
2580            return PackageParser.generatePermissionGroupInfo(
2581                    mPermissionGroups.get(name), flags);
2582        }
2583    }
2584
2585    @Override
2586    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2587        // reader
2588        synchronized (mPackages) {
2589            final int N = mPermissionGroups.size();
2590            ArrayList<PermissionGroupInfo> out
2591                    = new ArrayList<PermissionGroupInfo>(N);
2592            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2593                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2594            }
2595            return out;
2596        }
2597    }
2598
2599    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2600            int userId) {
2601        if (!sUserManager.exists(userId)) return null;
2602        PackageSetting ps = mSettings.mPackages.get(packageName);
2603        if (ps != null) {
2604            if (ps.pkg == null) {
2605                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2606                        flags, userId);
2607                if (pInfo != null) {
2608                    return pInfo.applicationInfo;
2609                }
2610                return null;
2611            }
2612            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2613                    ps.readUserState(userId), userId);
2614        }
2615        return null;
2616    }
2617
2618    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2619            int userId) {
2620        if (!sUserManager.exists(userId)) return null;
2621        PackageSetting ps = mSettings.mPackages.get(packageName);
2622        if (ps != null) {
2623            PackageParser.Package pkg = ps.pkg;
2624            if (pkg == null) {
2625                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2626                    return null;
2627                }
2628                // Only data remains, so we aren't worried about code paths
2629                pkg = new PackageParser.Package(packageName);
2630                pkg.applicationInfo.packageName = packageName;
2631                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2632                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2633                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2634                        packageName, userId).getAbsolutePath();
2635                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2636                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2637            }
2638            return generatePackageInfo(pkg, flags, userId);
2639        }
2640        return null;
2641    }
2642
2643    @Override
2644    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2645        if (!sUserManager.exists(userId)) return null;
2646        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2647        // writer
2648        synchronized (mPackages) {
2649            PackageParser.Package p = mPackages.get(packageName);
2650            if (DEBUG_PACKAGE_INFO) Log.v(
2651                    TAG, "getApplicationInfo " + packageName
2652                    + ": " + p);
2653            if (p != null) {
2654                PackageSetting ps = mSettings.mPackages.get(packageName);
2655                if (ps == null) return null;
2656                // Note: isEnabledLP() does not apply here - always return info
2657                return PackageParser.generateApplicationInfo(
2658                        p, flags, ps.readUserState(userId), userId);
2659            }
2660            if ("android".equals(packageName)||"system".equals(packageName)) {
2661                return mAndroidApplication;
2662            }
2663            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2664                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2665            }
2666        }
2667        return null;
2668    }
2669
2670    @Override
2671    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2672            final IPackageDataObserver observer) {
2673        mContext.enforceCallingOrSelfPermission(
2674                android.Manifest.permission.CLEAR_APP_CACHE, null);
2675        // Queue up an async operation since clearing cache may take a little while.
2676        mHandler.post(new Runnable() {
2677            public void run() {
2678                mHandler.removeCallbacks(this);
2679                int retCode = -1;
2680                synchronized (mInstallLock) {
2681                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2682                    if (retCode < 0) {
2683                        Slog.w(TAG, "Couldn't clear application caches");
2684                    }
2685                }
2686                if (observer != null) {
2687                    try {
2688                        observer.onRemoveCompleted(null, (retCode >= 0));
2689                    } catch (RemoteException e) {
2690                        Slog.w(TAG, "RemoveException when invoking call back");
2691                    }
2692                }
2693            }
2694        });
2695    }
2696
2697    @Override
2698    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2699            final IntentSender pi) {
2700        mContext.enforceCallingOrSelfPermission(
2701                android.Manifest.permission.CLEAR_APP_CACHE, null);
2702        // Queue up an async operation since clearing cache may take a little while.
2703        mHandler.post(new Runnable() {
2704            public void run() {
2705                mHandler.removeCallbacks(this);
2706                int retCode = -1;
2707                synchronized (mInstallLock) {
2708                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2709                    if (retCode < 0) {
2710                        Slog.w(TAG, "Couldn't clear application caches");
2711                    }
2712                }
2713                if(pi != null) {
2714                    try {
2715                        // Callback via pending intent
2716                        int code = (retCode >= 0) ? 1 : 0;
2717                        pi.sendIntent(null, code, null,
2718                                null, null);
2719                    } catch (SendIntentException e1) {
2720                        Slog.i(TAG, "Failed to send pending intent");
2721                    }
2722                }
2723            }
2724        });
2725    }
2726
2727    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2728        synchronized (mInstallLock) {
2729            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2730                throw new IOException("Failed to free enough space");
2731            }
2732        }
2733    }
2734
2735    @Override
2736    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2737        if (!sUserManager.exists(userId)) return null;
2738        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2739        synchronized (mPackages) {
2740            PackageParser.Activity a = mActivities.mActivities.get(component);
2741
2742            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2743            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2744                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2745                if (ps == null) return null;
2746                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2747                        userId);
2748            }
2749            if (mResolveComponentName.equals(component)) {
2750                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2751                        new PackageUserState(), userId);
2752            }
2753        }
2754        return null;
2755    }
2756
2757    @Override
2758    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2759            String resolvedType) {
2760        synchronized (mPackages) {
2761            PackageParser.Activity a = mActivities.mActivities.get(component);
2762            if (a == null) {
2763                return false;
2764            }
2765            for (int i=0; i<a.intents.size(); i++) {
2766                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2767                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2768                    return true;
2769                }
2770            }
2771            return false;
2772        }
2773    }
2774
2775    @Override
2776    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2777        if (!sUserManager.exists(userId)) return null;
2778        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2779        synchronized (mPackages) {
2780            PackageParser.Activity a = mReceivers.mActivities.get(component);
2781            if (DEBUG_PACKAGE_INFO) Log.v(
2782                TAG, "getReceiverInfo " + component + ": " + a);
2783            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2784                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2785                if (ps == null) return null;
2786                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2787                        userId);
2788            }
2789        }
2790        return null;
2791    }
2792
2793    @Override
2794    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2795        if (!sUserManager.exists(userId)) return null;
2796        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2797        synchronized (mPackages) {
2798            PackageParser.Service s = mServices.mServices.get(component);
2799            if (DEBUG_PACKAGE_INFO) Log.v(
2800                TAG, "getServiceInfo " + component + ": " + s);
2801            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2802                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2803                if (ps == null) return null;
2804                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2805                        userId);
2806            }
2807        }
2808        return null;
2809    }
2810
2811    @Override
2812    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2813        if (!sUserManager.exists(userId)) return null;
2814        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2815        synchronized (mPackages) {
2816            PackageParser.Provider p = mProviders.mProviders.get(component);
2817            if (DEBUG_PACKAGE_INFO) Log.v(
2818                TAG, "getProviderInfo " + component + ": " + p);
2819            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2820                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2821                if (ps == null) return null;
2822                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2823                        userId);
2824            }
2825        }
2826        return null;
2827    }
2828
2829    @Override
2830    public String[] getSystemSharedLibraryNames() {
2831        Set<String> libSet;
2832        synchronized (mPackages) {
2833            libSet = mSharedLibraries.keySet();
2834            int size = libSet.size();
2835            if (size > 0) {
2836                String[] libs = new String[size];
2837                libSet.toArray(libs);
2838                return libs;
2839            }
2840        }
2841        return null;
2842    }
2843
2844    /**
2845     * @hide
2846     */
2847    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2848        synchronized (mPackages) {
2849            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2850            if (lib != null && lib.apk != null) {
2851                return mPackages.get(lib.apk);
2852            }
2853        }
2854        return null;
2855    }
2856
2857    @Override
2858    public FeatureInfo[] getSystemAvailableFeatures() {
2859        Collection<FeatureInfo> featSet;
2860        synchronized (mPackages) {
2861            featSet = mAvailableFeatures.values();
2862            int size = featSet.size();
2863            if (size > 0) {
2864                FeatureInfo[] features = new FeatureInfo[size+1];
2865                featSet.toArray(features);
2866                FeatureInfo fi = new FeatureInfo();
2867                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2868                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2869                features[size] = fi;
2870                return features;
2871            }
2872        }
2873        return null;
2874    }
2875
2876    @Override
2877    public boolean hasSystemFeature(String name) {
2878        synchronized (mPackages) {
2879            return mAvailableFeatures.containsKey(name);
2880        }
2881    }
2882
2883    private void checkValidCaller(int uid, int userId) {
2884        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2885            return;
2886
2887        throw new SecurityException("Caller uid=" + uid
2888                + " is not privileged to communicate with user=" + userId);
2889    }
2890
2891    @Override
2892    public int checkPermission(String permName, String pkgName, int userId) {
2893        if (!sUserManager.exists(userId)) {
2894            return PackageManager.PERMISSION_DENIED;
2895        }
2896
2897        synchronized (mPackages) {
2898            final PackageParser.Package p = mPackages.get(pkgName);
2899            if (p != null && p.mExtras != null) {
2900                final PackageSetting ps = (PackageSetting) p.mExtras;
2901                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2902                    return PackageManager.PERMISSION_GRANTED;
2903                }
2904            }
2905        }
2906
2907        return PackageManager.PERMISSION_DENIED;
2908    }
2909
2910    @Override
2911    public int checkUidPermission(String permName, int uid) {
2912        final int userId = UserHandle.getUserId(uid);
2913
2914        if (!sUserManager.exists(userId)) {
2915            return PackageManager.PERMISSION_DENIED;
2916        }
2917
2918        synchronized (mPackages) {
2919            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2920            if (obj != null) {
2921                final SettingBase ps = (SettingBase) obj;
2922                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2923                    return PackageManager.PERMISSION_GRANTED;
2924                }
2925            } else {
2926                ArraySet<String> perms = mSystemPermissions.get(uid);
2927                if (perms != null && perms.contains(permName)) {
2928                    return PackageManager.PERMISSION_GRANTED;
2929                }
2930            }
2931        }
2932
2933        return PackageManager.PERMISSION_DENIED;
2934    }
2935
2936    /**
2937     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2938     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2939     * @param checkShell TODO(yamasani):
2940     * @param message the message to log on security exception
2941     */
2942    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2943            boolean checkShell, String message) {
2944        if (userId < 0) {
2945            throw new IllegalArgumentException("Invalid userId " + userId);
2946        }
2947        if (checkShell) {
2948            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2949        }
2950        if (userId == UserHandle.getUserId(callingUid)) return;
2951        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2952            if (requireFullPermission) {
2953                mContext.enforceCallingOrSelfPermission(
2954                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2955            } else {
2956                try {
2957                    mContext.enforceCallingOrSelfPermission(
2958                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2959                } catch (SecurityException se) {
2960                    mContext.enforceCallingOrSelfPermission(
2961                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2962                }
2963            }
2964        }
2965    }
2966
2967    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2968        if (callingUid == Process.SHELL_UID) {
2969            if (userHandle >= 0
2970                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2971                throw new SecurityException("Shell does not have permission to access user "
2972                        + userHandle);
2973            } else if (userHandle < 0) {
2974                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2975                        + Debug.getCallers(3));
2976            }
2977        }
2978    }
2979
2980    private BasePermission findPermissionTreeLP(String permName) {
2981        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2982            if (permName.startsWith(bp.name) &&
2983                    permName.length() > bp.name.length() &&
2984                    permName.charAt(bp.name.length()) == '.') {
2985                return bp;
2986            }
2987        }
2988        return null;
2989    }
2990
2991    private BasePermission checkPermissionTreeLP(String permName) {
2992        if (permName != null) {
2993            BasePermission bp = findPermissionTreeLP(permName);
2994            if (bp != null) {
2995                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2996                    return bp;
2997                }
2998                throw new SecurityException("Calling uid "
2999                        + Binder.getCallingUid()
3000                        + " is not allowed to add to permission tree "
3001                        + bp.name + " owned by uid " + bp.uid);
3002            }
3003        }
3004        throw new SecurityException("No permission tree found for " + permName);
3005    }
3006
3007    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3008        if (s1 == null) {
3009            return s2 == null;
3010        }
3011        if (s2 == null) {
3012            return false;
3013        }
3014        if (s1.getClass() != s2.getClass()) {
3015            return false;
3016        }
3017        return s1.equals(s2);
3018    }
3019
3020    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3021        if (pi1.icon != pi2.icon) return false;
3022        if (pi1.logo != pi2.logo) return false;
3023        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3024        if (!compareStrings(pi1.name, pi2.name)) return false;
3025        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3026        // We'll take care of setting this one.
3027        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3028        // These are not currently stored in settings.
3029        //if (!compareStrings(pi1.group, pi2.group)) return false;
3030        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3031        //if (pi1.labelRes != pi2.labelRes) return false;
3032        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3033        return true;
3034    }
3035
3036    int permissionInfoFootprint(PermissionInfo info) {
3037        int size = info.name.length();
3038        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3039        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3040        return size;
3041    }
3042
3043    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3044        int size = 0;
3045        for (BasePermission perm : mSettings.mPermissions.values()) {
3046            if (perm.uid == tree.uid) {
3047                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3048            }
3049        }
3050        return size;
3051    }
3052
3053    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3054        // We calculate the max size of permissions defined by this uid and throw
3055        // if that plus the size of 'info' would exceed our stated maximum.
3056        if (tree.uid != Process.SYSTEM_UID) {
3057            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3058            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3059                throw new SecurityException("Permission tree size cap exceeded");
3060            }
3061        }
3062    }
3063
3064    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3065        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3066            throw new SecurityException("Label must be specified in permission");
3067        }
3068        BasePermission tree = checkPermissionTreeLP(info.name);
3069        BasePermission bp = mSettings.mPermissions.get(info.name);
3070        boolean added = bp == null;
3071        boolean changed = true;
3072        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3073        if (added) {
3074            enforcePermissionCapLocked(info, tree);
3075            bp = new BasePermission(info.name, tree.sourcePackage,
3076                    BasePermission.TYPE_DYNAMIC);
3077        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3078            throw new SecurityException(
3079                    "Not allowed to modify non-dynamic permission "
3080                    + info.name);
3081        } else {
3082            if (bp.protectionLevel == fixedLevel
3083                    && bp.perm.owner.equals(tree.perm.owner)
3084                    && bp.uid == tree.uid
3085                    && comparePermissionInfos(bp.perm.info, info)) {
3086                changed = false;
3087            }
3088        }
3089        bp.protectionLevel = fixedLevel;
3090        info = new PermissionInfo(info);
3091        info.protectionLevel = fixedLevel;
3092        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3093        bp.perm.info.packageName = tree.perm.info.packageName;
3094        bp.uid = tree.uid;
3095        if (added) {
3096            mSettings.mPermissions.put(info.name, bp);
3097        }
3098        if (changed) {
3099            if (!async) {
3100                mSettings.writeLPr();
3101            } else {
3102                scheduleWriteSettingsLocked();
3103            }
3104        }
3105        return added;
3106    }
3107
3108    @Override
3109    public boolean addPermission(PermissionInfo info) {
3110        synchronized (mPackages) {
3111            return addPermissionLocked(info, false);
3112        }
3113    }
3114
3115    @Override
3116    public boolean addPermissionAsync(PermissionInfo info) {
3117        synchronized (mPackages) {
3118            return addPermissionLocked(info, true);
3119        }
3120    }
3121
3122    @Override
3123    public void removePermission(String name) {
3124        synchronized (mPackages) {
3125            checkPermissionTreeLP(name);
3126            BasePermission bp = mSettings.mPermissions.get(name);
3127            if (bp != null) {
3128                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3129                    throw new SecurityException(
3130                            "Not allowed to modify non-dynamic permission "
3131                            + name);
3132                }
3133                mSettings.mPermissions.remove(name);
3134                mSettings.writeLPr();
3135            }
3136        }
3137    }
3138
3139    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3140            BasePermission bp) {
3141        int index = pkg.requestedPermissions.indexOf(bp.name);
3142        if (index == -1) {
3143            throw new SecurityException("Package " + pkg.packageName
3144                    + " has not requested permission " + bp.name);
3145        }
3146        if (!bp.isRuntime()) {
3147            throw new SecurityException("Permission " + bp.name
3148                    + " is not a changeable permission type");
3149        }
3150    }
3151
3152    @Override
3153    public void grantRuntimePermission(String packageName, String name, int userId) {
3154        if (!sUserManager.exists(userId)) {
3155            Log.e(TAG, "No such user:" + userId);
3156            return;
3157        }
3158
3159        mContext.enforceCallingOrSelfPermission(
3160                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3161                "grantRuntimePermission");
3162
3163        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3164                "grantRuntimePermission");
3165
3166        boolean gidsChanged = false;
3167        final SettingBase sb;
3168
3169        synchronized (mPackages) {
3170            final PackageParser.Package pkg = mPackages.get(packageName);
3171            if (pkg == null) {
3172                throw new IllegalArgumentException("Unknown package: " + packageName);
3173            }
3174
3175            final BasePermission bp = mSettings.mPermissions.get(name);
3176            if (bp == null) {
3177                throw new IllegalArgumentException("Unknown permission: " + name);
3178            }
3179
3180            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3181
3182            sb = (SettingBase) pkg.mExtras;
3183            if (sb == null) {
3184                throw new IllegalArgumentException("Unknown package: " + packageName);
3185            }
3186
3187            final PermissionsState permissionsState = sb.getPermissionsState();
3188
3189            final int flags = permissionsState.getPermissionFlags(name, userId);
3190            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3191                throw new SecurityException("Cannot grant system fixed permission: "
3192                        + name + " for package: " + packageName);
3193            }
3194
3195            final int result = permissionsState.grantRuntimePermission(bp, userId);
3196            switch (result) {
3197                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3198                    return;
3199                }
3200
3201                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3202                    gidsChanged = true;
3203                } break;
3204            }
3205
3206            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3207
3208            // Not critical if that is lost - app has to request again.
3209            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3210        }
3211
3212        if (gidsChanged) {
3213            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3214        }
3215    }
3216
3217    @Override
3218    public void revokeRuntimePermission(String packageName, String name, int userId) {
3219        if (!sUserManager.exists(userId)) {
3220            Log.e(TAG, "No such user:" + userId);
3221            return;
3222        }
3223
3224        mContext.enforceCallingOrSelfPermission(
3225                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3226                "revokeRuntimePermission");
3227
3228        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3229                "revokeRuntimePermission");
3230
3231        final SettingBase sb;
3232
3233        synchronized (mPackages) {
3234            final PackageParser.Package pkg = mPackages.get(packageName);
3235            if (pkg == null) {
3236                throw new IllegalArgumentException("Unknown package: " + packageName);
3237            }
3238
3239            final BasePermission bp = mSettings.mPermissions.get(name);
3240            if (bp == null) {
3241                throw new IllegalArgumentException("Unknown permission: " + name);
3242            }
3243
3244            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3245
3246            sb = (SettingBase) pkg.mExtras;
3247            if (sb == null) {
3248                throw new IllegalArgumentException("Unknown package: " + packageName);
3249            }
3250
3251            final PermissionsState permissionsState = sb.getPermissionsState();
3252
3253            final int flags = permissionsState.getPermissionFlags(name, userId);
3254            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3255                throw new SecurityException("Cannot revoke system fixed permission: "
3256                        + name + " for package: " + packageName);
3257            }
3258
3259            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3260                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3261                return;
3262            }
3263
3264            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3265
3266            // Critical, after this call app should never have the permission.
3267            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3268        }
3269
3270        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3271    }
3272
3273    @Override
3274    public int getPermissionFlags(String name, String packageName, int userId) {
3275        if (!sUserManager.exists(userId)) {
3276            return 0;
3277        }
3278
3279        mContext.enforceCallingOrSelfPermission(
3280                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3281                "getPermissionFlags");
3282
3283        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3284                "getPermissionFlags");
3285
3286        synchronized (mPackages) {
3287            final PackageParser.Package pkg = mPackages.get(packageName);
3288            if (pkg == null) {
3289                throw new IllegalArgumentException("Unknown package: " + packageName);
3290            }
3291
3292            final BasePermission bp = mSettings.mPermissions.get(name);
3293            if (bp == null) {
3294                throw new IllegalArgumentException("Unknown permission: " + name);
3295            }
3296
3297            SettingBase sb = (SettingBase) pkg.mExtras;
3298            if (sb == null) {
3299                throw new IllegalArgumentException("Unknown package: " + packageName);
3300            }
3301
3302            PermissionsState permissionsState = sb.getPermissionsState();
3303            return permissionsState.getPermissionFlags(name, userId);
3304        }
3305    }
3306
3307    @Override
3308    public void updatePermissionFlags(String name, String packageName, int flagMask,
3309            int flagValues, int userId) {
3310        if (!sUserManager.exists(userId)) {
3311            return;
3312        }
3313
3314        mContext.enforceCallingOrSelfPermission(
3315                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3316                "updatePermissionFlags");
3317
3318        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3319                "updatePermissionFlags");
3320
3321        // Only the system can change policy flags.
3322        if (getCallingUid() != Process.SYSTEM_UID) {
3323            flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3324            flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3325        }
3326
3327        // Only the package manager can change system flags.
3328        flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3329        flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3330
3331        synchronized (mPackages) {
3332            final PackageParser.Package pkg = mPackages.get(packageName);
3333            if (pkg == null) {
3334                throw new IllegalArgumentException("Unknown package: " + packageName);
3335            }
3336
3337            final BasePermission bp = mSettings.mPermissions.get(name);
3338            if (bp == null) {
3339                throw new IllegalArgumentException("Unknown permission: " + name);
3340            }
3341
3342            SettingBase sb = (SettingBase) pkg.mExtras;
3343            if (sb == null) {
3344                throw new IllegalArgumentException("Unknown package: " + packageName);
3345            }
3346
3347            PermissionsState permissionsState = sb.getPermissionsState();
3348
3349            // Only the package manager can change flags for system component permissions.
3350            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3351            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3352                return;
3353            }
3354
3355            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3356                // Install and runtime permissions are stored in different places,
3357                // so figure out what permission changed and persist the change.
3358                if (permissionsState.getInstallPermissionState(name) != null) {
3359                    scheduleWriteSettingsLocked();
3360                } else if (permissionsState.getRuntimePermissionState(name, userId) != null) {
3361                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3362                }
3363            }
3364        }
3365    }
3366
3367    @Override
3368    public boolean shouldShowRequestPermissionRationale(String permissionName,
3369            String packageName, int userId) {
3370        if (UserHandle.getCallingUserId() != userId) {
3371            mContext.enforceCallingPermission(
3372                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3373                    "canShowRequestPermissionRationale for user " + userId);
3374        }
3375
3376        final int uid = getPackageUid(packageName, userId);
3377        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3378            return false;
3379        }
3380
3381        if (checkPermission(permissionName, packageName, userId)
3382                == PackageManager.PERMISSION_GRANTED) {
3383            return false;
3384        }
3385
3386        final int flags;
3387
3388        final long identity = Binder.clearCallingIdentity();
3389        try {
3390            flags = getPermissionFlags(permissionName,
3391                    packageName, userId);
3392        } finally {
3393            Binder.restoreCallingIdentity(identity);
3394        }
3395
3396        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3397                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3398                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3399
3400        if ((flags & fixedFlags) != 0) {
3401            return false;
3402        }
3403
3404        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3405    }
3406
3407    @Override
3408    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3409        mContext.enforceCallingOrSelfPermission(
3410                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3411                "addOnPermissionsChangeListener");
3412
3413        synchronized (mPackages) {
3414            mOnPermissionChangeListeners.addListenerLocked(listener);
3415        }
3416    }
3417
3418    @Override
3419    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3420        synchronized (mPackages) {
3421            mOnPermissionChangeListeners.removeListenerLocked(listener);
3422        }
3423    }
3424
3425    @Override
3426    public boolean isProtectedBroadcast(String actionName) {
3427        synchronized (mPackages) {
3428            return mProtectedBroadcasts.contains(actionName);
3429        }
3430    }
3431
3432    @Override
3433    public int checkSignatures(String pkg1, String pkg2) {
3434        synchronized (mPackages) {
3435            final PackageParser.Package p1 = mPackages.get(pkg1);
3436            final PackageParser.Package p2 = mPackages.get(pkg2);
3437            if (p1 == null || p1.mExtras == null
3438                    || p2 == null || p2.mExtras == null) {
3439                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3440            }
3441            return compareSignatures(p1.mSignatures, p2.mSignatures);
3442        }
3443    }
3444
3445    @Override
3446    public int checkUidSignatures(int uid1, int uid2) {
3447        // Map to base uids.
3448        uid1 = UserHandle.getAppId(uid1);
3449        uid2 = UserHandle.getAppId(uid2);
3450        // reader
3451        synchronized (mPackages) {
3452            Signature[] s1;
3453            Signature[] s2;
3454            Object obj = mSettings.getUserIdLPr(uid1);
3455            if (obj != null) {
3456                if (obj instanceof SharedUserSetting) {
3457                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3458                } else if (obj instanceof PackageSetting) {
3459                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3460                } else {
3461                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3462                }
3463            } else {
3464                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3465            }
3466            obj = mSettings.getUserIdLPr(uid2);
3467            if (obj != null) {
3468                if (obj instanceof SharedUserSetting) {
3469                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3470                } else if (obj instanceof PackageSetting) {
3471                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3472                } else {
3473                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3474                }
3475            } else {
3476                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3477            }
3478            return compareSignatures(s1, s2);
3479        }
3480    }
3481
3482    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3483        final long identity = Binder.clearCallingIdentity();
3484        try {
3485            if (sb instanceof SharedUserSetting) {
3486                SharedUserSetting sus = (SharedUserSetting) sb;
3487                final int packageCount = sus.packages.size();
3488                for (int i = 0; i < packageCount; i++) {
3489                    PackageSetting susPs = sus.packages.valueAt(i);
3490                    if (userId == UserHandle.USER_ALL) {
3491                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3492                    } else {
3493                        final int uid = UserHandle.getUid(userId, susPs.appId);
3494                        killUid(uid, reason);
3495                    }
3496                }
3497            } else if (sb instanceof PackageSetting) {
3498                PackageSetting ps = (PackageSetting) sb;
3499                if (userId == UserHandle.USER_ALL) {
3500                    killApplication(ps.pkg.packageName, ps.appId, reason);
3501                } else {
3502                    final int uid = UserHandle.getUid(userId, ps.appId);
3503                    killUid(uid, reason);
3504                }
3505            }
3506        } finally {
3507            Binder.restoreCallingIdentity(identity);
3508        }
3509    }
3510
3511    private static void killUid(int uid, String reason) {
3512        IActivityManager am = ActivityManagerNative.getDefault();
3513        if (am != null) {
3514            try {
3515                am.killUid(uid, reason);
3516            } catch (RemoteException e) {
3517                /* ignore - same process */
3518            }
3519        }
3520    }
3521
3522    /**
3523     * Compares two sets of signatures. Returns:
3524     * <br />
3525     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3526     * <br />
3527     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3528     * <br />
3529     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3530     * <br />
3531     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3532     * <br />
3533     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3534     */
3535    static int compareSignatures(Signature[] s1, Signature[] s2) {
3536        if (s1 == null) {
3537            return s2 == null
3538                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3539                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3540        }
3541
3542        if (s2 == null) {
3543            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3544        }
3545
3546        if (s1.length != s2.length) {
3547            return PackageManager.SIGNATURE_NO_MATCH;
3548        }
3549
3550        // Since both signature sets are of size 1, we can compare without HashSets.
3551        if (s1.length == 1) {
3552            return s1[0].equals(s2[0]) ?
3553                    PackageManager.SIGNATURE_MATCH :
3554                    PackageManager.SIGNATURE_NO_MATCH;
3555        }
3556
3557        ArraySet<Signature> set1 = new ArraySet<Signature>();
3558        for (Signature sig : s1) {
3559            set1.add(sig);
3560        }
3561        ArraySet<Signature> set2 = new ArraySet<Signature>();
3562        for (Signature sig : s2) {
3563            set2.add(sig);
3564        }
3565        // Make sure s2 contains all signatures in s1.
3566        if (set1.equals(set2)) {
3567            return PackageManager.SIGNATURE_MATCH;
3568        }
3569        return PackageManager.SIGNATURE_NO_MATCH;
3570    }
3571
3572    /**
3573     * If the database version for this type of package (internal storage or
3574     * external storage) is less than the version where package signatures
3575     * were updated, return true.
3576     */
3577    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3578        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3579                DatabaseVersion.SIGNATURE_END_ENTITY))
3580                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3581                        DatabaseVersion.SIGNATURE_END_ENTITY));
3582    }
3583
3584    /**
3585     * Used for backward compatibility to make sure any packages with
3586     * certificate chains get upgraded to the new style. {@code existingSigs}
3587     * will be in the old format (since they were stored on disk from before the
3588     * system upgrade) and {@code scannedSigs} will be in the newer format.
3589     */
3590    private int compareSignaturesCompat(PackageSignatures existingSigs,
3591            PackageParser.Package scannedPkg) {
3592        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3593            return PackageManager.SIGNATURE_NO_MATCH;
3594        }
3595
3596        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3597        for (Signature sig : existingSigs.mSignatures) {
3598            existingSet.add(sig);
3599        }
3600        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3601        for (Signature sig : scannedPkg.mSignatures) {
3602            try {
3603                Signature[] chainSignatures = sig.getChainSignatures();
3604                for (Signature chainSig : chainSignatures) {
3605                    scannedCompatSet.add(chainSig);
3606                }
3607            } catch (CertificateEncodingException e) {
3608                scannedCompatSet.add(sig);
3609            }
3610        }
3611        /*
3612         * Make sure the expanded scanned set contains all signatures in the
3613         * existing one.
3614         */
3615        if (scannedCompatSet.equals(existingSet)) {
3616            // Migrate the old signatures to the new scheme.
3617            existingSigs.assignSignatures(scannedPkg.mSignatures);
3618            // The new KeySets will be re-added later in the scanning process.
3619            synchronized (mPackages) {
3620                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3621            }
3622            return PackageManager.SIGNATURE_MATCH;
3623        }
3624        return PackageManager.SIGNATURE_NO_MATCH;
3625    }
3626
3627    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3628        if (isExternal(scannedPkg)) {
3629            return mSettings.isExternalDatabaseVersionOlderThan(
3630                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3631        } else {
3632            return mSettings.isInternalDatabaseVersionOlderThan(
3633                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3634        }
3635    }
3636
3637    private int compareSignaturesRecover(PackageSignatures existingSigs,
3638            PackageParser.Package scannedPkg) {
3639        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3640            return PackageManager.SIGNATURE_NO_MATCH;
3641        }
3642
3643        String msg = null;
3644        try {
3645            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3646                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3647                        + scannedPkg.packageName);
3648                return PackageManager.SIGNATURE_MATCH;
3649            }
3650        } catch (CertificateException e) {
3651            msg = e.getMessage();
3652        }
3653
3654        logCriticalInfo(Log.INFO,
3655                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3656        return PackageManager.SIGNATURE_NO_MATCH;
3657    }
3658
3659    @Override
3660    public String[] getPackagesForUid(int uid) {
3661        uid = UserHandle.getAppId(uid);
3662        // reader
3663        synchronized (mPackages) {
3664            Object obj = mSettings.getUserIdLPr(uid);
3665            if (obj instanceof SharedUserSetting) {
3666                final SharedUserSetting sus = (SharedUserSetting) obj;
3667                final int N = sus.packages.size();
3668                final String[] res = new String[N];
3669                final Iterator<PackageSetting> it = sus.packages.iterator();
3670                int i = 0;
3671                while (it.hasNext()) {
3672                    res[i++] = it.next().name;
3673                }
3674                return res;
3675            } else if (obj instanceof PackageSetting) {
3676                final PackageSetting ps = (PackageSetting) obj;
3677                return new String[] { ps.name };
3678            }
3679        }
3680        return null;
3681    }
3682
3683    @Override
3684    public String getNameForUid(int uid) {
3685        // reader
3686        synchronized (mPackages) {
3687            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3688            if (obj instanceof SharedUserSetting) {
3689                final SharedUserSetting sus = (SharedUserSetting) obj;
3690                return sus.name + ":" + sus.userId;
3691            } else if (obj instanceof PackageSetting) {
3692                final PackageSetting ps = (PackageSetting) obj;
3693                return ps.name;
3694            }
3695        }
3696        return null;
3697    }
3698
3699    @Override
3700    public int getUidForSharedUser(String sharedUserName) {
3701        if(sharedUserName == null) {
3702            return -1;
3703        }
3704        // reader
3705        synchronized (mPackages) {
3706            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3707            if (suid == null) {
3708                return -1;
3709            }
3710            return suid.userId;
3711        }
3712    }
3713
3714    @Override
3715    public int getFlagsForUid(int uid) {
3716        synchronized (mPackages) {
3717            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3718            if (obj instanceof SharedUserSetting) {
3719                final SharedUserSetting sus = (SharedUserSetting) obj;
3720                return sus.pkgFlags;
3721            } else if (obj instanceof PackageSetting) {
3722                final PackageSetting ps = (PackageSetting) obj;
3723                return ps.pkgFlags;
3724            }
3725        }
3726        return 0;
3727    }
3728
3729    @Override
3730    public int getPrivateFlagsForUid(int uid) {
3731        synchronized (mPackages) {
3732            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3733            if (obj instanceof SharedUserSetting) {
3734                final SharedUserSetting sus = (SharedUserSetting) obj;
3735                return sus.pkgPrivateFlags;
3736            } else if (obj instanceof PackageSetting) {
3737                final PackageSetting ps = (PackageSetting) obj;
3738                return ps.pkgPrivateFlags;
3739            }
3740        }
3741        return 0;
3742    }
3743
3744    @Override
3745    public boolean isUidPrivileged(int uid) {
3746        uid = UserHandle.getAppId(uid);
3747        // reader
3748        synchronized (mPackages) {
3749            Object obj = mSettings.getUserIdLPr(uid);
3750            if (obj instanceof SharedUserSetting) {
3751                final SharedUserSetting sus = (SharedUserSetting) obj;
3752                final Iterator<PackageSetting> it = sus.packages.iterator();
3753                while (it.hasNext()) {
3754                    if (it.next().isPrivileged()) {
3755                        return true;
3756                    }
3757                }
3758            } else if (obj instanceof PackageSetting) {
3759                final PackageSetting ps = (PackageSetting) obj;
3760                return ps.isPrivileged();
3761            }
3762        }
3763        return false;
3764    }
3765
3766    @Override
3767    public String[] getAppOpPermissionPackages(String permissionName) {
3768        synchronized (mPackages) {
3769            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3770            if (pkgs == null) {
3771                return null;
3772            }
3773            return pkgs.toArray(new String[pkgs.size()]);
3774        }
3775    }
3776
3777    @Override
3778    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3779            int flags, int userId) {
3780        if (!sUserManager.exists(userId)) return null;
3781        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3782        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3783        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3784    }
3785
3786    @Override
3787    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3788            IntentFilter filter, int match, ComponentName activity) {
3789        final int userId = UserHandle.getCallingUserId();
3790        if (DEBUG_PREFERRED) {
3791            Log.v(TAG, "setLastChosenActivity intent=" + intent
3792                + " resolvedType=" + resolvedType
3793                + " flags=" + flags
3794                + " filter=" + filter
3795                + " match=" + match
3796                + " activity=" + activity);
3797            filter.dump(new PrintStreamPrinter(System.out), "    ");
3798        }
3799        intent.setComponent(null);
3800        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3801        // Find any earlier preferred or last chosen entries and nuke them
3802        findPreferredActivity(intent, resolvedType,
3803                flags, query, 0, false, true, false, userId);
3804        // Add the new activity as the last chosen for this filter
3805        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3806                "Setting last chosen");
3807    }
3808
3809    @Override
3810    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3811        final int userId = UserHandle.getCallingUserId();
3812        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3813        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3814        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3815                false, false, false, userId);
3816    }
3817
3818    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3819            int flags, List<ResolveInfo> query, int userId) {
3820        if (query != null) {
3821            final int N = query.size();
3822            if (N == 1) {
3823                return query.get(0);
3824            } else if (N > 1) {
3825                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3826                // If there is more than one activity with the same priority,
3827                // then let the user decide between them.
3828                ResolveInfo r0 = query.get(0);
3829                ResolveInfo r1 = query.get(1);
3830                if (DEBUG_INTENT_MATCHING || debug) {
3831                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3832                            + r1.activityInfo.name + "=" + r1.priority);
3833                }
3834                // If the first activity has a higher priority, or a different
3835                // default, then it is always desireable to pick it.
3836                if (r0.priority != r1.priority
3837                        || r0.preferredOrder != r1.preferredOrder
3838                        || r0.isDefault != r1.isDefault) {
3839                    return query.get(0);
3840                }
3841                // If we have saved a preference for a preferred activity for
3842                // this Intent, use that.
3843                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3844                        flags, query, r0.priority, true, false, debug, userId);
3845                if (ri != null) {
3846                    return ri;
3847                }
3848                if (userId != 0) {
3849                    ri = new ResolveInfo(mResolveInfo);
3850                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3851                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3852                            ri.activityInfo.applicationInfo);
3853                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3854                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3855                    return ri;
3856                }
3857                return mResolveInfo;
3858            }
3859        }
3860        return null;
3861    }
3862
3863    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3864            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3865        final int N = query.size();
3866        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3867                .get(userId);
3868        // Get the list of persistent preferred activities that handle the intent
3869        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3870        List<PersistentPreferredActivity> pprefs = ppir != null
3871                ? ppir.queryIntent(intent, resolvedType,
3872                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3873                : null;
3874        if (pprefs != null && pprefs.size() > 0) {
3875            final int M = pprefs.size();
3876            for (int i=0; i<M; i++) {
3877                final PersistentPreferredActivity ppa = pprefs.get(i);
3878                if (DEBUG_PREFERRED || debug) {
3879                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3880                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3881                            + "\n  component=" + ppa.mComponent);
3882                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3883                }
3884                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3885                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3886                if (DEBUG_PREFERRED || debug) {
3887                    Slog.v(TAG, "Found persistent preferred activity:");
3888                    if (ai != null) {
3889                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3890                    } else {
3891                        Slog.v(TAG, "  null");
3892                    }
3893                }
3894                if (ai == null) {
3895                    // This previously registered persistent preferred activity
3896                    // component is no longer known. Ignore it and do NOT remove it.
3897                    continue;
3898                }
3899                for (int j=0; j<N; j++) {
3900                    final ResolveInfo ri = query.get(j);
3901                    if (!ri.activityInfo.applicationInfo.packageName
3902                            .equals(ai.applicationInfo.packageName)) {
3903                        continue;
3904                    }
3905                    if (!ri.activityInfo.name.equals(ai.name)) {
3906                        continue;
3907                    }
3908                    //  Found a persistent preference that can handle the intent.
3909                    if (DEBUG_PREFERRED || debug) {
3910                        Slog.v(TAG, "Returning persistent preferred activity: " +
3911                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3912                    }
3913                    return ri;
3914                }
3915            }
3916        }
3917        return null;
3918    }
3919
3920    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3921            List<ResolveInfo> query, int priority, boolean always,
3922            boolean removeMatches, boolean debug, int userId) {
3923        if (!sUserManager.exists(userId)) return null;
3924        // writer
3925        synchronized (mPackages) {
3926            if (intent.getSelector() != null) {
3927                intent = intent.getSelector();
3928            }
3929            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3930
3931            // Try to find a matching persistent preferred activity.
3932            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3933                    debug, userId);
3934
3935            // If a persistent preferred activity matched, use it.
3936            if (pri != null) {
3937                return pri;
3938            }
3939
3940            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3941            // Get the list of preferred activities that handle the intent
3942            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3943            List<PreferredActivity> prefs = pir != null
3944                    ? pir.queryIntent(intent, resolvedType,
3945                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3946                    : null;
3947            if (prefs != null && prefs.size() > 0) {
3948                boolean changed = false;
3949                try {
3950                    // First figure out how good the original match set is.
3951                    // We will only allow preferred activities that came
3952                    // from the same match quality.
3953                    int match = 0;
3954
3955                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3956
3957                    final int N = query.size();
3958                    for (int j=0; j<N; j++) {
3959                        final ResolveInfo ri = query.get(j);
3960                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3961                                + ": 0x" + Integer.toHexString(match));
3962                        if (ri.match > match) {
3963                            match = ri.match;
3964                        }
3965                    }
3966
3967                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3968                            + Integer.toHexString(match));
3969
3970                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3971                    final int M = prefs.size();
3972                    for (int i=0; i<M; i++) {
3973                        final PreferredActivity pa = prefs.get(i);
3974                        if (DEBUG_PREFERRED || debug) {
3975                            Slog.v(TAG, "Checking PreferredActivity ds="
3976                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3977                                    + "\n  component=" + pa.mPref.mComponent);
3978                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3979                        }
3980                        if (pa.mPref.mMatch != match) {
3981                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3982                                    + Integer.toHexString(pa.mPref.mMatch));
3983                            continue;
3984                        }
3985                        // If it's not an "always" type preferred activity and that's what we're
3986                        // looking for, skip it.
3987                        if (always && !pa.mPref.mAlways) {
3988                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3989                            continue;
3990                        }
3991                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3992                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3993                        if (DEBUG_PREFERRED || debug) {
3994                            Slog.v(TAG, "Found preferred activity:");
3995                            if (ai != null) {
3996                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3997                            } else {
3998                                Slog.v(TAG, "  null");
3999                            }
4000                        }
4001                        if (ai == null) {
4002                            // This previously registered preferred activity
4003                            // component is no longer known.  Most likely an update
4004                            // to the app was installed and in the new version this
4005                            // component no longer exists.  Clean it up by removing
4006                            // it from the preferred activities list, and skip it.
4007                            Slog.w(TAG, "Removing dangling preferred activity: "
4008                                    + pa.mPref.mComponent);
4009                            pir.removeFilter(pa);
4010                            changed = true;
4011                            continue;
4012                        }
4013                        for (int j=0; j<N; j++) {
4014                            final ResolveInfo ri = query.get(j);
4015                            if (!ri.activityInfo.applicationInfo.packageName
4016                                    .equals(ai.applicationInfo.packageName)) {
4017                                continue;
4018                            }
4019                            if (!ri.activityInfo.name.equals(ai.name)) {
4020                                continue;
4021                            }
4022
4023                            if (removeMatches) {
4024                                pir.removeFilter(pa);
4025                                changed = true;
4026                                if (DEBUG_PREFERRED) {
4027                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4028                                }
4029                                break;
4030                            }
4031
4032                            // Okay we found a previously set preferred or last chosen app.
4033                            // If the result set is different from when this
4034                            // was created, we need to clear it and re-ask the
4035                            // user their preference, if we're looking for an "always" type entry.
4036                            if (always && !pa.mPref.sameSet(query)) {
4037                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4038                                        + intent + " type " + resolvedType);
4039                                if (DEBUG_PREFERRED) {
4040                                    Slog.v(TAG, "Removing preferred activity since set changed "
4041                                            + pa.mPref.mComponent);
4042                                }
4043                                pir.removeFilter(pa);
4044                                // Re-add the filter as a "last chosen" entry (!always)
4045                                PreferredActivity lastChosen = new PreferredActivity(
4046                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4047                                pir.addFilter(lastChosen);
4048                                changed = true;
4049                                return null;
4050                            }
4051
4052                            // Yay! Either the set matched or we're looking for the last chosen
4053                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4054                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4055                            return ri;
4056                        }
4057                    }
4058                } finally {
4059                    if (changed) {
4060                        if (DEBUG_PREFERRED) {
4061                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4062                        }
4063                        scheduleWritePackageRestrictionsLocked(userId);
4064                    }
4065                }
4066            }
4067        }
4068        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4069        return null;
4070    }
4071
4072    /*
4073     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4074     */
4075    @Override
4076    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4077            int targetUserId) {
4078        mContext.enforceCallingOrSelfPermission(
4079                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4080        List<CrossProfileIntentFilter> matches =
4081                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4082        if (matches != null) {
4083            int size = matches.size();
4084            for (int i = 0; i < size; i++) {
4085                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4086            }
4087        }
4088        if (hasWebURI(intent)) {
4089            // cross-profile app linking works only towards the parent.
4090            final UserInfo parent = getProfileParent(sourceUserId);
4091            synchronized(mPackages) {
4092                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4093                        parent.id) != null;
4094            }
4095        }
4096        return false;
4097    }
4098
4099    private UserInfo getProfileParent(int userId) {
4100        final long identity = Binder.clearCallingIdentity();
4101        try {
4102            return sUserManager.getProfileParent(userId);
4103        } finally {
4104            Binder.restoreCallingIdentity(identity);
4105        }
4106    }
4107
4108    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4109            String resolvedType, int userId) {
4110        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4111        if (resolver != null) {
4112            return resolver.queryIntent(intent, resolvedType, false, userId);
4113        }
4114        return null;
4115    }
4116
4117    @Override
4118    public List<ResolveInfo> queryIntentActivities(Intent intent,
4119            String resolvedType, int flags, int userId) {
4120        if (!sUserManager.exists(userId)) return Collections.emptyList();
4121        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4122        ComponentName comp = intent.getComponent();
4123        if (comp == null) {
4124            if (intent.getSelector() != null) {
4125                intent = intent.getSelector();
4126                comp = intent.getComponent();
4127            }
4128        }
4129
4130        if (comp != null) {
4131            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4132            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4133            if (ai != null) {
4134                final ResolveInfo ri = new ResolveInfo();
4135                ri.activityInfo = ai;
4136                list.add(ri);
4137            }
4138            return list;
4139        }
4140
4141        // reader
4142        synchronized (mPackages) {
4143            final String pkgName = intent.getPackage();
4144            if (pkgName == null) {
4145                List<CrossProfileIntentFilter> matchingFilters =
4146                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4147                // Check for results that need to skip the current profile.
4148                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4149                        resolvedType, flags, userId);
4150                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4151                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4152                    result.add(xpResolveInfo);
4153                    return filterIfNotPrimaryUser(result, userId);
4154                }
4155
4156                // Check for results in the current profile.
4157                List<ResolveInfo> result = mActivities.queryIntent(
4158                        intent, resolvedType, flags, userId);
4159
4160                // Check for cross profile results.
4161                xpResolveInfo = queryCrossProfileIntents(
4162                        matchingFilters, intent, resolvedType, flags, userId);
4163                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4164                    result.add(xpResolveInfo);
4165                    Collections.sort(result, mResolvePrioritySorter);
4166                }
4167                result = filterIfNotPrimaryUser(result, userId);
4168                if (hasWebURI(intent)) {
4169                    CrossProfileDomainInfo xpDomainInfo = null;
4170                    final UserInfo parent = getProfileParent(userId);
4171                    if (parent != null) {
4172                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4173                                flags, userId, parent.id);
4174                    }
4175                    if (xpDomainInfo != null) {
4176                        if (xpResolveInfo != null) {
4177                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4178                            // in the result.
4179                            result.remove(xpResolveInfo);
4180                        }
4181                        if (result.size() == 0) {
4182                            result.add(xpDomainInfo.resolveInfo);
4183                            return result;
4184                        }
4185                    } else if (result.size() <= 1) {
4186                        return result;
4187                    }
4188                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4189                            xpDomainInfo);
4190                    Collections.sort(result, mResolvePrioritySorter);
4191                }
4192                return result;
4193            }
4194            final PackageParser.Package pkg = mPackages.get(pkgName);
4195            if (pkg != null) {
4196                return filterIfNotPrimaryUser(
4197                        mActivities.queryIntentForPackage(
4198                                intent, resolvedType, flags, pkg.activities, userId),
4199                        userId);
4200            }
4201            return new ArrayList<ResolveInfo>();
4202        }
4203    }
4204
4205    private static class CrossProfileDomainInfo {
4206        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4207        ResolveInfo resolveInfo;
4208        /* Best domain verification status of the activities found in the other profile */
4209        int bestDomainVerificationStatus;
4210    }
4211
4212    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4213            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4214        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_APP_LINKING,
4215                sourceUserId)) {
4216            return null;
4217        }
4218        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4219                resolvedType, flags, parentUserId);
4220
4221        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4222            return null;
4223        }
4224        CrossProfileDomainInfo result = null;
4225        int size = resultTargetUser.size();
4226        for (int i = 0; i < size; i++) {
4227            ResolveInfo riTargetUser = resultTargetUser.get(i);
4228            // Intent filter verification is only for filters that specify a host. So don't return
4229            // those that handle all web uris.
4230            if (riTargetUser.handleAllWebDataURI) {
4231                continue;
4232            }
4233            String packageName = riTargetUser.activityInfo.packageName;
4234            PackageSetting ps = mSettings.mPackages.get(packageName);
4235            if (ps == null) {
4236                continue;
4237            }
4238            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4239            if (result == null) {
4240                result = new CrossProfileDomainInfo();
4241                result.resolveInfo =
4242                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4243                result.bestDomainVerificationStatus = status;
4244            } else {
4245                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4246                        result.bestDomainVerificationStatus);
4247            }
4248        }
4249        return result;
4250    }
4251
4252    /**
4253     * Verification statuses are ordered from the worse to the best, except for
4254     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4255     */
4256    private int bestDomainVerificationStatus(int status1, int status2) {
4257        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4258            return status2;
4259        }
4260        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4261            return status1;
4262        }
4263        return (int) MathUtils.max(status1, status2);
4264    }
4265
4266    private boolean isUserEnabled(int userId) {
4267        long callingId = Binder.clearCallingIdentity();
4268        try {
4269            UserInfo userInfo = sUserManager.getUserInfo(userId);
4270            return userInfo != null && userInfo.isEnabled();
4271        } finally {
4272            Binder.restoreCallingIdentity(callingId);
4273        }
4274    }
4275
4276    /**
4277     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4278     *
4279     * @return filtered list
4280     */
4281    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4282        if (userId == UserHandle.USER_OWNER) {
4283            return resolveInfos;
4284        }
4285        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4286            ResolveInfo info = resolveInfos.get(i);
4287            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4288                resolveInfos.remove(i);
4289            }
4290        }
4291        return resolveInfos;
4292    }
4293
4294    private static boolean hasWebURI(Intent intent) {
4295        if (intent.getData() == null) {
4296            return false;
4297        }
4298        final String scheme = intent.getScheme();
4299        if (TextUtils.isEmpty(scheme)) {
4300            return false;
4301        }
4302        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4303    }
4304
4305    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4306            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4307        if (DEBUG_PREFERRED) {
4308            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4309                    candidates.size());
4310        }
4311
4312        final int userId = UserHandle.getCallingUserId();
4313        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4314        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4315        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4316        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4317        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4318
4319        synchronized (mPackages) {
4320            final int count = candidates.size();
4321            // First, try to use the domain prefered App. Partition the candidates into four lists:
4322            // one for the final results, one for the "do not use ever", one for "undefined status"
4323            // and finally one for "Browser App type".
4324            for (int n=0; n<count; n++) {
4325                ResolveInfo info = candidates.get(n);
4326                String packageName = info.activityInfo.packageName;
4327                PackageSetting ps = mSettings.mPackages.get(packageName);
4328                if (ps != null) {
4329                    // Add to the special match all list (Browser use case)
4330                    if (info.handleAllWebDataURI) {
4331                        matchAllList.add(info);
4332                        continue;
4333                    }
4334                    // Try to get the status from User settings first
4335                    int status = getDomainVerificationStatusLPr(ps, userId);
4336                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4337                        alwaysList.add(info);
4338                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4339                        neverList.add(info);
4340                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4341                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4342                        undefinedList.add(info);
4343                    }
4344                }
4345            }
4346            // First try to add the "always" resolution for the current user if there is any
4347            if (alwaysList.size() > 0) {
4348                result.addAll(alwaysList);
4349            // if there is an "always" for the parent user, add it.
4350            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4351                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4352                result.add(xpDomainInfo.resolveInfo);
4353            } else {
4354                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4355                result.addAll(undefinedList);
4356                if (xpDomainInfo != null && (
4357                        xpDomainInfo.bestDomainVerificationStatus
4358                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4359                        || xpDomainInfo.bestDomainVerificationStatus
4360                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4361                    result.add(xpDomainInfo.resolveInfo);
4362                }
4363                // Also add Browsers (all of them or only the default one)
4364                if ((flags & MATCH_ALL) != 0) {
4365                    result.addAll(matchAllList);
4366                } else {
4367                    // Try to add the Default Browser if we can
4368                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4369                            UserHandle.myUserId());
4370                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4371                        boolean defaultBrowserFound = false;
4372                        final int browserCount = matchAllList.size();
4373                        for (int n=0; n<browserCount; n++) {
4374                            ResolveInfo browser = matchAllList.get(n);
4375                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4376                                result.add(browser);
4377                                defaultBrowserFound = true;
4378                                break;
4379                            }
4380                        }
4381                        if (!defaultBrowserFound) {
4382                            result.addAll(matchAllList);
4383                        }
4384                    } else {
4385                        result.addAll(matchAllList);
4386                    }
4387                }
4388
4389                // If there is nothing selected, add all candidates and remove the ones that the User
4390                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4391                if (result.size() == 0) {
4392                    result.addAll(candidates);
4393                    result.removeAll(neverList);
4394                }
4395            }
4396        }
4397        if (DEBUG_PREFERRED) {
4398            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4399                    result.size());
4400        }
4401        return result;
4402    }
4403
4404    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4405        int status = ps.getDomainVerificationStatusForUser(userId);
4406        // if none available, get the master status
4407        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4408            if (ps.getIntentFilterVerificationInfo() != null) {
4409                status = ps.getIntentFilterVerificationInfo().getStatus();
4410            }
4411        }
4412        return status;
4413    }
4414
4415    private ResolveInfo querySkipCurrentProfileIntents(
4416            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4417            int flags, int sourceUserId) {
4418        if (matchingFilters != null) {
4419            int size = matchingFilters.size();
4420            for (int i = 0; i < size; i ++) {
4421                CrossProfileIntentFilter filter = matchingFilters.get(i);
4422                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4423                    // Checking if there are activities in the target user that can handle the
4424                    // intent.
4425                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4426                            flags, sourceUserId);
4427                    if (resolveInfo != null) {
4428                        return resolveInfo;
4429                    }
4430                }
4431            }
4432        }
4433        return null;
4434    }
4435
4436    // Return matching ResolveInfo if any for skip current profile intent filters.
4437    private ResolveInfo queryCrossProfileIntents(
4438            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4439            int flags, int sourceUserId) {
4440        if (matchingFilters != null) {
4441            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4442            // match the same intent. For performance reasons, it is better not to
4443            // run queryIntent twice for the same userId
4444            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4445            int size = matchingFilters.size();
4446            for (int i = 0; i < size; i++) {
4447                CrossProfileIntentFilter filter = matchingFilters.get(i);
4448                int targetUserId = filter.getTargetUserId();
4449                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4450                        && !alreadyTriedUserIds.get(targetUserId)) {
4451                    // Checking if there are activities in the target user that can handle the
4452                    // intent.
4453                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4454                            flags, sourceUserId);
4455                    if (resolveInfo != null) return resolveInfo;
4456                    alreadyTriedUserIds.put(targetUserId, true);
4457                }
4458            }
4459        }
4460        return null;
4461    }
4462
4463    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4464            String resolvedType, int flags, int sourceUserId) {
4465        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4466                resolvedType, flags, filter.getTargetUserId());
4467        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4468            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4469        }
4470        return null;
4471    }
4472
4473    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4474            int sourceUserId, int targetUserId) {
4475        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4476        String className;
4477        if (targetUserId == UserHandle.USER_OWNER) {
4478            className = FORWARD_INTENT_TO_USER_OWNER;
4479        } else {
4480            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4481        }
4482        ComponentName forwardingActivityComponentName = new ComponentName(
4483                mAndroidApplication.packageName, className);
4484        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4485                sourceUserId);
4486        if (targetUserId == UserHandle.USER_OWNER) {
4487            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4488            forwardingResolveInfo.noResourceId = true;
4489        }
4490        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4491        forwardingResolveInfo.priority = 0;
4492        forwardingResolveInfo.preferredOrder = 0;
4493        forwardingResolveInfo.match = 0;
4494        forwardingResolveInfo.isDefault = true;
4495        forwardingResolveInfo.filter = filter;
4496        forwardingResolveInfo.targetUserId = targetUserId;
4497        return forwardingResolveInfo;
4498    }
4499
4500    @Override
4501    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4502            Intent[] specifics, String[] specificTypes, Intent intent,
4503            String resolvedType, int flags, int userId) {
4504        if (!sUserManager.exists(userId)) return Collections.emptyList();
4505        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4506                false, "query intent activity options");
4507        final String resultsAction = intent.getAction();
4508
4509        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4510                | PackageManager.GET_RESOLVED_FILTER, userId);
4511
4512        if (DEBUG_INTENT_MATCHING) {
4513            Log.v(TAG, "Query " + intent + ": " + results);
4514        }
4515
4516        int specificsPos = 0;
4517        int N;
4518
4519        // todo: note that the algorithm used here is O(N^2).  This
4520        // isn't a problem in our current environment, but if we start running
4521        // into situations where we have more than 5 or 10 matches then this
4522        // should probably be changed to something smarter...
4523
4524        // First we go through and resolve each of the specific items
4525        // that were supplied, taking care of removing any corresponding
4526        // duplicate items in the generic resolve list.
4527        if (specifics != null) {
4528            for (int i=0; i<specifics.length; i++) {
4529                final Intent sintent = specifics[i];
4530                if (sintent == null) {
4531                    continue;
4532                }
4533
4534                if (DEBUG_INTENT_MATCHING) {
4535                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4536                }
4537
4538                String action = sintent.getAction();
4539                if (resultsAction != null && resultsAction.equals(action)) {
4540                    // If this action was explicitly requested, then don't
4541                    // remove things that have it.
4542                    action = null;
4543                }
4544
4545                ResolveInfo ri = null;
4546                ActivityInfo ai = null;
4547
4548                ComponentName comp = sintent.getComponent();
4549                if (comp == null) {
4550                    ri = resolveIntent(
4551                        sintent,
4552                        specificTypes != null ? specificTypes[i] : null,
4553                            flags, userId);
4554                    if (ri == null) {
4555                        continue;
4556                    }
4557                    if (ri == mResolveInfo) {
4558                        // ACK!  Must do something better with this.
4559                    }
4560                    ai = ri.activityInfo;
4561                    comp = new ComponentName(ai.applicationInfo.packageName,
4562                            ai.name);
4563                } else {
4564                    ai = getActivityInfo(comp, flags, userId);
4565                    if (ai == null) {
4566                        continue;
4567                    }
4568                }
4569
4570                // Look for any generic query activities that are duplicates
4571                // of this specific one, and remove them from the results.
4572                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4573                N = results.size();
4574                int j;
4575                for (j=specificsPos; j<N; j++) {
4576                    ResolveInfo sri = results.get(j);
4577                    if ((sri.activityInfo.name.equals(comp.getClassName())
4578                            && sri.activityInfo.applicationInfo.packageName.equals(
4579                                    comp.getPackageName()))
4580                        || (action != null && sri.filter.matchAction(action))) {
4581                        results.remove(j);
4582                        if (DEBUG_INTENT_MATCHING) Log.v(
4583                            TAG, "Removing duplicate item from " + j
4584                            + " due to specific " + specificsPos);
4585                        if (ri == null) {
4586                            ri = sri;
4587                        }
4588                        j--;
4589                        N--;
4590                    }
4591                }
4592
4593                // Add this specific item to its proper place.
4594                if (ri == null) {
4595                    ri = new ResolveInfo();
4596                    ri.activityInfo = ai;
4597                }
4598                results.add(specificsPos, ri);
4599                ri.specificIndex = i;
4600                specificsPos++;
4601            }
4602        }
4603
4604        // Now we go through the remaining generic results and remove any
4605        // duplicate actions that are found here.
4606        N = results.size();
4607        for (int i=specificsPos; i<N-1; i++) {
4608            final ResolveInfo rii = results.get(i);
4609            if (rii.filter == null) {
4610                continue;
4611            }
4612
4613            // Iterate over all of the actions of this result's intent
4614            // filter...  typically this should be just one.
4615            final Iterator<String> it = rii.filter.actionsIterator();
4616            if (it == null) {
4617                continue;
4618            }
4619            while (it.hasNext()) {
4620                final String action = it.next();
4621                if (resultsAction != null && resultsAction.equals(action)) {
4622                    // If this action was explicitly requested, then don't
4623                    // remove things that have it.
4624                    continue;
4625                }
4626                for (int j=i+1; j<N; j++) {
4627                    final ResolveInfo rij = results.get(j);
4628                    if (rij.filter != null && rij.filter.hasAction(action)) {
4629                        results.remove(j);
4630                        if (DEBUG_INTENT_MATCHING) Log.v(
4631                            TAG, "Removing duplicate item from " + j
4632                            + " due to action " + action + " at " + i);
4633                        j--;
4634                        N--;
4635                    }
4636                }
4637            }
4638
4639            // If the caller didn't request filter information, drop it now
4640            // so we don't have to marshall/unmarshall it.
4641            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4642                rii.filter = null;
4643            }
4644        }
4645
4646        // Filter out the caller activity if so requested.
4647        if (caller != null) {
4648            N = results.size();
4649            for (int i=0; i<N; i++) {
4650                ActivityInfo ainfo = results.get(i).activityInfo;
4651                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4652                        && caller.getClassName().equals(ainfo.name)) {
4653                    results.remove(i);
4654                    break;
4655                }
4656            }
4657        }
4658
4659        // If the caller didn't request filter information,
4660        // drop them now so we don't have to
4661        // marshall/unmarshall it.
4662        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4663            N = results.size();
4664            for (int i=0; i<N; i++) {
4665                results.get(i).filter = null;
4666            }
4667        }
4668
4669        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4670        return results;
4671    }
4672
4673    @Override
4674    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4675            int userId) {
4676        if (!sUserManager.exists(userId)) return Collections.emptyList();
4677        ComponentName comp = intent.getComponent();
4678        if (comp == null) {
4679            if (intent.getSelector() != null) {
4680                intent = intent.getSelector();
4681                comp = intent.getComponent();
4682            }
4683        }
4684        if (comp != null) {
4685            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4686            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4687            if (ai != null) {
4688                ResolveInfo ri = new ResolveInfo();
4689                ri.activityInfo = ai;
4690                list.add(ri);
4691            }
4692            return list;
4693        }
4694
4695        // reader
4696        synchronized (mPackages) {
4697            String pkgName = intent.getPackage();
4698            if (pkgName == null) {
4699                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4700            }
4701            final PackageParser.Package pkg = mPackages.get(pkgName);
4702            if (pkg != null) {
4703                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4704                        userId);
4705            }
4706            return null;
4707        }
4708    }
4709
4710    @Override
4711    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4712        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4713        if (!sUserManager.exists(userId)) return null;
4714        if (query != null) {
4715            if (query.size() >= 1) {
4716                // If there is more than one service with the same priority,
4717                // just arbitrarily pick the first one.
4718                return query.get(0);
4719            }
4720        }
4721        return null;
4722    }
4723
4724    @Override
4725    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4726            int userId) {
4727        if (!sUserManager.exists(userId)) return Collections.emptyList();
4728        ComponentName comp = intent.getComponent();
4729        if (comp == null) {
4730            if (intent.getSelector() != null) {
4731                intent = intent.getSelector();
4732                comp = intent.getComponent();
4733            }
4734        }
4735        if (comp != null) {
4736            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4737            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4738            if (si != null) {
4739                final ResolveInfo ri = new ResolveInfo();
4740                ri.serviceInfo = si;
4741                list.add(ri);
4742            }
4743            return list;
4744        }
4745
4746        // reader
4747        synchronized (mPackages) {
4748            String pkgName = intent.getPackage();
4749            if (pkgName == null) {
4750                return mServices.queryIntent(intent, resolvedType, flags, userId);
4751            }
4752            final PackageParser.Package pkg = mPackages.get(pkgName);
4753            if (pkg != null) {
4754                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4755                        userId);
4756            }
4757            return null;
4758        }
4759    }
4760
4761    @Override
4762    public List<ResolveInfo> queryIntentContentProviders(
4763            Intent intent, String resolvedType, int flags, int userId) {
4764        if (!sUserManager.exists(userId)) return Collections.emptyList();
4765        ComponentName comp = intent.getComponent();
4766        if (comp == null) {
4767            if (intent.getSelector() != null) {
4768                intent = intent.getSelector();
4769                comp = intent.getComponent();
4770            }
4771        }
4772        if (comp != null) {
4773            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4774            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4775            if (pi != null) {
4776                final ResolveInfo ri = new ResolveInfo();
4777                ri.providerInfo = pi;
4778                list.add(ri);
4779            }
4780            return list;
4781        }
4782
4783        // reader
4784        synchronized (mPackages) {
4785            String pkgName = intent.getPackage();
4786            if (pkgName == null) {
4787                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4788            }
4789            final PackageParser.Package pkg = mPackages.get(pkgName);
4790            if (pkg != null) {
4791                return mProviders.queryIntentForPackage(
4792                        intent, resolvedType, flags, pkg.providers, userId);
4793            }
4794            return null;
4795        }
4796    }
4797
4798    @Override
4799    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4800        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4801
4802        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4803
4804        // writer
4805        synchronized (mPackages) {
4806            ArrayList<PackageInfo> list;
4807            if (listUninstalled) {
4808                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4809                for (PackageSetting ps : mSettings.mPackages.values()) {
4810                    PackageInfo pi;
4811                    if (ps.pkg != null) {
4812                        pi = generatePackageInfo(ps.pkg, flags, userId);
4813                    } else {
4814                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4815                    }
4816                    if (pi != null) {
4817                        list.add(pi);
4818                    }
4819                }
4820            } else {
4821                list = new ArrayList<PackageInfo>(mPackages.size());
4822                for (PackageParser.Package p : mPackages.values()) {
4823                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4824                    if (pi != null) {
4825                        list.add(pi);
4826                    }
4827                }
4828            }
4829
4830            return new ParceledListSlice<PackageInfo>(list);
4831        }
4832    }
4833
4834    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4835            String[] permissions, boolean[] tmp, int flags, int userId) {
4836        int numMatch = 0;
4837        final PermissionsState permissionsState = ps.getPermissionsState();
4838        for (int i=0; i<permissions.length; i++) {
4839            final String permission = permissions[i];
4840            if (permissionsState.hasPermission(permission, userId)) {
4841                tmp[i] = true;
4842                numMatch++;
4843            } else {
4844                tmp[i] = false;
4845            }
4846        }
4847        if (numMatch == 0) {
4848            return;
4849        }
4850        PackageInfo pi;
4851        if (ps.pkg != null) {
4852            pi = generatePackageInfo(ps.pkg, flags, userId);
4853        } else {
4854            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4855        }
4856        // The above might return null in cases of uninstalled apps or install-state
4857        // skew across users/profiles.
4858        if (pi != null) {
4859            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4860                if (numMatch == permissions.length) {
4861                    pi.requestedPermissions = permissions;
4862                } else {
4863                    pi.requestedPermissions = new String[numMatch];
4864                    numMatch = 0;
4865                    for (int i=0; i<permissions.length; i++) {
4866                        if (tmp[i]) {
4867                            pi.requestedPermissions[numMatch] = permissions[i];
4868                            numMatch++;
4869                        }
4870                    }
4871                }
4872            }
4873            list.add(pi);
4874        }
4875    }
4876
4877    @Override
4878    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4879            String[] permissions, int flags, int userId) {
4880        if (!sUserManager.exists(userId)) return null;
4881        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4882
4883        // writer
4884        synchronized (mPackages) {
4885            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4886            boolean[] tmpBools = new boolean[permissions.length];
4887            if (listUninstalled) {
4888                for (PackageSetting ps : mSettings.mPackages.values()) {
4889                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4890                }
4891            } else {
4892                for (PackageParser.Package pkg : mPackages.values()) {
4893                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4894                    if (ps != null) {
4895                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4896                                userId);
4897                    }
4898                }
4899            }
4900
4901            return new ParceledListSlice<PackageInfo>(list);
4902        }
4903    }
4904
4905    @Override
4906    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4907        if (!sUserManager.exists(userId)) return null;
4908        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4909
4910        // writer
4911        synchronized (mPackages) {
4912            ArrayList<ApplicationInfo> list;
4913            if (listUninstalled) {
4914                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4915                for (PackageSetting ps : mSettings.mPackages.values()) {
4916                    ApplicationInfo ai;
4917                    if (ps.pkg != null) {
4918                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4919                                ps.readUserState(userId), userId);
4920                    } else {
4921                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4922                    }
4923                    if (ai != null) {
4924                        list.add(ai);
4925                    }
4926                }
4927            } else {
4928                list = new ArrayList<ApplicationInfo>(mPackages.size());
4929                for (PackageParser.Package p : mPackages.values()) {
4930                    if (p.mExtras != null) {
4931                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4932                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4933                        if (ai != null) {
4934                            list.add(ai);
4935                        }
4936                    }
4937                }
4938            }
4939
4940            return new ParceledListSlice<ApplicationInfo>(list);
4941        }
4942    }
4943
4944    public List<ApplicationInfo> getPersistentApplications(int flags) {
4945        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4946
4947        // reader
4948        synchronized (mPackages) {
4949            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4950            final int userId = UserHandle.getCallingUserId();
4951            while (i.hasNext()) {
4952                final PackageParser.Package p = i.next();
4953                if (p.applicationInfo != null
4954                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4955                        && (!mSafeMode || isSystemApp(p))) {
4956                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4957                    if (ps != null) {
4958                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4959                                ps.readUserState(userId), userId);
4960                        if (ai != null) {
4961                            finalList.add(ai);
4962                        }
4963                    }
4964                }
4965            }
4966        }
4967
4968        return finalList;
4969    }
4970
4971    @Override
4972    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4973        if (!sUserManager.exists(userId)) return null;
4974        // reader
4975        synchronized (mPackages) {
4976            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4977            PackageSetting ps = provider != null
4978                    ? mSettings.mPackages.get(provider.owner.packageName)
4979                    : null;
4980            return ps != null
4981                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4982                    && (!mSafeMode || (provider.info.applicationInfo.flags
4983                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4984                    ? PackageParser.generateProviderInfo(provider, flags,
4985                            ps.readUserState(userId), userId)
4986                    : null;
4987        }
4988    }
4989
4990    /**
4991     * @deprecated
4992     */
4993    @Deprecated
4994    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4995        // reader
4996        synchronized (mPackages) {
4997            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4998                    .entrySet().iterator();
4999            final int userId = UserHandle.getCallingUserId();
5000            while (i.hasNext()) {
5001                Map.Entry<String, PackageParser.Provider> entry = i.next();
5002                PackageParser.Provider p = entry.getValue();
5003                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5004
5005                if (ps != null && p.syncable
5006                        && (!mSafeMode || (p.info.applicationInfo.flags
5007                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5008                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5009                            ps.readUserState(userId), userId);
5010                    if (info != null) {
5011                        outNames.add(entry.getKey());
5012                        outInfo.add(info);
5013                    }
5014                }
5015            }
5016        }
5017    }
5018
5019    @Override
5020    public List<ProviderInfo> queryContentProviders(String processName,
5021            int uid, int flags) {
5022        ArrayList<ProviderInfo> finalList = null;
5023        // reader
5024        synchronized (mPackages) {
5025            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5026            final int userId = processName != null ?
5027                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5028            while (i.hasNext()) {
5029                final PackageParser.Provider p = i.next();
5030                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5031                if (ps != null && p.info.authority != null
5032                        && (processName == null
5033                                || (p.info.processName.equals(processName)
5034                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5035                        && mSettings.isEnabledLPr(p.info, flags, userId)
5036                        && (!mSafeMode
5037                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5038                    if (finalList == null) {
5039                        finalList = new ArrayList<ProviderInfo>(3);
5040                    }
5041                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5042                            ps.readUserState(userId), userId);
5043                    if (info != null) {
5044                        finalList.add(info);
5045                    }
5046                }
5047            }
5048        }
5049
5050        if (finalList != null) {
5051            Collections.sort(finalList, mProviderInitOrderSorter);
5052        }
5053
5054        return finalList;
5055    }
5056
5057    @Override
5058    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5059            int flags) {
5060        // reader
5061        synchronized (mPackages) {
5062            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5063            return PackageParser.generateInstrumentationInfo(i, flags);
5064        }
5065    }
5066
5067    @Override
5068    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5069            int flags) {
5070        ArrayList<InstrumentationInfo> finalList =
5071            new ArrayList<InstrumentationInfo>();
5072
5073        // reader
5074        synchronized (mPackages) {
5075            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5076            while (i.hasNext()) {
5077                final PackageParser.Instrumentation p = i.next();
5078                if (targetPackage == null
5079                        || targetPackage.equals(p.info.targetPackage)) {
5080                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5081                            flags);
5082                    if (ii != null) {
5083                        finalList.add(ii);
5084                    }
5085                }
5086            }
5087        }
5088
5089        return finalList;
5090    }
5091
5092    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5093        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5094        if (overlays == null) {
5095            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5096            return;
5097        }
5098        for (PackageParser.Package opkg : overlays.values()) {
5099            // Not much to do if idmap fails: we already logged the error
5100            // and we certainly don't want to abort installation of pkg simply
5101            // because an overlay didn't fit properly. For these reasons,
5102            // ignore the return value of createIdmapForPackagePairLI.
5103            createIdmapForPackagePairLI(pkg, opkg);
5104        }
5105    }
5106
5107    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5108            PackageParser.Package opkg) {
5109        if (!opkg.mTrustedOverlay) {
5110            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5111                    opkg.baseCodePath + ": overlay not trusted");
5112            return false;
5113        }
5114        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5115        if (overlaySet == null) {
5116            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5117                    opkg.baseCodePath + " but target package has no known overlays");
5118            return false;
5119        }
5120        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5121        // TODO: generate idmap for split APKs
5122        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5123            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5124                    + opkg.baseCodePath);
5125            return false;
5126        }
5127        PackageParser.Package[] overlayArray =
5128            overlaySet.values().toArray(new PackageParser.Package[0]);
5129        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5130            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5131                return p1.mOverlayPriority - p2.mOverlayPriority;
5132            }
5133        };
5134        Arrays.sort(overlayArray, cmp);
5135
5136        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5137        int i = 0;
5138        for (PackageParser.Package p : overlayArray) {
5139            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5140        }
5141        return true;
5142    }
5143
5144    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5145        final File[] files = dir.listFiles();
5146        if (ArrayUtils.isEmpty(files)) {
5147            Log.d(TAG, "No files in app dir " + dir);
5148            return;
5149        }
5150
5151        if (DEBUG_PACKAGE_SCANNING) {
5152            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5153                    + " flags=0x" + Integer.toHexString(parseFlags));
5154        }
5155
5156        for (File file : files) {
5157            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5158                    && !PackageInstallerService.isStageName(file.getName());
5159            if (!isPackage) {
5160                // Ignore entries which are not packages
5161                continue;
5162            }
5163            try {
5164                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5165                        scanFlags, currentTime, null);
5166            } catch (PackageManagerException e) {
5167                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5168
5169                // Delete invalid userdata apps
5170                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5171                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5172                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5173                    if (file.isDirectory()) {
5174                        mInstaller.rmPackageDir(file.getAbsolutePath());
5175                    } else {
5176                        file.delete();
5177                    }
5178                }
5179            }
5180        }
5181    }
5182
5183    private static File getSettingsProblemFile() {
5184        File dataDir = Environment.getDataDirectory();
5185        File systemDir = new File(dataDir, "system");
5186        File fname = new File(systemDir, "uiderrors.txt");
5187        return fname;
5188    }
5189
5190    static void reportSettingsProblem(int priority, String msg) {
5191        logCriticalInfo(priority, msg);
5192    }
5193
5194    static void logCriticalInfo(int priority, String msg) {
5195        Slog.println(priority, TAG, msg);
5196        EventLogTags.writePmCriticalInfo(msg);
5197        try {
5198            File fname = getSettingsProblemFile();
5199            FileOutputStream out = new FileOutputStream(fname, true);
5200            PrintWriter pw = new FastPrintWriter(out);
5201            SimpleDateFormat formatter = new SimpleDateFormat();
5202            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5203            pw.println(dateString + ": " + msg);
5204            pw.close();
5205            FileUtils.setPermissions(
5206                    fname.toString(),
5207                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5208                    -1, -1);
5209        } catch (java.io.IOException e) {
5210        }
5211    }
5212
5213    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5214            PackageParser.Package pkg, File srcFile, int parseFlags)
5215            throws PackageManagerException {
5216        if (ps != null
5217                && ps.codePath.equals(srcFile)
5218                && ps.timeStamp == srcFile.lastModified()
5219                && !isCompatSignatureUpdateNeeded(pkg)
5220                && !isRecoverSignatureUpdateNeeded(pkg)) {
5221            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5222            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5223            ArraySet<PublicKey> signingKs;
5224            synchronized (mPackages) {
5225                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5226            }
5227            if (ps.signatures.mSignatures != null
5228                    && ps.signatures.mSignatures.length != 0
5229                    && signingKs != null) {
5230                // Optimization: reuse the existing cached certificates
5231                // if the package appears to be unchanged.
5232                pkg.mSignatures = ps.signatures.mSignatures;
5233                pkg.mSigningKeys = signingKs;
5234                return;
5235            }
5236
5237            Slog.w(TAG, "PackageSetting for " + ps.name
5238                    + " is missing signatures.  Collecting certs again to recover them.");
5239        } else {
5240            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5241        }
5242
5243        try {
5244            pp.collectCertificates(pkg, parseFlags);
5245            pp.collectManifestDigest(pkg);
5246        } catch (PackageParserException e) {
5247            throw PackageManagerException.from(e);
5248        }
5249    }
5250
5251    /*
5252     *  Scan a package and return the newly parsed package.
5253     *  Returns null in case of errors and the error code is stored in mLastScanError
5254     */
5255    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5256            long currentTime, UserHandle user) throws PackageManagerException {
5257        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5258        parseFlags |= mDefParseFlags;
5259        PackageParser pp = new PackageParser();
5260        pp.setSeparateProcesses(mSeparateProcesses);
5261        pp.setOnlyCoreApps(mOnlyCore);
5262        pp.setDisplayMetrics(mMetrics);
5263
5264        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5265            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5266        }
5267
5268        final PackageParser.Package pkg;
5269        try {
5270            pkg = pp.parsePackage(scanFile, parseFlags);
5271        } catch (PackageParserException e) {
5272            throw PackageManagerException.from(e);
5273        }
5274
5275        PackageSetting ps = null;
5276        PackageSetting updatedPkg;
5277        // reader
5278        synchronized (mPackages) {
5279            // Look to see if we already know about this package.
5280            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5281            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5282                // This package has been renamed to its original name.  Let's
5283                // use that.
5284                ps = mSettings.peekPackageLPr(oldName);
5285            }
5286            // If there was no original package, see one for the real package name.
5287            if (ps == null) {
5288                ps = mSettings.peekPackageLPr(pkg.packageName);
5289            }
5290            // Check to see if this package could be hiding/updating a system
5291            // package.  Must look for it either under the original or real
5292            // package name depending on our state.
5293            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5294            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5295        }
5296        boolean updatedPkgBetter = false;
5297        // First check if this is a system package that may involve an update
5298        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5299            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5300            // it needs to drop FLAG_PRIVILEGED.
5301            if (locationIsPrivileged(scanFile)) {
5302                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5303            } else {
5304                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5305            }
5306
5307            if (ps != null && !ps.codePath.equals(scanFile)) {
5308                // The path has changed from what was last scanned...  check the
5309                // version of the new path against what we have stored to determine
5310                // what to do.
5311                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5312                if (pkg.mVersionCode <= ps.versionCode) {
5313                    // The system package has been updated and the code path does not match
5314                    // Ignore entry. Skip it.
5315                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5316                            + " ignored: updated version " + ps.versionCode
5317                            + " better than this " + pkg.mVersionCode);
5318                    if (!updatedPkg.codePath.equals(scanFile)) {
5319                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5320                                + ps.name + " changing from " + updatedPkg.codePathString
5321                                + " to " + scanFile);
5322                        updatedPkg.codePath = scanFile;
5323                        updatedPkg.codePathString = scanFile.toString();
5324                        updatedPkg.resourcePath = scanFile;
5325                        updatedPkg.resourcePathString = scanFile.toString();
5326                    }
5327                    updatedPkg.pkg = pkg;
5328                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5329                } else {
5330                    // The current app on the system partition is better than
5331                    // what we have updated to on the data partition; switch
5332                    // back to the system partition version.
5333                    // At this point, its safely assumed that package installation for
5334                    // apps in system partition will go through. If not there won't be a working
5335                    // version of the app
5336                    // writer
5337                    synchronized (mPackages) {
5338                        // Just remove the loaded entries from package lists.
5339                        mPackages.remove(ps.name);
5340                    }
5341
5342                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5343                            + " reverting from " + ps.codePathString
5344                            + ": new version " + pkg.mVersionCode
5345                            + " better than installed " + ps.versionCode);
5346
5347                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5348                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5349                    synchronized (mInstallLock) {
5350                        args.cleanUpResourcesLI();
5351                    }
5352                    synchronized (mPackages) {
5353                        mSettings.enableSystemPackageLPw(ps.name);
5354                    }
5355                    updatedPkgBetter = true;
5356                }
5357            }
5358        }
5359
5360        if (updatedPkg != null) {
5361            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5362            // initially
5363            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5364
5365            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5366            // flag set initially
5367            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5368                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5369            }
5370        }
5371
5372        // Verify certificates against what was last scanned
5373        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5374
5375        /*
5376         * A new system app appeared, but we already had a non-system one of the
5377         * same name installed earlier.
5378         */
5379        boolean shouldHideSystemApp = false;
5380        if (updatedPkg == null && ps != null
5381                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5382            /*
5383             * Check to make sure the signatures match first. If they don't,
5384             * wipe the installed application and its data.
5385             */
5386            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5387                    != PackageManager.SIGNATURE_MATCH) {
5388                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5389                        + " signatures don't match existing userdata copy; removing");
5390                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5391                ps = null;
5392            } else {
5393                /*
5394                 * If the newly-added system app is an older version than the
5395                 * already installed version, hide it. It will be scanned later
5396                 * and re-added like an update.
5397                 */
5398                if (pkg.mVersionCode <= ps.versionCode) {
5399                    shouldHideSystemApp = true;
5400                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5401                            + " but new version " + pkg.mVersionCode + " better than installed "
5402                            + ps.versionCode + "; hiding system");
5403                } else {
5404                    /*
5405                     * The newly found system app is a newer version that the
5406                     * one previously installed. Simply remove the
5407                     * already-installed application and replace it with our own
5408                     * while keeping the application data.
5409                     */
5410                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5411                            + " reverting from " + ps.codePathString + ": new version "
5412                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5413                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5414                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5415                    synchronized (mInstallLock) {
5416                        args.cleanUpResourcesLI();
5417                    }
5418                }
5419            }
5420        }
5421
5422        // The apk is forward locked (not public) if its code and resources
5423        // are kept in different files. (except for app in either system or
5424        // vendor path).
5425        // TODO grab this value from PackageSettings
5426        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5427            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5428                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5429            }
5430        }
5431
5432        // TODO: extend to support forward-locked splits
5433        String resourcePath = null;
5434        String baseResourcePath = null;
5435        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5436            if (ps != null && ps.resourcePathString != null) {
5437                resourcePath = ps.resourcePathString;
5438                baseResourcePath = ps.resourcePathString;
5439            } else {
5440                // Should not happen at all. Just log an error.
5441                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5442            }
5443        } else {
5444            resourcePath = pkg.codePath;
5445            baseResourcePath = pkg.baseCodePath;
5446        }
5447
5448        // Set application objects path explicitly.
5449        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5450        pkg.applicationInfo.setCodePath(pkg.codePath);
5451        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5452        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5453        pkg.applicationInfo.setResourcePath(resourcePath);
5454        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5455        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5456
5457        // Note that we invoke the following method only if we are about to unpack an application
5458        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5459                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5460
5461        /*
5462         * If the system app should be overridden by a previously installed
5463         * data, hide the system app now and let the /data/app scan pick it up
5464         * again.
5465         */
5466        if (shouldHideSystemApp) {
5467            synchronized (mPackages) {
5468                /*
5469                 * We have to grant systems permissions before we hide, because
5470                 * grantPermissions will assume the package update is trying to
5471                 * expand its permissions.
5472                 */
5473                grantPermissionsLPw(pkg, true, pkg.packageName);
5474                mSettings.disableSystemPackageLPw(pkg.packageName);
5475            }
5476        }
5477
5478        return scannedPkg;
5479    }
5480
5481    private static String fixProcessName(String defProcessName,
5482            String processName, int uid) {
5483        if (processName == null) {
5484            return defProcessName;
5485        }
5486        return processName;
5487    }
5488
5489    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5490            throws PackageManagerException {
5491        if (pkgSetting.signatures.mSignatures != null) {
5492            // Already existing package. Make sure signatures match
5493            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5494                    == PackageManager.SIGNATURE_MATCH;
5495            if (!match) {
5496                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5497                        == PackageManager.SIGNATURE_MATCH;
5498            }
5499            if (!match) {
5500                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5501                        == PackageManager.SIGNATURE_MATCH;
5502            }
5503            if (!match) {
5504                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5505                        + pkg.packageName + " signatures do not match the "
5506                        + "previously installed version; ignoring!");
5507            }
5508        }
5509
5510        // Check for shared user signatures
5511        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5512            // Already existing package. Make sure signatures match
5513            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5514                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5515            if (!match) {
5516                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5517                        == PackageManager.SIGNATURE_MATCH;
5518            }
5519            if (!match) {
5520                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5521                        == PackageManager.SIGNATURE_MATCH;
5522            }
5523            if (!match) {
5524                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5525                        "Package " + pkg.packageName
5526                        + " has no signatures that match those in shared user "
5527                        + pkgSetting.sharedUser.name + "; ignoring!");
5528            }
5529        }
5530    }
5531
5532    /**
5533     * Enforces that only the system UID or root's UID can call a method exposed
5534     * via Binder.
5535     *
5536     * @param message used as message if SecurityException is thrown
5537     * @throws SecurityException if the caller is not system or root
5538     */
5539    private static final void enforceSystemOrRoot(String message) {
5540        final int uid = Binder.getCallingUid();
5541        if (uid != Process.SYSTEM_UID && uid != 0) {
5542            throw new SecurityException(message);
5543        }
5544    }
5545
5546    @Override
5547    public void performBootDexOpt() {
5548        enforceSystemOrRoot("Only the system can request dexopt be performed");
5549
5550        // Before everything else, see whether we need to fstrim.
5551        try {
5552            IMountService ms = PackageHelper.getMountService();
5553            if (ms != null) {
5554                final boolean isUpgrade = isUpgrade();
5555                boolean doTrim = isUpgrade;
5556                if (doTrim) {
5557                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5558                } else {
5559                    final long interval = android.provider.Settings.Global.getLong(
5560                            mContext.getContentResolver(),
5561                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5562                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5563                    if (interval > 0) {
5564                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5565                        if (timeSinceLast > interval) {
5566                            doTrim = true;
5567                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5568                                    + "; running immediately");
5569                        }
5570                    }
5571                }
5572                if (doTrim) {
5573                    if (!isFirstBoot()) {
5574                        try {
5575                            ActivityManagerNative.getDefault().showBootMessage(
5576                                    mContext.getResources().getString(
5577                                            R.string.android_upgrading_fstrim), true);
5578                        } catch (RemoteException e) {
5579                        }
5580                    }
5581                    ms.runMaintenance();
5582                }
5583            } else {
5584                Slog.e(TAG, "Mount service unavailable!");
5585            }
5586        } catch (RemoteException e) {
5587            // Can't happen; MountService is local
5588        }
5589
5590        final ArraySet<PackageParser.Package> pkgs;
5591        synchronized (mPackages) {
5592            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5593        }
5594
5595        if (pkgs != null) {
5596            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5597            // in case the device runs out of space.
5598            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5599            // Give priority to core apps.
5600            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5601                PackageParser.Package pkg = it.next();
5602                if (pkg.coreApp) {
5603                    if (DEBUG_DEXOPT) {
5604                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5605                    }
5606                    sortedPkgs.add(pkg);
5607                    it.remove();
5608                }
5609            }
5610            // Give priority to system apps that listen for pre boot complete.
5611            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5612            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5613            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5614                PackageParser.Package pkg = it.next();
5615                if (pkgNames.contains(pkg.packageName)) {
5616                    if (DEBUG_DEXOPT) {
5617                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5618                    }
5619                    sortedPkgs.add(pkg);
5620                    it.remove();
5621                }
5622            }
5623            // Give priority to system apps.
5624            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5625                PackageParser.Package pkg = it.next();
5626                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5627                    if (DEBUG_DEXOPT) {
5628                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5629                    }
5630                    sortedPkgs.add(pkg);
5631                    it.remove();
5632                }
5633            }
5634            // Give priority to updated system apps.
5635            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5636                PackageParser.Package pkg = it.next();
5637                if (pkg.isUpdatedSystemApp()) {
5638                    if (DEBUG_DEXOPT) {
5639                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5640                    }
5641                    sortedPkgs.add(pkg);
5642                    it.remove();
5643                }
5644            }
5645            // Give priority to apps that listen for boot complete.
5646            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5647            pkgNames = getPackageNamesForIntent(intent);
5648            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5649                PackageParser.Package pkg = it.next();
5650                if (pkgNames.contains(pkg.packageName)) {
5651                    if (DEBUG_DEXOPT) {
5652                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5653                    }
5654                    sortedPkgs.add(pkg);
5655                    it.remove();
5656                }
5657            }
5658            // Filter out packages that aren't recently used.
5659            filterRecentlyUsedApps(pkgs);
5660            // Add all remaining apps.
5661            for (PackageParser.Package pkg : pkgs) {
5662                if (DEBUG_DEXOPT) {
5663                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5664                }
5665                sortedPkgs.add(pkg);
5666            }
5667
5668            // If we want to be lazy, filter everything that wasn't recently used.
5669            if (mLazyDexOpt) {
5670                filterRecentlyUsedApps(sortedPkgs);
5671            }
5672
5673            int i = 0;
5674            int total = sortedPkgs.size();
5675            File dataDir = Environment.getDataDirectory();
5676            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5677            if (lowThreshold == 0) {
5678                throw new IllegalStateException("Invalid low memory threshold");
5679            }
5680            for (PackageParser.Package pkg : sortedPkgs) {
5681                long usableSpace = dataDir.getUsableSpace();
5682                if (usableSpace < lowThreshold) {
5683                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5684                    break;
5685                }
5686                performBootDexOpt(pkg, ++i, total);
5687            }
5688        }
5689    }
5690
5691    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5692        // Filter out packages that aren't recently used.
5693        //
5694        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5695        // should do a full dexopt.
5696        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5697            int total = pkgs.size();
5698            int skipped = 0;
5699            long now = System.currentTimeMillis();
5700            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5701                PackageParser.Package pkg = i.next();
5702                long then = pkg.mLastPackageUsageTimeInMills;
5703                if (then + mDexOptLRUThresholdInMills < now) {
5704                    if (DEBUG_DEXOPT) {
5705                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5706                              ((then == 0) ? "never" : new Date(then)));
5707                    }
5708                    i.remove();
5709                    skipped++;
5710                }
5711            }
5712            if (DEBUG_DEXOPT) {
5713                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5714            }
5715        }
5716    }
5717
5718    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5719        List<ResolveInfo> ris = null;
5720        try {
5721            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5722                    intent, null, 0, UserHandle.USER_OWNER);
5723        } catch (RemoteException e) {
5724        }
5725        ArraySet<String> pkgNames = new ArraySet<String>();
5726        if (ris != null) {
5727            for (ResolveInfo ri : ris) {
5728                pkgNames.add(ri.activityInfo.packageName);
5729            }
5730        }
5731        return pkgNames;
5732    }
5733
5734    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5735        if (DEBUG_DEXOPT) {
5736            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5737        }
5738        if (!isFirstBoot()) {
5739            try {
5740                ActivityManagerNative.getDefault().showBootMessage(
5741                        mContext.getResources().getString(R.string.android_upgrading_apk,
5742                                curr, total), true);
5743            } catch (RemoteException e) {
5744            }
5745        }
5746        PackageParser.Package p = pkg;
5747        synchronized (mInstallLock) {
5748            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5749                    false /* force dex */, false /* defer */, true /* include dependencies */);
5750        }
5751    }
5752
5753    @Override
5754    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5755        return performDexOpt(packageName, instructionSet, false);
5756    }
5757
5758    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5759        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5760        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5761        if (!dexopt && !updateUsage) {
5762            // We aren't going to dexopt or update usage, so bail early.
5763            return false;
5764        }
5765        PackageParser.Package p;
5766        final String targetInstructionSet;
5767        synchronized (mPackages) {
5768            p = mPackages.get(packageName);
5769            if (p == null) {
5770                return false;
5771            }
5772            if (updateUsage) {
5773                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5774            }
5775            mPackageUsage.write(false);
5776            if (!dexopt) {
5777                // We aren't going to dexopt, so bail early.
5778                return false;
5779            }
5780
5781            targetInstructionSet = instructionSet != null ? instructionSet :
5782                    getPrimaryInstructionSet(p.applicationInfo);
5783            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5784                return false;
5785            }
5786        }
5787
5788        synchronized (mInstallLock) {
5789            final String[] instructionSets = new String[] { targetInstructionSet };
5790            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5791                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5792            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5793        }
5794    }
5795
5796    public ArraySet<String> getPackagesThatNeedDexOpt() {
5797        ArraySet<String> pkgs = null;
5798        synchronized (mPackages) {
5799            for (PackageParser.Package p : mPackages.values()) {
5800                if (DEBUG_DEXOPT) {
5801                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5802                }
5803                if (!p.mDexOptPerformed.isEmpty()) {
5804                    continue;
5805                }
5806                if (pkgs == null) {
5807                    pkgs = new ArraySet<String>();
5808                }
5809                pkgs.add(p.packageName);
5810            }
5811        }
5812        return pkgs;
5813    }
5814
5815    public void shutdown() {
5816        mPackageUsage.write(true);
5817    }
5818
5819    @Override
5820    public void forceDexOpt(String packageName) {
5821        enforceSystemOrRoot("forceDexOpt");
5822
5823        PackageParser.Package pkg;
5824        synchronized (mPackages) {
5825            pkg = mPackages.get(packageName);
5826            if (pkg == null) {
5827                throw new IllegalArgumentException("Missing package: " + packageName);
5828            }
5829        }
5830
5831        synchronized (mInstallLock) {
5832            final String[] instructionSets = new String[] {
5833                    getPrimaryInstructionSet(pkg.applicationInfo) };
5834            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5835                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5836            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5837                throw new IllegalStateException("Failed to dexopt: " + res);
5838            }
5839        }
5840    }
5841
5842    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5843        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5844            Slog.w(TAG, "Unable to update from " + oldPkg.name
5845                    + " to " + newPkg.packageName
5846                    + ": old package not in system partition");
5847            return false;
5848        } else if (mPackages.get(oldPkg.name) != null) {
5849            Slog.w(TAG, "Unable to update from " + oldPkg.name
5850                    + " to " + newPkg.packageName
5851                    + ": old package still exists");
5852            return false;
5853        }
5854        return true;
5855    }
5856
5857    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5858        int[] users = sUserManager.getUserIds();
5859        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5860        if (res < 0) {
5861            return res;
5862        }
5863        for (int user : users) {
5864            if (user != 0) {
5865                res = mInstaller.createUserData(volumeUuid, packageName,
5866                        UserHandle.getUid(user, uid), user, seinfo);
5867                if (res < 0) {
5868                    return res;
5869                }
5870            }
5871        }
5872        return res;
5873    }
5874
5875    private int removeDataDirsLI(String volumeUuid, String packageName) {
5876        int[] users = sUserManager.getUserIds();
5877        int res = 0;
5878        for (int user : users) {
5879            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5880            if (resInner < 0) {
5881                res = resInner;
5882            }
5883        }
5884
5885        return res;
5886    }
5887
5888    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5889        int[] users = sUserManager.getUserIds();
5890        int res = 0;
5891        for (int user : users) {
5892            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5893            if (resInner < 0) {
5894                res = resInner;
5895            }
5896        }
5897        return res;
5898    }
5899
5900    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5901            PackageParser.Package changingLib) {
5902        if (file.path != null) {
5903            usesLibraryFiles.add(file.path);
5904            return;
5905        }
5906        PackageParser.Package p = mPackages.get(file.apk);
5907        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5908            // If we are doing this while in the middle of updating a library apk,
5909            // then we need to make sure to use that new apk for determining the
5910            // dependencies here.  (We haven't yet finished committing the new apk
5911            // to the package manager state.)
5912            if (p == null || p.packageName.equals(changingLib.packageName)) {
5913                p = changingLib;
5914            }
5915        }
5916        if (p != null) {
5917            usesLibraryFiles.addAll(p.getAllCodePaths());
5918        }
5919    }
5920
5921    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5922            PackageParser.Package changingLib) throws PackageManagerException {
5923        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5924            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5925            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5926            for (int i=0; i<N; i++) {
5927                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5928                if (file == null) {
5929                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5930                            "Package " + pkg.packageName + " requires unavailable shared library "
5931                            + pkg.usesLibraries.get(i) + "; failing!");
5932                }
5933                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5934            }
5935            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5936            for (int i=0; i<N; i++) {
5937                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5938                if (file == null) {
5939                    Slog.w(TAG, "Package " + pkg.packageName
5940                            + " desires unavailable shared library "
5941                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5942                } else {
5943                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5944                }
5945            }
5946            N = usesLibraryFiles.size();
5947            if (N > 0) {
5948                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5949            } else {
5950                pkg.usesLibraryFiles = null;
5951            }
5952        }
5953    }
5954
5955    private static boolean hasString(List<String> list, List<String> which) {
5956        if (list == null) {
5957            return false;
5958        }
5959        for (int i=list.size()-1; i>=0; i--) {
5960            for (int j=which.size()-1; j>=0; j--) {
5961                if (which.get(j).equals(list.get(i))) {
5962                    return true;
5963                }
5964            }
5965        }
5966        return false;
5967    }
5968
5969    private void updateAllSharedLibrariesLPw() {
5970        for (PackageParser.Package pkg : mPackages.values()) {
5971            try {
5972                updateSharedLibrariesLPw(pkg, null);
5973            } catch (PackageManagerException e) {
5974                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5975            }
5976        }
5977    }
5978
5979    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5980            PackageParser.Package changingPkg) {
5981        ArrayList<PackageParser.Package> res = null;
5982        for (PackageParser.Package pkg : mPackages.values()) {
5983            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5984                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5985                if (res == null) {
5986                    res = new ArrayList<PackageParser.Package>();
5987                }
5988                res.add(pkg);
5989                try {
5990                    updateSharedLibrariesLPw(pkg, changingPkg);
5991                } catch (PackageManagerException e) {
5992                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5993                }
5994            }
5995        }
5996        return res;
5997    }
5998
5999    /**
6000     * Derive the value of the {@code cpuAbiOverride} based on the provided
6001     * value and an optional stored value from the package settings.
6002     */
6003    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6004        String cpuAbiOverride = null;
6005
6006        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6007            cpuAbiOverride = null;
6008        } else if (abiOverride != null) {
6009            cpuAbiOverride = abiOverride;
6010        } else if (settings != null) {
6011            cpuAbiOverride = settings.cpuAbiOverrideString;
6012        }
6013
6014        return cpuAbiOverride;
6015    }
6016
6017    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6018            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6019        boolean success = false;
6020        try {
6021            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6022                    currentTime, user);
6023            success = true;
6024            return res;
6025        } finally {
6026            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6027                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6028            }
6029        }
6030    }
6031
6032    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6033            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6034        final File scanFile = new File(pkg.codePath);
6035        if (pkg.applicationInfo.getCodePath() == null ||
6036                pkg.applicationInfo.getResourcePath() == null) {
6037            // Bail out. The resource and code paths haven't been set.
6038            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6039                    "Code and resource paths haven't been set correctly");
6040        }
6041
6042        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6043            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6044        } else {
6045            // Only allow system apps to be flagged as core apps.
6046            pkg.coreApp = false;
6047        }
6048
6049        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6050            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6051        }
6052
6053        if (mCustomResolverComponentName != null &&
6054                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6055            setUpCustomResolverActivity(pkg);
6056        }
6057
6058        if (pkg.packageName.equals("android")) {
6059            synchronized (mPackages) {
6060                if (mAndroidApplication != null) {
6061                    Slog.w(TAG, "*************************************************");
6062                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6063                    Slog.w(TAG, " file=" + scanFile);
6064                    Slog.w(TAG, "*************************************************");
6065                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6066                            "Core android package being redefined.  Skipping.");
6067                }
6068
6069                // Set up information for our fall-back user intent resolution activity.
6070                mPlatformPackage = pkg;
6071                pkg.mVersionCode = mSdkVersion;
6072                mAndroidApplication = pkg.applicationInfo;
6073
6074                if (!mResolverReplaced) {
6075                    mResolveActivity.applicationInfo = mAndroidApplication;
6076                    mResolveActivity.name = ResolverActivity.class.getName();
6077                    mResolveActivity.packageName = mAndroidApplication.packageName;
6078                    mResolveActivity.processName = "system:ui";
6079                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6080                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6081                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6082                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6083                    mResolveActivity.exported = true;
6084                    mResolveActivity.enabled = true;
6085                    mResolveInfo.activityInfo = mResolveActivity;
6086                    mResolveInfo.priority = 0;
6087                    mResolveInfo.preferredOrder = 0;
6088                    mResolveInfo.match = 0;
6089                    mResolveComponentName = new ComponentName(
6090                            mAndroidApplication.packageName, mResolveActivity.name);
6091                }
6092            }
6093        }
6094
6095        if (DEBUG_PACKAGE_SCANNING) {
6096            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6097                Log.d(TAG, "Scanning package " + pkg.packageName);
6098        }
6099
6100        if (mPackages.containsKey(pkg.packageName)
6101                || mSharedLibraries.containsKey(pkg.packageName)) {
6102            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6103                    "Application package " + pkg.packageName
6104                    + " already installed.  Skipping duplicate.");
6105        }
6106
6107        // If we're only installing presumed-existing packages, require that the
6108        // scanned APK is both already known and at the path previously established
6109        // for it.  Previously unknown packages we pick up normally, but if we have an
6110        // a priori expectation about this package's install presence, enforce it.
6111        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6112            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6113            if (known != null) {
6114                if (DEBUG_PACKAGE_SCANNING) {
6115                    Log.d(TAG, "Examining " + pkg.codePath
6116                            + " and requiring known paths " + known.codePathString
6117                            + " & " + known.resourcePathString);
6118                }
6119                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6120                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6121                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6122                            "Application package " + pkg.packageName
6123                            + " found at " + pkg.applicationInfo.getCodePath()
6124                            + " but expected at " + known.codePathString + "; ignoring.");
6125                }
6126            }
6127        }
6128
6129        // Initialize package source and resource directories
6130        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6131        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6132
6133        SharedUserSetting suid = null;
6134        PackageSetting pkgSetting = null;
6135
6136        if (!isSystemApp(pkg)) {
6137            // Only system apps can use these features.
6138            pkg.mOriginalPackages = null;
6139            pkg.mRealPackage = null;
6140            pkg.mAdoptPermissions = null;
6141        }
6142
6143        // writer
6144        synchronized (mPackages) {
6145            if (pkg.mSharedUserId != null) {
6146                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6147                if (suid == null) {
6148                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6149                            "Creating application package " + pkg.packageName
6150                            + " for shared user failed");
6151                }
6152                if (DEBUG_PACKAGE_SCANNING) {
6153                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6154                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6155                                + "): packages=" + suid.packages);
6156                }
6157            }
6158
6159            // Check if we are renaming from an original package name.
6160            PackageSetting origPackage = null;
6161            String realName = null;
6162            if (pkg.mOriginalPackages != null) {
6163                // This package may need to be renamed to a previously
6164                // installed name.  Let's check on that...
6165                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6166                if (pkg.mOriginalPackages.contains(renamed)) {
6167                    // This package had originally been installed as the
6168                    // original name, and we have already taken care of
6169                    // transitioning to the new one.  Just update the new
6170                    // one to continue using the old name.
6171                    realName = pkg.mRealPackage;
6172                    if (!pkg.packageName.equals(renamed)) {
6173                        // Callers into this function may have already taken
6174                        // care of renaming the package; only do it here if
6175                        // it is not already done.
6176                        pkg.setPackageName(renamed);
6177                    }
6178
6179                } else {
6180                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6181                        if ((origPackage = mSettings.peekPackageLPr(
6182                                pkg.mOriginalPackages.get(i))) != null) {
6183                            // We do have the package already installed under its
6184                            // original name...  should we use it?
6185                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6186                                // New package is not compatible with original.
6187                                origPackage = null;
6188                                continue;
6189                            } else if (origPackage.sharedUser != null) {
6190                                // Make sure uid is compatible between packages.
6191                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6192                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6193                                            + " to " + pkg.packageName + ": old uid "
6194                                            + origPackage.sharedUser.name
6195                                            + " differs from " + pkg.mSharedUserId);
6196                                    origPackage = null;
6197                                    continue;
6198                                }
6199                            } else {
6200                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6201                                        + pkg.packageName + " to old name " + origPackage.name);
6202                            }
6203                            break;
6204                        }
6205                    }
6206                }
6207            }
6208
6209            if (mTransferedPackages.contains(pkg.packageName)) {
6210                Slog.w(TAG, "Package " + pkg.packageName
6211                        + " was transferred to another, but its .apk remains");
6212            }
6213
6214            // Just create the setting, don't add it yet. For already existing packages
6215            // the PkgSetting exists already and doesn't have to be created.
6216            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6217                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6218                    pkg.applicationInfo.primaryCpuAbi,
6219                    pkg.applicationInfo.secondaryCpuAbi,
6220                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6221                    user, false);
6222            if (pkgSetting == null) {
6223                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6224                        "Creating application package " + pkg.packageName + " failed");
6225            }
6226
6227            if (pkgSetting.origPackage != null) {
6228                // If we are first transitioning from an original package,
6229                // fix up the new package's name now.  We need to do this after
6230                // looking up the package under its new name, so getPackageLP
6231                // can take care of fiddling things correctly.
6232                pkg.setPackageName(origPackage.name);
6233
6234                // File a report about this.
6235                String msg = "New package " + pkgSetting.realName
6236                        + " renamed to replace old package " + pkgSetting.name;
6237                reportSettingsProblem(Log.WARN, msg);
6238
6239                // Make a note of it.
6240                mTransferedPackages.add(origPackage.name);
6241
6242                // No longer need to retain this.
6243                pkgSetting.origPackage = null;
6244            }
6245
6246            if (realName != null) {
6247                // Make a note of it.
6248                mTransferedPackages.add(pkg.packageName);
6249            }
6250
6251            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6252                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6253            }
6254
6255            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6256                // Check all shared libraries and map to their actual file path.
6257                // We only do this here for apps not on a system dir, because those
6258                // are the only ones that can fail an install due to this.  We
6259                // will take care of the system apps by updating all of their
6260                // library paths after the scan is done.
6261                updateSharedLibrariesLPw(pkg, null);
6262            }
6263
6264            if (mFoundPolicyFile) {
6265                SELinuxMMAC.assignSeinfoValue(pkg);
6266            }
6267
6268            pkg.applicationInfo.uid = pkgSetting.appId;
6269            pkg.mExtras = pkgSetting;
6270            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6271                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6272                    // We just determined the app is signed correctly, so bring
6273                    // over the latest parsed certs.
6274                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6275                } else {
6276                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6277                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6278                                "Package " + pkg.packageName + " upgrade keys do not match the "
6279                                + "previously installed version");
6280                    } else {
6281                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6282                        String msg = "System package " + pkg.packageName
6283                            + " signature changed; retaining data.";
6284                        reportSettingsProblem(Log.WARN, msg);
6285                    }
6286                }
6287            } else {
6288                try {
6289                    verifySignaturesLP(pkgSetting, pkg);
6290                    // We just determined the app is signed correctly, so bring
6291                    // over the latest parsed certs.
6292                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6293                } catch (PackageManagerException e) {
6294                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6295                        throw e;
6296                    }
6297                    // The signature has changed, but this package is in the system
6298                    // image...  let's recover!
6299                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6300                    // However...  if this package is part of a shared user, but it
6301                    // doesn't match the signature of the shared user, let's fail.
6302                    // What this means is that you can't change the signatures
6303                    // associated with an overall shared user, which doesn't seem all
6304                    // that unreasonable.
6305                    if (pkgSetting.sharedUser != null) {
6306                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6307                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6308                            throw new PackageManagerException(
6309                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6310                                            "Signature mismatch for shared user : "
6311                                            + pkgSetting.sharedUser);
6312                        }
6313                    }
6314                    // File a report about this.
6315                    String msg = "System package " + pkg.packageName
6316                        + " signature changed; retaining data.";
6317                    reportSettingsProblem(Log.WARN, msg);
6318                }
6319            }
6320            // Verify that this new package doesn't have any content providers
6321            // that conflict with existing packages.  Only do this if the
6322            // package isn't already installed, since we don't want to break
6323            // things that are installed.
6324            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6325                final int N = pkg.providers.size();
6326                int i;
6327                for (i=0; i<N; i++) {
6328                    PackageParser.Provider p = pkg.providers.get(i);
6329                    if (p.info.authority != null) {
6330                        String names[] = p.info.authority.split(";");
6331                        for (int j = 0; j < names.length; j++) {
6332                            if (mProvidersByAuthority.containsKey(names[j])) {
6333                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6334                                final String otherPackageName =
6335                                        ((other != null && other.getComponentName() != null) ?
6336                                                other.getComponentName().getPackageName() : "?");
6337                                throw new PackageManagerException(
6338                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6339                                                "Can't install because provider name " + names[j]
6340                                                + " (in package " + pkg.applicationInfo.packageName
6341                                                + ") is already used by " + otherPackageName);
6342                            }
6343                        }
6344                    }
6345                }
6346            }
6347
6348            if (pkg.mAdoptPermissions != null) {
6349                // This package wants to adopt ownership of permissions from
6350                // another package.
6351                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6352                    final String origName = pkg.mAdoptPermissions.get(i);
6353                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6354                    if (orig != null) {
6355                        if (verifyPackageUpdateLPr(orig, pkg)) {
6356                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6357                                    + pkg.packageName);
6358                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6359                        }
6360                    }
6361                }
6362            }
6363        }
6364
6365        final String pkgName = pkg.packageName;
6366
6367        final long scanFileTime = scanFile.lastModified();
6368        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6369        pkg.applicationInfo.processName = fixProcessName(
6370                pkg.applicationInfo.packageName,
6371                pkg.applicationInfo.processName,
6372                pkg.applicationInfo.uid);
6373
6374        File dataPath;
6375        if (mPlatformPackage == pkg) {
6376            // The system package is special.
6377            dataPath = new File(Environment.getDataDirectory(), "system");
6378
6379            pkg.applicationInfo.dataDir = dataPath.getPath();
6380
6381        } else {
6382            // This is a normal package, need to make its data directory.
6383            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6384                    UserHandle.USER_OWNER);
6385
6386            boolean uidError = false;
6387            if (dataPath.exists()) {
6388                int currentUid = 0;
6389                try {
6390                    StructStat stat = Os.stat(dataPath.getPath());
6391                    currentUid = stat.st_uid;
6392                } catch (ErrnoException e) {
6393                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6394                }
6395
6396                // If we have mismatched owners for the data path, we have a problem.
6397                if (currentUid != pkg.applicationInfo.uid) {
6398                    boolean recovered = false;
6399                    if (currentUid == 0) {
6400                        // The directory somehow became owned by root.  Wow.
6401                        // This is probably because the system was stopped while
6402                        // installd was in the middle of messing with its libs
6403                        // directory.  Ask installd to fix that.
6404                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6405                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6406                        if (ret >= 0) {
6407                            recovered = true;
6408                            String msg = "Package " + pkg.packageName
6409                                    + " unexpectedly changed to uid 0; recovered to " +
6410                                    + pkg.applicationInfo.uid;
6411                            reportSettingsProblem(Log.WARN, msg);
6412                        }
6413                    }
6414                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6415                            || (scanFlags&SCAN_BOOTING) != 0)) {
6416                        // If this is a system app, we can at least delete its
6417                        // current data so the application will still work.
6418                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6419                        if (ret >= 0) {
6420                            // TODO: Kill the processes first
6421                            // Old data gone!
6422                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6423                                    ? "System package " : "Third party package ";
6424                            String msg = prefix + pkg.packageName
6425                                    + " has changed from uid: "
6426                                    + currentUid + " to "
6427                                    + pkg.applicationInfo.uid + "; old data erased";
6428                            reportSettingsProblem(Log.WARN, msg);
6429                            recovered = true;
6430
6431                            // And now re-install the app.
6432                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6433                                    pkg.applicationInfo.seinfo);
6434                            if (ret == -1) {
6435                                // Ack should not happen!
6436                                msg = prefix + pkg.packageName
6437                                        + " could not have data directory re-created after delete.";
6438                                reportSettingsProblem(Log.WARN, msg);
6439                                throw new PackageManagerException(
6440                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6441                            }
6442                        }
6443                        if (!recovered) {
6444                            mHasSystemUidErrors = true;
6445                        }
6446                    } else if (!recovered) {
6447                        // If we allow this install to proceed, we will be broken.
6448                        // Abort, abort!
6449                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6450                                "scanPackageLI");
6451                    }
6452                    if (!recovered) {
6453                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6454                            + pkg.applicationInfo.uid + "/fs_"
6455                            + currentUid;
6456                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6457                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6458                        String msg = "Package " + pkg.packageName
6459                                + " has mismatched uid: "
6460                                + currentUid + " on disk, "
6461                                + pkg.applicationInfo.uid + " in settings";
6462                        // writer
6463                        synchronized (mPackages) {
6464                            mSettings.mReadMessages.append(msg);
6465                            mSettings.mReadMessages.append('\n');
6466                            uidError = true;
6467                            if (!pkgSetting.uidError) {
6468                                reportSettingsProblem(Log.ERROR, msg);
6469                            }
6470                        }
6471                    }
6472                }
6473                pkg.applicationInfo.dataDir = dataPath.getPath();
6474                if (mShouldRestoreconData) {
6475                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6476                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6477                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6478                }
6479            } else {
6480                if (DEBUG_PACKAGE_SCANNING) {
6481                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6482                        Log.v(TAG, "Want this data dir: " + dataPath);
6483                }
6484                //invoke installer to do the actual installation
6485                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6486                        pkg.applicationInfo.seinfo);
6487                if (ret < 0) {
6488                    // Error from installer
6489                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6490                            "Unable to create data dirs [errorCode=" + ret + "]");
6491                }
6492
6493                if (dataPath.exists()) {
6494                    pkg.applicationInfo.dataDir = dataPath.getPath();
6495                } else {
6496                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6497                    pkg.applicationInfo.dataDir = null;
6498                }
6499            }
6500
6501            pkgSetting.uidError = uidError;
6502        }
6503
6504        final String path = scanFile.getPath();
6505        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6506
6507        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6508            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6509
6510            // Some system apps still use directory structure for native libraries
6511            // in which case we might end up not detecting abi solely based on apk
6512            // structure. Try to detect abi based on directory structure.
6513            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6514                    pkg.applicationInfo.primaryCpuAbi == null) {
6515                setBundledAppAbisAndRoots(pkg, pkgSetting);
6516                setNativeLibraryPaths(pkg);
6517            }
6518
6519        } else {
6520            if ((scanFlags & SCAN_MOVE) != 0) {
6521                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6522                // but we already have this packages package info in the PackageSetting. We just
6523                // use that and derive the native library path based on the new codepath.
6524                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6525                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6526            }
6527
6528            // Set native library paths again. For moves, the path will be updated based on the
6529            // ABIs we've determined above. For non-moves, the path will be updated based on the
6530            // ABIs we determined during compilation, but the path will depend on the final
6531            // package path (after the rename away from the stage path).
6532            setNativeLibraryPaths(pkg);
6533        }
6534
6535        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6536        final int[] userIds = sUserManager.getUserIds();
6537        synchronized (mInstallLock) {
6538            // Create a native library symlink only if we have native libraries
6539            // and if the native libraries are 32 bit libraries. We do not provide
6540            // this symlink for 64 bit libraries.
6541            if (pkg.applicationInfo.primaryCpuAbi != null &&
6542                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6543                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6544                for (int userId : userIds) {
6545                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6546                            nativeLibPath, userId) < 0) {
6547                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6548                                "Failed linking native library dir (user=" + userId + ")");
6549                    }
6550                }
6551            }
6552        }
6553
6554        // This is a special case for the "system" package, where the ABI is
6555        // dictated by the zygote configuration (and init.rc). We should keep track
6556        // of this ABI so that we can deal with "normal" applications that run under
6557        // the same UID correctly.
6558        if (mPlatformPackage == pkg) {
6559            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6560                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6561        }
6562
6563        // If there's a mismatch between the abi-override in the package setting
6564        // and the abiOverride specified for the install. Warn about this because we
6565        // would've already compiled the app without taking the package setting into
6566        // account.
6567        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6568            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6569                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6570                        " for package: " + pkg.packageName);
6571            }
6572        }
6573
6574        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6575        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6576        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6577
6578        // Copy the derived override back to the parsed package, so that we can
6579        // update the package settings accordingly.
6580        pkg.cpuAbiOverride = cpuAbiOverride;
6581
6582        if (DEBUG_ABI_SELECTION) {
6583            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6584                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6585                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6586        }
6587
6588        // Push the derived path down into PackageSettings so we know what to
6589        // clean up at uninstall time.
6590        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6591
6592        if (DEBUG_ABI_SELECTION) {
6593            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6594                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6595                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6596        }
6597
6598        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6599            // We don't do this here during boot because we can do it all
6600            // at once after scanning all existing packages.
6601            //
6602            // We also do this *before* we perform dexopt on this package, so that
6603            // we can avoid redundant dexopts, and also to make sure we've got the
6604            // code and package path correct.
6605            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6606                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6607        }
6608
6609        if ((scanFlags & SCAN_NO_DEX) == 0) {
6610            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6611                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6612            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6613                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6614            }
6615        }
6616        if (mFactoryTest && pkg.requestedPermissions.contains(
6617                android.Manifest.permission.FACTORY_TEST)) {
6618            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6619        }
6620
6621        ArrayList<PackageParser.Package> clientLibPkgs = null;
6622
6623        // writer
6624        synchronized (mPackages) {
6625            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6626                // Only system apps can add new shared libraries.
6627                if (pkg.libraryNames != null) {
6628                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6629                        String name = pkg.libraryNames.get(i);
6630                        boolean allowed = false;
6631                        if (pkg.isUpdatedSystemApp()) {
6632                            // New library entries can only be added through the
6633                            // system image.  This is important to get rid of a lot
6634                            // of nasty edge cases: for example if we allowed a non-
6635                            // system update of the app to add a library, then uninstalling
6636                            // the update would make the library go away, and assumptions
6637                            // we made such as through app install filtering would now
6638                            // have allowed apps on the device which aren't compatible
6639                            // with it.  Better to just have the restriction here, be
6640                            // conservative, and create many fewer cases that can negatively
6641                            // impact the user experience.
6642                            final PackageSetting sysPs = mSettings
6643                                    .getDisabledSystemPkgLPr(pkg.packageName);
6644                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6645                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6646                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6647                                        allowed = true;
6648                                        allowed = true;
6649                                        break;
6650                                    }
6651                                }
6652                            }
6653                        } else {
6654                            allowed = true;
6655                        }
6656                        if (allowed) {
6657                            if (!mSharedLibraries.containsKey(name)) {
6658                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6659                            } else if (!name.equals(pkg.packageName)) {
6660                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6661                                        + name + " already exists; skipping");
6662                            }
6663                        } else {
6664                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6665                                    + name + " that is not declared on system image; skipping");
6666                        }
6667                    }
6668                    if ((scanFlags&SCAN_BOOTING) == 0) {
6669                        // If we are not booting, we need to update any applications
6670                        // that are clients of our shared library.  If we are booting,
6671                        // this will all be done once the scan is complete.
6672                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6673                    }
6674                }
6675            }
6676        }
6677
6678        // We also need to dexopt any apps that are dependent on this library.  Note that
6679        // if these fail, we should abort the install since installing the library will
6680        // result in some apps being broken.
6681        if (clientLibPkgs != null) {
6682            if ((scanFlags & SCAN_NO_DEX) == 0) {
6683                for (int i = 0; i < clientLibPkgs.size(); i++) {
6684                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6685                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6686                            null /* instruction sets */, forceDex,
6687                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6688                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6689                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6690                                "scanPackageLI failed to dexopt clientLibPkgs");
6691                    }
6692                }
6693            }
6694        }
6695
6696        // Also need to kill any apps that are dependent on the library.
6697        if (clientLibPkgs != null) {
6698            for (int i=0; i<clientLibPkgs.size(); i++) {
6699                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6700                killApplication(clientPkg.applicationInfo.packageName,
6701                        clientPkg.applicationInfo.uid, "update lib");
6702            }
6703        }
6704
6705        // Make sure we're not adding any bogus keyset info
6706        KeySetManagerService ksms = mSettings.mKeySetManagerService;
6707        ksms.assertScannedPackageValid(pkg);
6708
6709        // writer
6710        synchronized (mPackages) {
6711            // We don't expect installation to fail beyond this point
6712
6713            // Add the new setting to mSettings
6714            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6715            // Add the new setting to mPackages
6716            mPackages.put(pkg.applicationInfo.packageName, pkg);
6717            // Make sure we don't accidentally delete its data.
6718            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6719            while (iter.hasNext()) {
6720                PackageCleanItem item = iter.next();
6721                if (pkgName.equals(item.packageName)) {
6722                    iter.remove();
6723                }
6724            }
6725
6726            // Take care of first install / last update times.
6727            if (currentTime != 0) {
6728                if (pkgSetting.firstInstallTime == 0) {
6729                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6730                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6731                    pkgSetting.lastUpdateTime = currentTime;
6732                }
6733            } else if (pkgSetting.firstInstallTime == 0) {
6734                // We need *something*.  Take time time stamp of the file.
6735                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6736            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6737                if (scanFileTime != pkgSetting.timeStamp) {
6738                    // A package on the system image has changed; consider this
6739                    // to be an update.
6740                    pkgSetting.lastUpdateTime = scanFileTime;
6741                }
6742            }
6743
6744            // Add the package's KeySets to the global KeySetManagerService
6745            ksms.addScannedPackageLPw(pkg);
6746
6747            int N = pkg.providers.size();
6748            StringBuilder r = null;
6749            int i;
6750            for (i=0; i<N; i++) {
6751                PackageParser.Provider p = pkg.providers.get(i);
6752                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6753                        p.info.processName, pkg.applicationInfo.uid);
6754                mProviders.addProvider(p);
6755                p.syncable = p.info.isSyncable;
6756                if (p.info.authority != null) {
6757                    String names[] = p.info.authority.split(";");
6758                    p.info.authority = null;
6759                    for (int j = 0; j < names.length; j++) {
6760                        if (j == 1 && p.syncable) {
6761                            // We only want the first authority for a provider to possibly be
6762                            // syncable, so if we already added this provider using a different
6763                            // authority clear the syncable flag. We copy the provider before
6764                            // changing it because the mProviders object contains a reference
6765                            // to a provider that we don't want to change.
6766                            // Only do this for the second authority since the resulting provider
6767                            // object can be the same for all future authorities for this provider.
6768                            p = new PackageParser.Provider(p);
6769                            p.syncable = false;
6770                        }
6771                        if (!mProvidersByAuthority.containsKey(names[j])) {
6772                            mProvidersByAuthority.put(names[j], p);
6773                            if (p.info.authority == null) {
6774                                p.info.authority = names[j];
6775                            } else {
6776                                p.info.authority = p.info.authority + ";" + names[j];
6777                            }
6778                            if (DEBUG_PACKAGE_SCANNING) {
6779                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6780                                    Log.d(TAG, "Registered content provider: " + names[j]
6781                                            + ", className = " + p.info.name + ", isSyncable = "
6782                                            + p.info.isSyncable);
6783                            }
6784                        } else {
6785                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6786                            Slog.w(TAG, "Skipping provider name " + names[j] +
6787                                    " (in package " + pkg.applicationInfo.packageName +
6788                                    "): name already used by "
6789                                    + ((other != null && other.getComponentName() != null)
6790                                            ? other.getComponentName().getPackageName() : "?"));
6791                        }
6792                    }
6793                }
6794                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6795                    if (r == null) {
6796                        r = new StringBuilder(256);
6797                    } else {
6798                        r.append(' ');
6799                    }
6800                    r.append(p.info.name);
6801                }
6802            }
6803            if (r != null) {
6804                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6805            }
6806
6807            N = pkg.services.size();
6808            r = null;
6809            for (i=0; i<N; i++) {
6810                PackageParser.Service s = pkg.services.get(i);
6811                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6812                        s.info.processName, pkg.applicationInfo.uid);
6813                mServices.addService(s);
6814                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6815                    if (r == null) {
6816                        r = new StringBuilder(256);
6817                    } else {
6818                        r.append(' ');
6819                    }
6820                    r.append(s.info.name);
6821                }
6822            }
6823            if (r != null) {
6824                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6825            }
6826
6827            N = pkg.receivers.size();
6828            r = null;
6829            for (i=0; i<N; i++) {
6830                PackageParser.Activity a = pkg.receivers.get(i);
6831                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6832                        a.info.processName, pkg.applicationInfo.uid);
6833                mReceivers.addActivity(a, "receiver");
6834                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6835                    if (r == null) {
6836                        r = new StringBuilder(256);
6837                    } else {
6838                        r.append(' ');
6839                    }
6840                    r.append(a.info.name);
6841                }
6842            }
6843            if (r != null) {
6844                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6845            }
6846
6847            N = pkg.activities.size();
6848            r = null;
6849            for (i=0; i<N; i++) {
6850                PackageParser.Activity a = pkg.activities.get(i);
6851                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6852                        a.info.processName, pkg.applicationInfo.uid);
6853                mActivities.addActivity(a, "activity");
6854                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6855                    if (r == null) {
6856                        r = new StringBuilder(256);
6857                    } else {
6858                        r.append(' ');
6859                    }
6860                    r.append(a.info.name);
6861                }
6862            }
6863            if (r != null) {
6864                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6865            }
6866
6867            N = pkg.permissionGroups.size();
6868            r = null;
6869            for (i=0; i<N; i++) {
6870                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6871                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6872                if (cur == null) {
6873                    mPermissionGroups.put(pg.info.name, pg);
6874                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6875                        if (r == null) {
6876                            r = new StringBuilder(256);
6877                        } else {
6878                            r.append(' ');
6879                        }
6880                        r.append(pg.info.name);
6881                    }
6882                } else {
6883                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6884                            + pg.info.packageName + " ignored: original from "
6885                            + cur.info.packageName);
6886                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6887                        if (r == null) {
6888                            r = new StringBuilder(256);
6889                        } else {
6890                            r.append(' ');
6891                        }
6892                        r.append("DUP:");
6893                        r.append(pg.info.name);
6894                    }
6895                }
6896            }
6897            if (r != null) {
6898                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6899            }
6900
6901            N = pkg.permissions.size();
6902            r = null;
6903            for (i=0; i<N; i++) {
6904                PackageParser.Permission p = pkg.permissions.get(i);
6905
6906                // Now that permission groups have a special meaning, we ignore permission
6907                // groups for legacy apps to prevent unexpected behavior. In particular,
6908                // permissions for one app being granted to someone just becuase they happen
6909                // to be in a group defined by another app (before this had no implications).
6910                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6911                    p.group = mPermissionGroups.get(p.info.group);
6912                    // Warn for a permission in an unknown group.
6913                    if (p.info.group != null && p.group == null) {
6914                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6915                                + p.info.packageName + " in an unknown group " + p.info.group);
6916                    }
6917                }
6918
6919                ArrayMap<String, BasePermission> permissionMap =
6920                        p.tree ? mSettings.mPermissionTrees
6921                                : mSettings.mPermissions;
6922                BasePermission bp = permissionMap.get(p.info.name);
6923
6924                // Allow system apps to redefine non-system permissions
6925                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6926                    final boolean currentOwnerIsSystem = (bp.perm != null
6927                            && isSystemApp(bp.perm.owner));
6928                    if (isSystemApp(p.owner)) {
6929                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6930                            // It's a built-in permission and no owner, take ownership now
6931                            bp.packageSetting = pkgSetting;
6932                            bp.perm = p;
6933                            bp.uid = pkg.applicationInfo.uid;
6934                            bp.sourcePackage = p.info.packageName;
6935                        } else if (!currentOwnerIsSystem) {
6936                            String msg = "New decl " + p.owner + " of permission  "
6937                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6938                            reportSettingsProblem(Log.WARN, msg);
6939                            bp = null;
6940                        }
6941                    }
6942                }
6943
6944                if (bp == null) {
6945                    bp = new BasePermission(p.info.name, p.info.packageName,
6946                            BasePermission.TYPE_NORMAL);
6947                    permissionMap.put(p.info.name, bp);
6948                }
6949
6950                if (bp.perm == null) {
6951                    if (bp.sourcePackage == null
6952                            || bp.sourcePackage.equals(p.info.packageName)) {
6953                        BasePermission tree = findPermissionTreeLP(p.info.name);
6954                        if (tree == null
6955                                || tree.sourcePackage.equals(p.info.packageName)) {
6956                            bp.packageSetting = pkgSetting;
6957                            bp.perm = p;
6958                            bp.uid = pkg.applicationInfo.uid;
6959                            bp.sourcePackage = p.info.packageName;
6960                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6961                                if (r == null) {
6962                                    r = new StringBuilder(256);
6963                                } else {
6964                                    r.append(' ');
6965                                }
6966                                r.append(p.info.name);
6967                            }
6968                        } else {
6969                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6970                                    + p.info.packageName + " ignored: base tree "
6971                                    + tree.name + " is from package "
6972                                    + tree.sourcePackage);
6973                        }
6974                    } else {
6975                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6976                                + p.info.packageName + " ignored: original from "
6977                                + bp.sourcePackage);
6978                    }
6979                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6980                    if (r == null) {
6981                        r = new StringBuilder(256);
6982                    } else {
6983                        r.append(' ');
6984                    }
6985                    r.append("DUP:");
6986                    r.append(p.info.name);
6987                }
6988                if (bp.perm == p) {
6989                    bp.protectionLevel = p.info.protectionLevel;
6990                }
6991            }
6992
6993            if (r != null) {
6994                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6995            }
6996
6997            N = pkg.instrumentation.size();
6998            r = null;
6999            for (i=0; i<N; i++) {
7000                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7001                a.info.packageName = pkg.applicationInfo.packageName;
7002                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7003                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7004                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7005                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7006                a.info.dataDir = pkg.applicationInfo.dataDir;
7007
7008                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7009                // need other information about the application, like the ABI and what not ?
7010                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7011                mInstrumentation.put(a.getComponentName(), a);
7012                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7013                    if (r == null) {
7014                        r = new StringBuilder(256);
7015                    } else {
7016                        r.append(' ');
7017                    }
7018                    r.append(a.info.name);
7019                }
7020            }
7021            if (r != null) {
7022                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7023            }
7024
7025            if (pkg.protectedBroadcasts != null) {
7026                N = pkg.protectedBroadcasts.size();
7027                for (i=0; i<N; i++) {
7028                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7029                }
7030            }
7031
7032            pkgSetting.setTimeStamp(scanFileTime);
7033
7034            // Create idmap files for pairs of (packages, overlay packages).
7035            // Note: "android", ie framework-res.apk, is handled by native layers.
7036            if (pkg.mOverlayTarget != null) {
7037                // This is an overlay package.
7038                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7039                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7040                        mOverlays.put(pkg.mOverlayTarget,
7041                                new ArrayMap<String, PackageParser.Package>());
7042                    }
7043                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7044                    map.put(pkg.packageName, pkg);
7045                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7046                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7047                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7048                                "scanPackageLI failed to createIdmap");
7049                    }
7050                }
7051            } else if (mOverlays.containsKey(pkg.packageName) &&
7052                    !pkg.packageName.equals("android")) {
7053                // This is a regular package, with one or more known overlay packages.
7054                createIdmapsForPackageLI(pkg);
7055            }
7056        }
7057
7058        return pkg;
7059    }
7060
7061    /**
7062     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7063     * is derived purely on the basis of the contents of {@code scanFile} and
7064     * {@code cpuAbiOverride}.
7065     *
7066     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7067     */
7068    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7069                                 String cpuAbiOverride, boolean extractLibs)
7070            throws PackageManagerException {
7071        // TODO: We can probably be smarter about this stuff. For installed apps,
7072        // we can calculate this information at install time once and for all. For
7073        // system apps, we can probably assume that this information doesn't change
7074        // after the first boot scan. As things stand, we do lots of unnecessary work.
7075
7076        // Give ourselves some initial paths; we'll come back for another
7077        // pass once we've determined ABI below.
7078        setNativeLibraryPaths(pkg);
7079
7080        // We would never need to extract libs for forward-locked and external packages,
7081        // since the container service will do it for us. We shouldn't attempt to
7082        // extract libs from system app when it was not updated.
7083        if (pkg.isForwardLocked() || isExternal(pkg) ||
7084            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7085            extractLibs = false;
7086        }
7087
7088        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7089        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7090
7091        NativeLibraryHelper.Handle handle = null;
7092        try {
7093            handle = NativeLibraryHelper.Handle.create(scanFile);
7094            // TODO(multiArch): This can be null for apps that didn't go through the
7095            // usual installation process. We can calculate it again, like we
7096            // do during install time.
7097            //
7098            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7099            // unnecessary.
7100            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7101
7102            // Null out the abis so that they can be recalculated.
7103            pkg.applicationInfo.primaryCpuAbi = null;
7104            pkg.applicationInfo.secondaryCpuAbi = null;
7105            if (isMultiArch(pkg.applicationInfo)) {
7106                // Warn if we've set an abiOverride for multi-lib packages..
7107                // By definition, we need to copy both 32 and 64 bit libraries for
7108                // such packages.
7109                if (pkg.cpuAbiOverride != null
7110                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7111                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7112                }
7113
7114                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7115                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7116                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7117                    if (extractLibs) {
7118                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7119                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7120                                useIsaSpecificSubdirs);
7121                    } else {
7122                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7123                    }
7124                }
7125
7126                maybeThrowExceptionForMultiArchCopy(
7127                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7128
7129                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7130                    if (extractLibs) {
7131                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7132                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7133                                useIsaSpecificSubdirs);
7134                    } else {
7135                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7136                    }
7137                }
7138
7139                maybeThrowExceptionForMultiArchCopy(
7140                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7141
7142                if (abi64 >= 0) {
7143                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7144                }
7145
7146                if (abi32 >= 0) {
7147                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7148                    if (abi64 >= 0) {
7149                        pkg.applicationInfo.secondaryCpuAbi = abi;
7150                    } else {
7151                        pkg.applicationInfo.primaryCpuAbi = abi;
7152                    }
7153                }
7154            } else {
7155                String[] abiList = (cpuAbiOverride != null) ?
7156                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7157
7158                // Enable gross and lame hacks for apps that are built with old
7159                // SDK tools. We must scan their APKs for renderscript bitcode and
7160                // not launch them if it's present. Don't bother checking on devices
7161                // that don't have 64 bit support.
7162                boolean needsRenderScriptOverride = false;
7163                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7164                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7165                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7166                    needsRenderScriptOverride = true;
7167                }
7168
7169                final int copyRet;
7170                if (extractLibs) {
7171                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7172                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7173                } else {
7174                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7175                }
7176
7177                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7178                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7179                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7180                }
7181
7182                if (copyRet >= 0) {
7183                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7184                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7185                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7186                } else if (needsRenderScriptOverride) {
7187                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7188                }
7189            }
7190        } catch (IOException ioe) {
7191            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7192        } finally {
7193            IoUtils.closeQuietly(handle);
7194        }
7195
7196        // Now that we've calculated the ABIs and determined if it's an internal app,
7197        // we will go ahead and populate the nativeLibraryPath.
7198        setNativeLibraryPaths(pkg);
7199    }
7200
7201    /**
7202     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7203     * i.e, so that all packages can be run inside a single process if required.
7204     *
7205     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7206     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7207     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7208     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7209     * updating a package that belongs to a shared user.
7210     *
7211     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7212     * adds unnecessary complexity.
7213     */
7214    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7215            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7216        String requiredInstructionSet = null;
7217        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7218            requiredInstructionSet = VMRuntime.getInstructionSet(
7219                     scannedPackage.applicationInfo.primaryCpuAbi);
7220        }
7221
7222        PackageSetting requirer = null;
7223        for (PackageSetting ps : packagesForUser) {
7224            // If packagesForUser contains scannedPackage, we skip it. This will happen
7225            // when scannedPackage is an update of an existing package. Without this check,
7226            // we will never be able to change the ABI of any package belonging to a shared
7227            // user, even if it's compatible with other packages.
7228            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7229                if (ps.primaryCpuAbiString == null) {
7230                    continue;
7231                }
7232
7233                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7234                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7235                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7236                    // this but there's not much we can do.
7237                    String errorMessage = "Instruction set mismatch, "
7238                            + ((requirer == null) ? "[caller]" : requirer)
7239                            + " requires " + requiredInstructionSet + " whereas " + ps
7240                            + " requires " + instructionSet;
7241                    Slog.w(TAG, errorMessage);
7242                }
7243
7244                if (requiredInstructionSet == null) {
7245                    requiredInstructionSet = instructionSet;
7246                    requirer = ps;
7247                }
7248            }
7249        }
7250
7251        if (requiredInstructionSet != null) {
7252            String adjustedAbi;
7253            if (requirer != null) {
7254                // requirer != null implies that either scannedPackage was null or that scannedPackage
7255                // did not require an ABI, in which case we have to adjust scannedPackage to match
7256                // the ABI of the set (which is the same as requirer's ABI)
7257                adjustedAbi = requirer.primaryCpuAbiString;
7258                if (scannedPackage != null) {
7259                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7260                }
7261            } else {
7262                // requirer == null implies that we're updating all ABIs in the set to
7263                // match scannedPackage.
7264                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7265            }
7266
7267            for (PackageSetting ps : packagesForUser) {
7268                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7269                    if (ps.primaryCpuAbiString != null) {
7270                        continue;
7271                    }
7272
7273                    ps.primaryCpuAbiString = adjustedAbi;
7274                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7275                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7276                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7277
7278                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7279                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7280                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7281                            ps.primaryCpuAbiString = null;
7282                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7283                            return;
7284                        } else {
7285                            mInstaller.rmdex(ps.codePathString,
7286                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7287                        }
7288                    }
7289                }
7290            }
7291        }
7292    }
7293
7294    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7295        synchronized (mPackages) {
7296            mResolverReplaced = true;
7297            // Set up information for custom user intent resolution activity.
7298            mResolveActivity.applicationInfo = pkg.applicationInfo;
7299            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7300            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7301            mResolveActivity.processName = pkg.applicationInfo.packageName;
7302            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7303            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7304                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7305            mResolveActivity.theme = 0;
7306            mResolveActivity.exported = true;
7307            mResolveActivity.enabled = true;
7308            mResolveInfo.activityInfo = mResolveActivity;
7309            mResolveInfo.priority = 0;
7310            mResolveInfo.preferredOrder = 0;
7311            mResolveInfo.match = 0;
7312            mResolveComponentName = mCustomResolverComponentName;
7313            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7314                    mResolveComponentName);
7315        }
7316    }
7317
7318    private static String calculateBundledApkRoot(final String codePathString) {
7319        final File codePath = new File(codePathString);
7320        final File codeRoot;
7321        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7322            codeRoot = Environment.getRootDirectory();
7323        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7324            codeRoot = Environment.getOemDirectory();
7325        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7326            codeRoot = Environment.getVendorDirectory();
7327        } else {
7328            // Unrecognized code path; take its top real segment as the apk root:
7329            // e.g. /something/app/blah.apk => /something
7330            try {
7331                File f = codePath.getCanonicalFile();
7332                File parent = f.getParentFile();    // non-null because codePath is a file
7333                File tmp;
7334                while ((tmp = parent.getParentFile()) != null) {
7335                    f = parent;
7336                    parent = tmp;
7337                }
7338                codeRoot = f;
7339                Slog.w(TAG, "Unrecognized code path "
7340                        + codePath + " - using " + codeRoot);
7341            } catch (IOException e) {
7342                // Can't canonicalize the code path -- shenanigans?
7343                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7344                return Environment.getRootDirectory().getPath();
7345            }
7346        }
7347        return codeRoot.getPath();
7348    }
7349
7350    /**
7351     * Derive and set the location of native libraries for the given package,
7352     * which varies depending on where and how the package was installed.
7353     */
7354    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7355        final ApplicationInfo info = pkg.applicationInfo;
7356        final String codePath = pkg.codePath;
7357        final File codeFile = new File(codePath);
7358        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7359        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7360
7361        info.nativeLibraryRootDir = null;
7362        info.nativeLibraryRootRequiresIsa = false;
7363        info.nativeLibraryDir = null;
7364        info.secondaryNativeLibraryDir = null;
7365
7366        if (isApkFile(codeFile)) {
7367            // Monolithic install
7368            if (bundledApp) {
7369                // If "/system/lib64/apkname" exists, assume that is the per-package
7370                // native library directory to use; otherwise use "/system/lib/apkname".
7371                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7372                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7373                        getPrimaryInstructionSet(info));
7374
7375                // This is a bundled system app so choose the path based on the ABI.
7376                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7377                // is just the default path.
7378                final String apkName = deriveCodePathName(codePath);
7379                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7380                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7381                        apkName).getAbsolutePath();
7382
7383                if (info.secondaryCpuAbi != null) {
7384                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7385                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7386                            secondaryLibDir, apkName).getAbsolutePath();
7387                }
7388            } else if (asecApp) {
7389                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7390                        .getAbsolutePath();
7391            } else {
7392                final String apkName = deriveCodePathName(codePath);
7393                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7394                        .getAbsolutePath();
7395            }
7396
7397            info.nativeLibraryRootRequiresIsa = false;
7398            info.nativeLibraryDir = info.nativeLibraryRootDir;
7399        } else {
7400            // Cluster install
7401            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7402            info.nativeLibraryRootRequiresIsa = true;
7403
7404            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7405                    getPrimaryInstructionSet(info)).getAbsolutePath();
7406
7407            if (info.secondaryCpuAbi != null) {
7408                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7409                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7410            }
7411        }
7412    }
7413
7414    /**
7415     * Calculate the abis and roots for a bundled app. These can uniquely
7416     * be determined from the contents of the system partition, i.e whether
7417     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7418     * of this information, and instead assume that the system was built
7419     * sensibly.
7420     */
7421    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7422                                           PackageSetting pkgSetting) {
7423        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7424
7425        // If "/system/lib64/apkname" exists, assume that is the per-package
7426        // native library directory to use; otherwise use "/system/lib/apkname".
7427        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7428        setBundledAppAbi(pkg, apkRoot, apkName);
7429        // pkgSetting might be null during rescan following uninstall of updates
7430        // to a bundled app, so accommodate that possibility.  The settings in
7431        // that case will be established later from the parsed package.
7432        //
7433        // If the settings aren't null, sync them up with what we've just derived.
7434        // note that apkRoot isn't stored in the package settings.
7435        if (pkgSetting != null) {
7436            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7437            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7438        }
7439    }
7440
7441    /**
7442     * Deduces the ABI of a bundled app and sets the relevant fields on the
7443     * parsed pkg object.
7444     *
7445     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7446     *        under which system libraries are installed.
7447     * @param apkName the name of the installed package.
7448     */
7449    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7450        final File codeFile = new File(pkg.codePath);
7451
7452        final boolean has64BitLibs;
7453        final boolean has32BitLibs;
7454        if (isApkFile(codeFile)) {
7455            // Monolithic install
7456            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7457            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7458        } else {
7459            // Cluster install
7460            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7461            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7462                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7463                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7464                has64BitLibs = (new File(rootDir, isa)).exists();
7465            } else {
7466                has64BitLibs = false;
7467            }
7468            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7469                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7470                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7471                has32BitLibs = (new File(rootDir, isa)).exists();
7472            } else {
7473                has32BitLibs = false;
7474            }
7475        }
7476
7477        if (has64BitLibs && !has32BitLibs) {
7478            // The package has 64 bit libs, but not 32 bit libs. Its primary
7479            // ABI should be 64 bit. We can safely assume here that the bundled
7480            // native libraries correspond to the most preferred ABI in the list.
7481
7482            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7483            pkg.applicationInfo.secondaryCpuAbi = null;
7484        } else if (has32BitLibs && !has64BitLibs) {
7485            // The package has 32 bit libs but not 64 bit libs. Its primary
7486            // ABI should be 32 bit.
7487
7488            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7489            pkg.applicationInfo.secondaryCpuAbi = null;
7490        } else if (has32BitLibs && has64BitLibs) {
7491            // The application has both 64 and 32 bit bundled libraries. We check
7492            // here that the app declares multiArch support, and warn if it doesn't.
7493            //
7494            // We will be lenient here and record both ABIs. The primary will be the
7495            // ABI that's higher on the list, i.e, a device that's configured to prefer
7496            // 64 bit apps will see a 64 bit primary ABI,
7497
7498            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7499                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7500            }
7501
7502            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7503                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7504                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7505            } else {
7506                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7507                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7508            }
7509        } else {
7510            pkg.applicationInfo.primaryCpuAbi = null;
7511            pkg.applicationInfo.secondaryCpuAbi = null;
7512        }
7513    }
7514
7515    private void killApplication(String pkgName, int appId, String reason) {
7516        // Request the ActivityManager to kill the process(only for existing packages)
7517        // so that we do not end up in a confused state while the user is still using the older
7518        // version of the application while the new one gets installed.
7519        IActivityManager am = ActivityManagerNative.getDefault();
7520        if (am != null) {
7521            try {
7522                am.killApplicationWithAppId(pkgName, appId, reason);
7523            } catch (RemoteException e) {
7524            }
7525        }
7526    }
7527
7528    void removePackageLI(PackageSetting ps, boolean chatty) {
7529        if (DEBUG_INSTALL) {
7530            if (chatty)
7531                Log.d(TAG, "Removing package " + ps.name);
7532        }
7533
7534        // writer
7535        synchronized (mPackages) {
7536            mPackages.remove(ps.name);
7537            final PackageParser.Package pkg = ps.pkg;
7538            if (pkg != null) {
7539                cleanPackageDataStructuresLILPw(pkg, chatty);
7540            }
7541        }
7542    }
7543
7544    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7545        if (DEBUG_INSTALL) {
7546            if (chatty)
7547                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7548        }
7549
7550        // writer
7551        synchronized (mPackages) {
7552            mPackages.remove(pkg.applicationInfo.packageName);
7553            cleanPackageDataStructuresLILPw(pkg, chatty);
7554        }
7555    }
7556
7557    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7558        int N = pkg.providers.size();
7559        StringBuilder r = null;
7560        int i;
7561        for (i=0; i<N; i++) {
7562            PackageParser.Provider p = pkg.providers.get(i);
7563            mProviders.removeProvider(p);
7564            if (p.info.authority == null) {
7565
7566                /* There was another ContentProvider with this authority when
7567                 * this app was installed so this authority is null,
7568                 * Ignore it as we don't have to unregister the provider.
7569                 */
7570                continue;
7571            }
7572            String names[] = p.info.authority.split(";");
7573            for (int j = 0; j < names.length; j++) {
7574                if (mProvidersByAuthority.get(names[j]) == p) {
7575                    mProvidersByAuthority.remove(names[j]);
7576                    if (DEBUG_REMOVE) {
7577                        if (chatty)
7578                            Log.d(TAG, "Unregistered content provider: " + names[j]
7579                                    + ", className = " + p.info.name + ", isSyncable = "
7580                                    + p.info.isSyncable);
7581                    }
7582                }
7583            }
7584            if (DEBUG_REMOVE && chatty) {
7585                if (r == null) {
7586                    r = new StringBuilder(256);
7587                } else {
7588                    r.append(' ');
7589                }
7590                r.append(p.info.name);
7591            }
7592        }
7593        if (r != null) {
7594            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7595        }
7596
7597        N = pkg.services.size();
7598        r = null;
7599        for (i=0; i<N; i++) {
7600            PackageParser.Service s = pkg.services.get(i);
7601            mServices.removeService(s);
7602            if (chatty) {
7603                if (r == null) {
7604                    r = new StringBuilder(256);
7605                } else {
7606                    r.append(' ');
7607                }
7608                r.append(s.info.name);
7609            }
7610        }
7611        if (r != null) {
7612            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7613        }
7614
7615        N = pkg.receivers.size();
7616        r = null;
7617        for (i=0; i<N; i++) {
7618            PackageParser.Activity a = pkg.receivers.get(i);
7619            mReceivers.removeActivity(a, "receiver");
7620            if (DEBUG_REMOVE && chatty) {
7621                if (r == null) {
7622                    r = new StringBuilder(256);
7623                } else {
7624                    r.append(' ');
7625                }
7626                r.append(a.info.name);
7627            }
7628        }
7629        if (r != null) {
7630            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7631        }
7632
7633        N = pkg.activities.size();
7634        r = null;
7635        for (i=0; i<N; i++) {
7636            PackageParser.Activity a = pkg.activities.get(i);
7637            mActivities.removeActivity(a, "activity");
7638            if (DEBUG_REMOVE && chatty) {
7639                if (r == null) {
7640                    r = new StringBuilder(256);
7641                } else {
7642                    r.append(' ');
7643                }
7644                r.append(a.info.name);
7645            }
7646        }
7647        if (r != null) {
7648            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7649        }
7650
7651        N = pkg.permissions.size();
7652        r = null;
7653        for (i=0; i<N; i++) {
7654            PackageParser.Permission p = pkg.permissions.get(i);
7655            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7656            if (bp == null) {
7657                bp = mSettings.mPermissionTrees.get(p.info.name);
7658            }
7659            if (bp != null && bp.perm == p) {
7660                bp.perm = null;
7661                if (DEBUG_REMOVE && chatty) {
7662                    if (r == null) {
7663                        r = new StringBuilder(256);
7664                    } else {
7665                        r.append(' ');
7666                    }
7667                    r.append(p.info.name);
7668                }
7669            }
7670            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7671                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7672                if (appOpPerms != null) {
7673                    appOpPerms.remove(pkg.packageName);
7674                }
7675            }
7676        }
7677        if (r != null) {
7678            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7679        }
7680
7681        N = pkg.requestedPermissions.size();
7682        r = null;
7683        for (i=0; i<N; i++) {
7684            String perm = pkg.requestedPermissions.get(i);
7685            BasePermission bp = mSettings.mPermissions.get(perm);
7686            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7687                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7688                if (appOpPerms != null) {
7689                    appOpPerms.remove(pkg.packageName);
7690                    if (appOpPerms.isEmpty()) {
7691                        mAppOpPermissionPackages.remove(perm);
7692                    }
7693                }
7694            }
7695        }
7696        if (r != null) {
7697            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7698        }
7699
7700        N = pkg.instrumentation.size();
7701        r = null;
7702        for (i=0; i<N; i++) {
7703            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7704            mInstrumentation.remove(a.getComponentName());
7705            if (DEBUG_REMOVE && chatty) {
7706                if (r == null) {
7707                    r = new StringBuilder(256);
7708                } else {
7709                    r.append(' ');
7710                }
7711                r.append(a.info.name);
7712            }
7713        }
7714        if (r != null) {
7715            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7716        }
7717
7718        r = null;
7719        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7720            // Only system apps can hold shared libraries.
7721            if (pkg.libraryNames != null) {
7722                for (i=0; i<pkg.libraryNames.size(); i++) {
7723                    String name = pkg.libraryNames.get(i);
7724                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7725                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7726                        mSharedLibraries.remove(name);
7727                        if (DEBUG_REMOVE && chatty) {
7728                            if (r == null) {
7729                                r = new StringBuilder(256);
7730                            } else {
7731                                r.append(' ');
7732                            }
7733                            r.append(name);
7734                        }
7735                    }
7736                }
7737            }
7738        }
7739        if (r != null) {
7740            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7741        }
7742    }
7743
7744    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7745        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7746            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7747                return true;
7748            }
7749        }
7750        return false;
7751    }
7752
7753    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7754    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7755    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7756
7757    private void updatePermissionsLPw(String changingPkg,
7758            PackageParser.Package pkgInfo, int flags) {
7759        // Make sure there are no dangling permission trees.
7760        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7761        while (it.hasNext()) {
7762            final BasePermission bp = it.next();
7763            if (bp.packageSetting == null) {
7764                // We may not yet have parsed the package, so just see if
7765                // we still know about its settings.
7766                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7767            }
7768            if (bp.packageSetting == null) {
7769                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7770                        + " from package " + bp.sourcePackage);
7771                it.remove();
7772            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7773                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7774                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7775                            + " from package " + bp.sourcePackage);
7776                    flags |= UPDATE_PERMISSIONS_ALL;
7777                    it.remove();
7778                }
7779            }
7780        }
7781
7782        // Make sure all dynamic permissions have been assigned to a package,
7783        // and make sure there are no dangling permissions.
7784        it = mSettings.mPermissions.values().iterator();
7785        while (it.hasNext()) {
7786            final BasePermission bp = it.next();
7787            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7788                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7789                        + bp.name + " pkg=" + bp.sourcePackage
7790                        + " info=" + bp.pendingInfo);
7791                if (bp.packageSetting == null && bp.pendingInfo != null) {
7792                    final BasePermission tree = findPermissionTreeLP(bp.name);
7793                    if (tree != null && tree.perm != null) {
7794                        bp.packageSetting = tree.packageSetting;
7795                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7796                                new PermissionInfo(bp.pendingInfo));
7797                        bp.perm.info.packageName = tree.perm.info.packageName;
7798                        bp.perm.info.name = bp.name;
7799                        bp.uid = tree.uid;
7800                    }
7801                }
7802            }
7803            if (bp.packageSetting == null) {
7804                // We may not yet have parsed the package, so just see if
7805                // we still know about its settings.
7806                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7807            }
7808            if (bp.packageSetting == null) {
7809                Slog.w(TAG, "Removing dangling permission: " + bp.name
7810                        + " from package " + bp.sourcePackage);
7811                it.remove();
7812            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7813                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7814                    Slog.i(TAG, "Removing old permission: " + bp.name
7815                            + " from package " + bp.sourcePackage);
7816                    flags |= UPDATE_PERMISSIONS_ALL;
7817                    it.remove();
7818                }
7819            }
7820        }
7821
7822        // Now update the permissions for all packages, in particular
7823        // replace the granted permissions of the system packages.
7824        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7825            for (PackageParser.Package pkg : mPackages.values()) {
7826                if (pkg != pkgInfo) {
7827                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7828                            changingPkg);
7829                }
7830            }
7831        }
7832
7833        if (pkgInfo != null) {
7834            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7835        }
7836    }
7837
7838    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7839            String packageOfInterest) {
7840        // IMPORTANT: There are two types of permissions: install and runtime.
7841        // Install time permissions are granted when the app is installed to
7842        // all device users and users added in the future. Runtime permissions
7843        // are granted at runtime explicitly to specific users. Normal and signature
7844        // protected permissions are install time permissions. Dangerous permissions
7845        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7846        // otherwise they are runtime permissions. This function does not manage
7847        // runtime permissions except for the case an app targeting Lollipop MR1
7848        // being upgraded to target a newer SDK, in which case dangerous permissions
7849        // are transformed from install time to runtime ones.
7850
7851        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7852        if (ps == null) {
7853            return;
7854        }
7855
7856        PermissionsState permissionsState = ps.getPermissionsState();
7857        PermissionsState origPermissions = permissionsState;
7858
7859        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7860
7861        int[] upgradeUserIds = EMPTY_INT_ARRAY;
7862        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7863
7864        boolean changedInstallPermission = false;
7865
7866        if (replace) {
7867            ps.installPermissionsFixed = false;
7868            if (!ps.isSharedUser()) {
7869                origPermissions = new PermissionsState(permissionsState);
7870                permissionsState.reset();
7871            }
7872        }
7873
7874        permissionsState.setGlobalGids(mGlobalGids);
7875
7876        final int N = pkg.requestedPermissions.size();
7877        for (int i=0; i<N; i++) {
7878            final String name = pkg.requestedPermissions.get(i);
7879            final BasePermission bp = mSettings.mPermissions.get(name);
7880
7881            if (DEBUG_INSTALL) {
7882                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7883            }
7884
7885            if (bp == null || bp.packageSetting == null) {
7886                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7887                    Slog.w(TAG, "Unknown permission " + name
7888                            + " in package " + pkg.packageName);
7889                }
7890                continue;
7891            }
7892
7893            final String perm = bp.name;
7894            boolean allowedSig = false;
7895            int grant = GRANT_DENIED;
7896
7897            // Keep track of app op permissions.
7898            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7899                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7900                if (pkgs == null) {
7901                    pkgs = new ArraySet<>();
7902                    mAppOpPermissionPackages.put(bp.name, pkgs);
7903                }
7904                pkgs.add(pkg.packageName);
7905            }
7906
7907            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7908            switch (level) {
7909                case PermissionInfo.PROTECTION_NORMAL: {
7910                    // For all apps normal permissions are install time ones.
7911                    grant = GRANT_INSTALL;
7912                } break;
7913
7914                case PermissionInfo.PROTECTION_DANGEROUS: {
7915                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7916                        // For legacy apps dangerous permissions are install time ones.
7917                        grant = GRANT_INSTALL_LEGACY;
7918                    } else if (ps.isSystem()) {
7919                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7920                        if (origPermissions.hasInstallPermission(bp.name)) {
7921                            // If a system app had an install permission, then the app was
7922                            // upgraded and we grant the permissions as runtime to all users.
7923                            grant = GRANT_UPGRADE;
7924                            upgradeUserIds = currentUserIds;
7925                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7926                            // If users changed since the last permissions update for a
7927                            // system app, we grant the permission as runtime to the new users.
7928                            grant = GRANT_UPGRADE;
7929                            upgradeUserIds = currentUserIds;
7930                            for (int userId : updatedUserIds) {
7931                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7932                            }
7933                        } else {
7934                            // Otherwise, we grant the permission as runtime if the app
7935                            // already had it, i.e. we preserve runtime permissions.
7936                            grant = GRANT_RUNTIME;
7937                        }
7938                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7939                        // For legacy apps that became modern, install becomes runtime.
7940                        grant = GRANT_UPGRADE;
7941                        upgradeUserIds = currentUserIds;
7942                    } else if (replace) {
7943                        // For upgraded modern apps keep runtime permissions unchanged.
7944                        grant = GRANT_RUNTIME;
7945                    }
7946                } break;
7947
7948                case PermissionInfo.PROTECTION_SIGNATURE: {
7949                    // For all apps signature permissions are install time ones.
7950                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7951                    if (allowedSig) {
7952                        grant = GRANT_INSTALL;
7953                    }
7954                } break;
7955            }
7956
7957            if (DEBUG_INSTALL) {
7958                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7959            }
7960
7961            if (grant != GRANT_DENIED) {
7962                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7963                    // If this is an existing, non-system package, then
7964                    // we can't add any new permissions to it.
7965                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7966                        // Except...  if this is a permission that was added
7967                        // to the platform (note: need to only do this when
7968                        // updating the platform).
7969                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7970                            grant = GRANT_DENIED;
7971                        }
7972                    }
7973                }
7974
7975                switch (grant) {
7976                    case GRANT_INSTALL: {
7977                        // Revoke this as runtime permission to handle the case of
7978                        // a runtime permssion being downgraded to an install one.
7979                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7980                            if (origPermissions.getRuntimePermissionState(
7981                                    bp.name, userId) != null) {
7982                                // Revoke the runtime permission and clear the flags.
7983                                origPermissions.revokeRuntimePermission(bp, userId);
7984                                origPermissions.updatePermissionFlags(bp, userId,
7985                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
7986                                // If we revoked a permission permission, we have to write.
7987                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7988                                        changedRuntimePermissionUserIds, userId);
7989                            }
7990                        }
7991                        // Grant an install permission.
7992                        if (permissionsState.grantInstallPermission(bp) !=
7993                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7994                            changedInstallPermission = true;
7995                        }
7996                    } break;
7997
7998                    case GRANT_INSTALL_LEGACY: {
7999                        // Grant an install permission.
8000                        if (permissionsState.grantInstallPermission(bp) !=
8001                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8002                            changedInstallPermission = true;
8003                        }
8004                    } break;
8005
8006                    case GRANT_RUNTIME: {
8007                        // Grant previously granted runtime permissions.
8008                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8009                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8010                                PermissionState permissionState = origPermissions
8011                                        .getRuntimePermissionState(bp.name, userId);
8012                                final int flags = permissionState.getFlags();
8013                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8014                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8015                                    // If we cannot put the permission as it was, we have to write.
8016                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8017                                            changedRuntimePermissionUserIds, userId);
8018                                } else {
8019                                    // System components not only get the permissions but
8020                                    // they are also fixed, so nothing can change that.
8021                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
8022                                            ? flags
8023                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
8024                                    // Propagate the permission flags.
8025                                    permissionsState.updatePermissionFlags(bp, userId,
8026                                            newFlags, newFlags);
8027                                }
8028                            }
8029                        }
8030                    } break;
8031
8032                    case GRANT_UPGRADE: {
8033                        // Grant runtime permissions for a previously held install permission.
8034                        PermissionState permissionState = origPermissions
8035                                .getInstallPermissionState(bp.name);
8036                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8037
8038                        origPermissions.revokeInstallPermission(bp);
8039                        // We will be transferring the permission flags, so clear them.
8040                        origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8041                                PackageManager.MASK_PERMISSION_FLAGS, 0);
8042
8043                        // If the permission is not to be promoted to runtime we ignore it and
8044                        // also its other flags as they are not applicable to install permissions.
8045                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8046                            for (int userId : upgradeUserIds) {
8047                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8048                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8049                                    // System components not only get the permissions but
8050                                    // they are also fixed so nothing can change that.
8051                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
8052                                            ? flags
8053                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
8054                                    // Transfer the permission flags.
8055                                    permissionsState.updatePermissionFlags(bp, userId,
8056                                            newFlags, newFlags);
8057                                    // If we granted the permission, we have to write.
8058                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8059                                            changedRuntimePermissionUserIds, userId);
8060                                }
8061                            }
8062                        }
8063                    } break;
8064
8065                    default: {
8066                        if (packageOfInterest == null
8067                                || packageOfInterest.equals(pkg.packageName)) {
8068                            Slog.w(TAG, "Not granting permission " + perm
8069                                    + " to package " + pkg.packageName
8070                                    + " because it was previously installed without");
8071                        }
8072                    } break;
8073                }
8074            } else {
8075                if (permissionsState.revokeInstallPermission(bp) !=
8076                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8077                    // Also drop the permission flags.
8078                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8079                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8080                    changedInstallPermission = true;
8081                    Slog.i(TAG, "Un-granting permission " + perm
8082                            + " from package " + pkg.packageName
8083                            + " (protectionLevel=" + bp.protectionLevel
8084                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8085                            + ")");
8086                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8087                    // Don't print warning for app op permissions, since it is fine for them
8088                    // not to be granted, there is a UI for the user to decide.
8089                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8090                        Slog.w(TAG, "Not granting permission " + perm
8091                                + " to package " + pkg.packageName
8092                                + " (protectionLevel=" + bp.protectionLevel
8093                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8094                                + ")");
8095                    }
8096                }
8097            }
8098        }
8099
8100        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8101                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8102            // This is the first that we have heard about this package, so the
8103            // permissions we have now selected are fixed until explicitly
8104            // changed.
8105            ps.installPermissionsFixed = true;
8106        }
8107
8108        ps.setPermissionsUpdatedForUserIds(currentUserIds);
8109
8110        // Persist the runtime permissions state for users with changes.
8111        for (int userId : changedRuntimePermissionUserIds) {
8112            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
8113        }
8114    }
8115
8116    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8117        boolean allowed = false;
8118        final int NP = PackageParser.NEW_PERMISSIONS.length;
8119        for (int ip=0; ip<NP; ip++) {
8120            final PackageParser.NewPermissionInfo npi
8121                    = PackageParser.NEW_PERMISSIONS[ip];
8122            if (npi.name.equals(perm)
8123                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8124                allowed = true;
8125                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8126                        + pkg.packageName);
8127                break;
8128            }
8129        }
8130        return allowed;
8131    }
8132
8133    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8134            BasePermission bp, PermissionsState origPermissions) {
8135        boolean allowed;
8136        allowed = (compareSignatures(
8137                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8138                        == PackageManager.SIGNATURE_MATCH)
8139                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8140                        == PackageManager.SIGNATURE_MATCH);
8141        if (!allowed && (bp.protectionLevel
8142                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8143            if (isSystemApp(pkg)) {
8144                // For updated system applications, a system permission
8145                // is granted only if it had been defined by the original application.
8146                if (pkg.isUpdatedSystemApp()) {
8147                    final PackageSetting sysPs = mSettings
8148                            .getDisabledSystemPkgLPr(pkg.packageName);
8149                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8150                        // If the original was granted this permission, we take
8151                        // that grant decision as read and propagate it to the
8152                        // update.
8153                        if (sysPs.isPrivileged()) {
8154                            allowed = true;
8155                        }
8156                    } else {
8157                        // The system apk may have been updated with an older
8158                        // version of the one on the data partition, but which
8159                        // granted a new system permission that it didn't have
8160                        // before.  In this case we do want to allow the app to
8161                        // now get the new permission if the ancestral apk is
8162                        // privileged to get it.
8163                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8164                            for (int j=0;
8165                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8166                                if (perm.equals(
8167                                        sysPs.pkg.requestedPermissions.get(j))) {
8168                                    allowed = true;
8169                                    break;
8170                                }
8171                            }
8172                        }
8173                    }
8174                } else {
8175                    allowed = isPrivilegedApp(pkg);
8176                }
8177            }
8178        }
8179        if (!allowed && (bp.protectionLevel
8180                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8181            // For development permissions, a development permission
8182            // is granted only if it was already granted.
8183            allowed = origPermissions.hasInstallPermission(perm);
8184        }
8185        return allowed;
8186    }
8187
8188    final class ActivityIntentResolver
8189            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8190        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8191                boolean defaultOnly, int userId) {
8192            if (!sUserManager.exists(userId)) return null;
8193            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8194            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8195        }
8196
8197        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8198                int userId) {
8199            if (!sUserManager.exists(userId)) return null;
8200            mFlags = flags;
8201            return super.queryIntent(intent, resolvedType,
8202                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8203        }
8204
8205        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8206                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8207            if (!sUserManager.exists(userId)) return null;
8208            if (packageActivities == null) {
8209                return null;
8210            }
8211            mFlags = flags;
8212            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8213            final int N = packageActivities.size();
8214            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8215                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8216
8217            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8218            for (int i = 0; i < N; ++i) {
8219                intentFilters = packageActivities.get(i).intents;
8220                if (intentFilters != null && intentFilters.size() > 0) {
8221                    PackageParser.ActivityIntentInfo[] array =
8222                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8223                    intentFilters.toArray(array);
8224                    listCut.add(array);
8225                }
8226            }
8227            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8228        }
8229
8230        public final void addActivity(PackageParser.Activity a, String type) {
8231            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8232            mActivities.put(a.getComponentName(), a);
8233            if (DEBUG_SHOW_INFO)
8234                Log.v(
8235                TAG, "  " + type + " " +
8236                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8237            if (DEBUG_SHOW_INFO)
8238                Log.v(TAG, "    Class=" + a.info.name);
8239            final int NI = a.intents.size();
8240            for (int j=0; j<NI; j++) {
8241                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8242                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8243                    intent.setPriority(0);
8244                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8245                            + a.className + " with priority > 0, forcing to 0");
8246                }
8247                if (DEBUG_SHOW_INFO) {
8248                    Log.v(TAG, "    IntentFilter:");
8249                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8250                }
8251                if (!intent.debugCheck()) {
8252                    Log.w(TAG, "==> For Activity " + a.info.name);
8253                }
8254                addFilter(intent);
8255            }
8256        }
8257
8258        public final void removeActivity(PackageParser.Activity a, String type) {
8259            mActivities.remove(a.getComponentName());
8260            if (DEBUG_SHOW_INFO) {
8261                Log.v(TAG, "  " + type + " "
8262                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8263                                : a.info.name) + ":");
8264                Log.v(TAG, "    Class=" + a.info.name);
8265            }
8266            final int NI = a.intents.size();
8267            for (int j=0; j<NI; j++) {
8268                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8269                if (DEBUG_SHOW_INFO) {
8270                    Log.v(TAG, "    IntentFilter:");
8271                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8272                }
8273                removeFilter(intent);
8274            }
8275        }
8276
8277        @Override
8278        protected boolean allowFilterResult(
8279                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8280            ActivityInfo filterAi = filter.activity.info;
8281            for (int i=dest.size()-1; i>=0; i--) {
8282                ActivityInfo destAi = dest.get(i).activityInfo;
8283                if (destAi.name == filterAi.name
8284                        && destAi.packageName == filterAi.packageName) {
8285                    return false;
8286                }
8287            }
8288            return true;
8289        }
8290
8291        @Override
8292        protected ActivityIntentInfo[] newArray(int size) {
8293            return new ActivityIntentInfo[size];
8294        }
8295
8296        @Override
8297        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8298            if (!sUserManager.exists(userId)) return true;
8299            PackageParser.Package p = filter.activity.owner;
8300            if (p != null) {
8301                PackageSetting ps = (PackageSetting)p.mExtras;
8302                if (ps != null) {
8303                    // System apps are never considered stopped for purposes of
8304                    // filtering, because there may be no way for the user to
8305                    // actually re-launch them.
8306                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8307                            && ps.getStopped(userId);
8308                }
8309            }
8310            return false;
8311        }
8312
8313        @Override
8314        protected boolean isPackageForFilter(String packageName,
8315                PackageParser.ActivityIntentInfo info) {
8316            return packageName.equals(info.activity.owner.packageName);
8317        }
8318
8319        @Override
8320        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8321                int match, int userId) {
8322            if (!sUserManager.exists(userId)) return null;
8323            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8324                return null;
8325            }
8326            final PackageParser.Activity activity = info.activity;
8327            if (mSafeMode && (activity.info.applicationInfo.flags
8328                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8329                return null;
8330            }
8331            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8332            if (ps == null) {
8333                return null;
8334            }
8335            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8336                    ps.readUserState(userId), userId);
8337            if (ai == null) {
8338                return null;
8339            }
8340            final ResolveInfo res = new ResolveInfo();
8341            res.activityInfo = ai;
8342            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8343                res.filter = info;
8344            }
8345            if (info != null) {
8346                res.handleAllWebDataURI = info.handleAllWebDataURI();
8347            }
8348            res.priority = info.getPriority();
8349            res.preferredOrder = activity.owner.mPreferredOrder;
8350            //System.out.println("Result: " + res.activityInfo.className +
8351            //                   " = " + res.priority);
8352            res.match = match;
8353            res.isDefault = info.hasDefault;
8354            res.labelRes = info.labelRes;
8355            res.nonLocalizedLabel = info.nonLocalizedLabel;
8356            if (userNeedsBadging(userId)) {
8357                res.noResourceId = true;
8358            } else {
8359                res.icon = info.icon;
8360            }
8361            res.system = res.activityInfo.applicationInfo.isSystemApp();
8362            return res;
8363        }
8364
8365        @Override
8366        protected void sortResults(List<ResolveInfo> results) {
8367            Collections.sort(results, mResolvePrioritySorter);
8368        }
8369
8370        @Override
8371        protected void dumpFilter(PrintWriter out, String prefix,
8372                PackageParser.ActivityIntentInfo filter) {
8373            out.print(prefix); out.print(
8374                    Integer.toHexString(System.identityHashCode(filter.activity)));
8375                    out.print(' ');
8376                    filter.activity.printComponentShortName(out);
8377                    out.print(" filter ");
8378                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8379        }
8380
8381        @Override
8382        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8383            return filter.activity;
8384        }
8385
8386        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8387            PackageParser.Activity activity = (PackageParser.Activity)label;
8388            out.print(prefix); out.print(
8389                    Integer.toHexString(System.identityHashCode(activity)));
8390                    out.print(' ');
8391                    activity.printComponentShortName(out);
8392            if (count > 1) {
8393                out.print(" ("); out.print(count); out.print(" filters)");
8394            }
8395            out.println();
8396        }
8397
8398//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8399//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8400//            final List<ResolveInfo> retList = Lists.newArrayList();
8401//            while (i.hasNext()) {
8402//                final ResolveInfo resolveInfo = i.next();
8403//                if (isEnabledLP(resolveInfo.activityInfo)) {
8404//                    retList.add(resolveInfo);
8405//                }
8406//            }
8407//            return retList;
8408//        }
8409
8410        // Keys are String (activity class name), values are Activity.
8411        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8412                = new ArrayMap<ComponentName, PackageParser.Activity>();
8413        private int mFlags;
8414    }
8415
8416    private final class ServiceIntentResolver
8417            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8418        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8419                boolean defaultOnly, int userId) {
8420            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8421            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8422        }
8423
8424        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8425                int userId) {
8426            if (!sUserManager.exists(userId)) return null;
8427            mFlags = flags;
8428            return super.queryIntent(intent, resolvedType,
8429                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8430        }
8431
8432        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8433                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8434            if (!sUserManager.exists(userId)) return null;
8435            if (packageServices == null) {
8436                return null;
8437            }
8438            mFlags = flags;
8439            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8440            final int N = packageServices.size();
8441            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8442                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8443
8444            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8445            for (int i = 0; i < N; ++i) {
8446                intentFilters = packageServices.get(i).intents;
8447                if (intentFilters != null && intentFilters.size() > 0) {
8448                    PackageParser.ServiceIntentInfo[] array =
8449                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8450                    intentFilters.toArray(array);
8451                    listCut.add(array);
8452                }
8453            }
8454            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8455        }
8456
8457        public final void addService(PackageParser.Service s) {
8458            mServices.put(s.getComponentName(), s);
8459            if (DEBUG_SHOW_INFO) {
8460                Log.v(TAG, "  "
8461                        + (s.info.nonLocalizedLabel != null
8462                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8463                Log.v(TAG, "    Class=" + s.info.name);
8464            }
8465            final int NI = s.intents.size();
8466            int j;
8467            for (j=0; j<NI; j++) {
8468                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8469                if (DEBUG_SHOW_INFO) {
8470                    Log.v(TAG, "    IntentFilter:");
8471                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8472                }
8473                if (!intent.debugCheck()) {
8474                    Log.w(TAG, "==> For Service " + s.info.name);
8475                }
8476                addFilter(intent);
8477            }
8478        }
8479
8480        public final void removeService(PackageParser.Service s) {
8481            mServices.remove(s.getComponentName());
8482            if (DEBUG_SHOW_INFO) {
8483                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8484                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8485                Log.v(TAG, "    Class=" + s.info.name);
8486            }
8487            final int NI = s.intents.size();
8488            int j;
8489            for (j=0; j<NI; j++) {
8490                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8491                if (DEBUG_SHOW_INFO) {
8492                    Log.v(TAG, "    IntentFilter:");
8493                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8494                }
8495                removeFilter(intent);
8496            }
8497        }
8498
8499        @Override
8500        protected boolean allowFilterResult(
8501                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8502            ServiceInfo filterSi = filter.service.info;
8503            for (int i=dest.size()-1; i>=0; i--) {
8504                ServiceInfo destAi = dest.get(i).serviceInfo;
8505                if (destAi.name == filterSi.name
8506                        && destAi.packageName == filterSi.packageName) {
8507                    return false;
8508                }
8509            }
8510            return true;
8511        }
8512
8513        @Override
8514        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8515            return new PackageParser.ServiceIntentInfo[size];
8516        }
8517
8518        @Override
8519        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8520            if (!sUserManager.exists(userId)) return true;
8521            PackageParser.Package p = filter.service.owner;
8522            if (p != null) {
8523                PackageSetting ps = (PackageSetting)p.mExtras;
8524                if (ps != null) {
8525                    // System apps are never considered stopped for purposes of
8526                    // filtering, because there may be no way for the user to
8527                    // actually re-launch them.
8528                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8529                            && ps.getStopped(userId);
8530                }
8531            }
8532            return false;
8533        }
8534
8535        @Override
8536        protected boolean isPackageForFilter(String packageName,
8537                PackageParser.ServiceIntentInfo info) {
8538            return packageName.equals(info.service.owner.packageName);
8539        }
8540
8541        @Override
8542        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8543                int match, int userId) {
8544            if (!sUserManager.exists(userId)) return null;
8545            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8546            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8547                return null;
8548            }
8549            final PackageParser.Service service = info.service;
8550            if (mSafeMode && (service.info.applicationInfo.flags
8551                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8552                return null;
8553            }
8554            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8555            if (ps == null) {
8556                return null;
8557            }
8558            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8559                    ps.readUserState(userId), userId);
8560            if (si == null) {
8561                return null;
8562            }
8563            final ResolveInfo res = new ResolveInfo();
8564            res.serviceInfo = si;
8565            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8566                res.filter = filter;
8567            }
8568            res.priority = info.getPriority();
8569            res.preferredOrder = service.owner.mPreferredOrder;
8570            res.match = match;
8571            res.isDefault = info.hasDefault;
8572            res.labelRes = info.labelRes;
8573            res.nonLocalizedLabel = info.nonLocalizedLabel;
8574            res.icon = info.icon;
8575            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8576            return res;
8577        }
8578
8579        @Override
8580        protected void sortResults(List<ResolveInfo> results) {
8581            Collections.sort(results, mResolvePrioritySorter);
8582        }
8583
8584        @Override
8585        protected void dumpFilter(PrintWriter out, String prefix,
8586                PackageParser.ServiceIntentInfo filter) {
8587            out.print(prefix); out.print(
8588                    Integer.toHexString(System.identityHashCode(filter.service)));
8589                    out.print(' ');
8590                    filter.service.printComponentShortName(out);
8591                    out.print(" filter ");
8592                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8593        }
8594
8595        @Override
8596        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8597            return filter.service;
8598        }
8599
8600        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8601            PackageParser.Service service = (PackageParser.Service)label;
8602            out.print(prefix); out.print(
8603                    Integer.toHexString(System.identityHashCode(service)));
8604                    out.print(' ');
8605                    service.printComponentShortName(out);
8606            if (count > 1) {
8607                out.print(" ("); out.print(count); out.print(" filters)");
8608            }
8609            out.println();
8610        }
8611
8612//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8613//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8614//            final List<ResolveInfo> retList = Lists.newArrayList();
8615//            while (i.hasNext()) {
8616//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8617//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8618//                    retList.add(resolveInfo);
8619//                }
8620//            }
8621//            return retList;
8622//        }
8623
8624        // Keys are String (activity class name), values are Activity.
8625        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8626                = new ArrayMap<ComponentName, PackageParser.Service>();
8627        private int mFlags;
8628    };
8629
8630    private final class ProviderIntentResolver
8631            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8632        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8633                boolean defaultOnly, int userId) {
8634            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8635            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8636        }
8637
8638        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8639                int userId) {
8640            if (!sUserManager.exists(userId))
8641                return null;
8642            mFlags = flags;
8643            return super.queryIntent(intent, resolvedType,
8644                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8645        }
8646
8647        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8648                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8649            if (!sUserManager.exists(userId))
8650                return null;
8651            if (packageProviders == null) {
8652                return null;
8653            }
8654            mFlags = flags;
8655            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8656            final int N = packageProviders.size();
8657            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8658                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8659
8660            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8661            for (int i = 0; i < N; ++i) {
8662                intentFilters = packageProviders.get(i).intents;
8663                if (intentFilters != null && intentFilters.size() > 0) {
8664                    PackageParser.ProviderIntentInfo[] array =
8665                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8666                    intentFilters.toArray(array);
8667                    listCut.add(array);
8668                }
8669            }
8670            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8671        }
8672
8673        public final void addProvider(PackageParser.Provider p) {
8674            if (mProviders.containsKey(p.getComponentName())) {
8675                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8676                return;
8677            }
8678
8679            mProviders.put(p.getComponentName(), p);
8680            if (DEBUG_SHOW_INFO) {
8681                Log.v(TAG, "  "
8682                        + (p.info.nonLocalizedLabel != null
8683                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8684                Log.v(TAG, "    Class=" + p.info.name);
8685            }
8686            final int NI = p.intents.size();
8687            int j;
8688            for (j = 0; j < NI; j++) {
8689                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8690                if (DEBUG_SHOW_INFO) {
8691                    Log.v(TAG, "    IntentFilter:");
8692                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8693                }
8694                if (!intent.debugCheck()) {
8695                    Log.w(TAG, "==> For Provider " + p.info.name);
8696                }
8697                addFilter(intent);
8698            }
8699        }
8700
8701        public final void removeProvider(PackageParser.Provider p) {
8702            mProviders.remove(p.getComponentName());
8703            if (DEBUG_SHOW_INFO) {
8704                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8705                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8706                Log.v(TAG, "    Class=" + p.info.name);
8707            }
8708            final int NI = p.intents.size();
8709            int j;
8710            for (j = 0; j < NI; j++) {
8711                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8712                if (DEBUG_SHOW_INFO) {
8713                    Log.v(TAG, "    IntentFilter:");
8714                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8715                }
8716                removeFilter(intent);
8717            }
8718        }
8719
8720        @Override
8721        protected boolean allowFilterResult(
8722                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8723            ProviderInfo filterPi = filter.provider.info;
8724            for (int i = dest.size() - 1; i >= 0; i--) {
8725                ProviderInfo destPi = dest.get(i).providerInfo;
8726                if (destPi.name == filterPi.name
8727                        && destPi.packageName == filterPi.packageName) {
8728                    return false;
8729                }
8730            }
8731            return true;
8732        }
8733
8734        @Override
8735        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8736            return new PackageParser.ProviderIntentInfo[size];
8737        }
8738
8739        @Override
8740        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8741            if (!sUserManager.exists(userId))
8742                return true;
8743            PackageParser.Package p = filter.provider.owner;
8744            if (p != null) {
8745                PackageSetting ps = (PackageSetting) p.mExtras;
8746                if (ps != null) {
8747                    // System apps are never considered stopped for purposes of
8748                    // filtering, because there may be no way for the user to
8749                    // actually re-launch them.
8750                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8751                            && ps.getStopped(userId);
8752                }
8753            }
8754            return false;
8755        }
8756
8757        @Override
8758        protected boolean isPackageForFilter(String packageName,
8759                PackageParser.ProviderIntentInfo info) {
8760            return packageName.equals(info.provider.owner.packageName);
8761        }
8762
8763        @Override
8764        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8765                int match, int userId) {
8766            if (!sUserManager.exists(userId))
8767                return null;
8768            final PackageParser.ProviderIntentInfo info = filter;
8769            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8770                return null;
8771            }
8772            final PackageParser.Provider provider = info.provider;
8773            if (mSafeMode && (provider.info.applicationInfo.flags
8774                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8775                return null;
8776            }
8777            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8778            if (ps == null) {
8779                return null;
8780            }
8781            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8782                    ps.readUserState(userId), userId);
8783            if (pi == null) {
8784                return null;
8785            }
8786            final ResolveInfo res = new ResolveInfo();
8787            res.providerInfo = pi;
8788            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8789                res.filter = filter;
8790            }
8791            res.priority = info.getPriority();
8792            res.preferredOrder = provider.owner.mPreferredOrder;
8793            res.match = match;
8794            res.isDefault = info.hasDefault;
8795            res.labelRes = info.labelRes;
8796            res.nonLocalizedLabel = info.nonLocalizedLabel;
8797            res.icon = info.icon;
8798            res.system = res.providerInfo.applicationInfo.isSystemApp();
8799            return res;
8800        }
8801
8802        @Override
8803        protected void sortResults(List<ResolveInfo> results) {
8804            Collections.sort(results, mResolvePrioritySorter);
8805        }
8806
8807        @Override
8808        protected void dumpFilter(PrintWriter out, String prefix,
8809                PackageParser.ProviderIntentInfo filter) {
8810            out.print(prefix);
8811            out.print(
8812                    Integer.toHexString(System.identityHashCode(filter.provider)));
8813            out.print(' ');
8814            filter.provider.printComponentShortName(out);
8815            out.print(" filter ");
8816            out.println(Integer.toHexString(System.identityHashCode(filter)));
8817        }
8818
8819        @Override
8820        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8821            return filter.provider;
8822        }
8823
8824        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8825            PackageParser.Provider provider = (PackageParser.Provider)label;
8826            out.print(prefix); out.print(
8827                    Integer.toHexString(System.identityHashCode(provider)));
8828                    out.print(' ');
8829                    provider.printComponentShortName(out);
8830            if (count > 1) {
8831                out.print(" ("); out.print(count); out.print(" filters)");
8832            }
8833            out.println();
8834        }
8835
8836        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8837                = new ArrayMap<ComponentName, PackageParser.Provider>();
8838        private int mFlags;
8839    };
8840
8841    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8842            new Comparator<ResolveInfo>() {
8843        public int compare(ResolveInfo r1, ResolveInfo r2) {
8844            int v1 = r1.priority;
8845            int v2 = r2.priority;
8846            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8847            if (v1 != v2) {
8848                return (v1 > v2) ? -1 : 1;
8849            }
8850            v1 = r1.preferredOrder;
8851            v2 = r2.preferredOrder;
8852            if (v1 != v2) {
8853                return (v1 > v2) ? -1 : 1;
8854            }
8855            if (r1.isDefault != r2.isDefault) {
8856                return r1.isDefault ? -1 : 1;
8857            }
8858            v1 = r1.match;
8859            v2 = r2.match;
8860            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8861            if (v1 != v2) {
8862                return (v1 > v2) ? -1 : 1;
8863            }
8864            if (r1.system != r2.system) {
8865                return r1.system ? -1 : 1;
8866            }
8867            return 0;
8868        }
8869    };
8870
8871    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8872            new Comparator<ProviderInfo>() {
8873        public int compare(ProviderInfo p1, ProviderInfo p2) {
8874            final int v1 = p1.initOrder;
8875            final int v2 = p2.initOrder;
8876            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8877        }
8878    };
8879
8880    final void sendPackageBroadcast(final String action, final String pkg,
8881            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8882            final int[] userIds) {
8883        mHandler.post(new Runnable() {
8884            @Override
8885            public void run() {
8886                try {
8887                    final IActivityManager am = ActivityManagerNative.getDefault();
8888                    if (am == null) return;
8889                    final int[] resolvedUserIds;
8890                    if (userIds == null) {
8891                        resolvedUserIds = am.getRunningUserIds();
8892                    } else {
8893                        resolvedUserIds = userIds;
8894                    }
8895                    for (int id : resolvedUserIds) {
8896                        final Intent intent = new Intent(action,
8897                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8898                        if (extras != null) {
8899                            intent.putExtras(extras);
8900                        }
8901                        if (targetPkg != null) {
8902                            intent.setPackage(targetPkg);
8903                        }
8904                        // Modify the UID when posting to other users
8905                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8906                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8907                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8908                            intent.putExtra(Intent.EXTRA_UID, uid);
8909                        }
8910                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8911                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8912                        if (DEBUG_BROADCASTS) {
8913                            RuntimeException here = new RuntimeException("here");
8914                            here.fillInStackTrace();
8915                            Slog.d(TAG, "Sending to user " + id + ": "
8916                                    + intent.toShortString(false, true, false, false)
8917                                    + " " + intent.getExtras(), here);
8918                        }
8919                        am.broadcastIntent(null, intent, null, finishedReceiver,
8920                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8921                                null, finishedReceiver != null, false, id);
8922                    }
8923                } catch (RemoteException ex) {
8924                }
8925            }
8926        });
8927    }
8928
8929    /**
8930     * Check if the external storage media is available. This is true if there
8931     * is a mounted external storage medium or if the external storage is
8932     * emulated.
8933     */
8934    private boolean isExternalMediaAvailable() {
8935        return mMediaMounted || Environment.isExternalStorageEmulated();
8936    }
8937
8938    @Override
8939    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8940        // writer
8941        synchronized (mPackages) {
8942            if (!isExternalMediaAvailable()) {
8943                // If the external storage is no longer mounted at this point,
8944                // the caller may not have been able to delete all of this
8945                // packages files and can not delete any more.  Bail.
8946                return null;
8947            }
8948            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8949            if (lastPackage != null) {
8950                pkgs.remove(lastPackage);
8951            }
8952            if (pkgs.size() > 0) {
8953                return pkgs.get(0);
8954            }
8955        }
8956        return null;
8957    }
8958
8959    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8960        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8961                userId, andCode ? 1 : 0, packageName);
8962        if (mSystemReady) {
8963            msg.sendToTarget();
8964        } else {
8965            if (mPostSystemReadyMessages == null) {
8966                mPostSystemReadyMessages = new ArrayList<>();
8967            }
8968            mPostSystemReadyMessages.add(msg);
8969        }
8970    }
8971
8972    void startCleaningPackages() {
8973        // reader
8974        synchronized (mPackages) {
8975            if (!isExternalMediaAvailable()) {
8976                return;
8977            }
8978            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8979                return;
8980            }
8981        }
8982        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8983        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8984        IActivityManager am = ActivityManagerNative.getDefault();
8985        if (am != null) {
8986            try {
8987                am.startService(null, intent, null, UserHandle.USER_OWNER);
8988            } catch (RemoteException e) {
8989            }
8990        }
8991    }
8992
8993    @Override
8994    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8995            int installFlags, String installerPackageName, VerificationParams verificationParams,
8996            String packageAbiOverride) {
8997        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8998                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8999    }
9000
9001    @Override
9002    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9003            int installFlags, String installerPackageName, VerificationParams verificationParams,
9004            String packageAbiOverride, int userId) {
9005        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9006
9007        final int callingUid = Binder.getCallingUid();
9008        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9009
9010        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9011            try {
9012                if (observer != null) {
9013                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9014                }
9015            } catch (RemoteException re) {
9016            }
9017            return;
9018        }
9019
9020        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9021            installFlags |= PackageManager.INSTALL_FROM_ADB;
9022
9023        } else {
9024            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9025            // about installerPackageName.
9026
9027            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9028            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9029        }
9030
9031        UserHandle user;
9032        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9033            user = UserHandle.ALL;
9034        } else {
9035            user = new UserHandle(userId);
9036        }
9037
9038        // Only system components can circumvent runtime permissions when installing.
9039        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9040                && mContext.checkCallingOrSelfPermission(Manifest.permission
9041                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9042            throw new SecurityException("You need the "
9043                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9044                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9045        }
9046
9047        verificationParams.setInstallerUid(callingUid);
9048
9049        final File originFile = new File(originPath);
9050        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9051
9052        final Message msg = mHandler.obtainMessage(INIT_COPY);
9053        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9054                null, verificationParams, user, packageAbiOverride);
9055        mHandler.sendMessage(msg);
9056    }
9057
9058    void installStage(String packageName, File stagedDir, String stagedCid,
9059            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9060            String installerPackageName, int installerUid, UserHandle user) {
9061        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9062                params.referrerUri, installerUid, null);
9063
9064        final OriginInfo origin;
9065        if (stagedDir != null) {
9066            origin = OriginInfo.fromStagedFile(stagedDir);
9067        } else {
9068            origin = OriginInfo.fromStagedContainer(stagedCid);
9069        }
9070
9071        final Message msg = mHandler.obtainMessage(INIT_COPY);
9072        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9073                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9074        mHandler.sendMessage(msg);
9075    }
9076
9077    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9078        Bundle extras = new Bundle(1);
9079        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9080
9081        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9082                packageName, extras, null, null, new int[] {userId});
9083        try {
9084            IActivityManager am = ActivityManagerNative.getDefault();
9085            final boolean isSystem =
9086                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9087            if (isSystem && am.isUserRunning(userId, false)) {
9088                // The just-installed/enabled app is bundled on the system, so presumed
9089                // to be able to run automatically without needing an explicit launch.
9090                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9091                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9092                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9093                        .setPackage(packageName);
9094                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9095                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9096            }
9097        } catch (RemoteException e) {
9098            // shouldn't happen
9099            Slog.w(TAG, "Unable to bootstrap installed package", e);
9100        }
9101    }
9102
9103    @Override
9104    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9105            int userId) {
9106        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9107        PackageSetting pkgSetting;
9108        final int uid = Binder.getCallingUid();
9109        enforceCrossUserPermission(uid, userId, true, true,
9110                "setApplicationHiddenSetting for user " + userId);
9111
9112        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9113            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9114            return false;
9115        }
9116
9117        long callingId = Binder.clearCallingIdentity();
9118        try {
9119            boolean sendAdded = false;
9120            boolean sendRemoved = false;
9121            // writer
9122            synchronized (mPackages) {
9123                pkgSetting = mSettings.mPackages.get(packageName);
9124                if (pkgSetting == null) {
9125                    return false;
9126                }
9127                if (pkgSetting.getHidden(userId) != hidden) {
9128                    pkgSetting.setHidden(hidden, userId);
9129                    mSettings.writePackageRestrictionsLPr(userId);
9130                    if (hidden) {
9131                        sendRemoved = true;
9132                    } else {
9133                        sendAdded = true;
9134                    }
9135                }
9136            }
9137            if (sendAdded) {
9138                sendPackageAddedForUser(packageName, pkgSetting, userId);
9139                return true;
9140            }
9141            if (sendRemoved) {
9142                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9143                        "hiding pkg");
9144                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9145            }
9146        } finally {
9147            Binder.restoreCallingIdentity(callingId);
9148        }
9149        return false;
9150    }
9151
9152    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9153            int userId) {
9154        final PackageRemovedInfo info = new PackageRemovedInfo();
9155        info.removedPackage = packageName;
9156        info.removedUsers = new int[] {userId};
9157        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9158        info.sendBroadcast(false, false, false);
9159    }
9160
9161    /**
9162     * Returns true if application is not found or there was an error. Otherwise it returns
9163     * the hidden state of the package for the given user.
9164     */
9165    @Override
9166    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9167        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9168        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9169                false, "getApplicationHidden for user " + userId);
9170        PackageSetting pkgSetting;
9171        long callingId = Binder.clearCallingIdentity();
9172        try {
9173            // writer
9174            synchronized (mPackages) {
9175                pkgSetting = mSettings.mPackages.get(packageName);
9176                if (pkgSetting == null) {
9177                    return true;
9178                }
9179                return pkgSetting.getHidden(userId);
9180            }
9181        } finally {
9182            Binder.restoreCallingIdentity(callingId);
9183        }
9184    }
9185
9186    /**
9187     * @hide
9188     */
9189    @Override
9190    public int installExistingPackageAsUser(String packageName, int userId) {
9191        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9192                null);
9193        PackageSetting pkgSetting;
9194        final int uid = Binder.getCallingUid();
9195        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9196                + userId);
9197        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9198            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9199        }
9200
9201        long callingId = Binder.clearCallingIdentity();
9202        try {
9203            boolean sendAdded = false;
9204
9205            // writer
9206            synchronized (mPackages) {
9207                pkgSetting = mSettings.mPackages.get(packageName);
9208                if (pkgSetting == null) {
9209                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9210                }
9211                if (!pkgSetting.getInstalled(userId)) {
9212                    pkgSetting.setInstalled(true, userId);
9213                    pkgSetting.setHidden(false, userId);
9214                    mSettings.writePackageRestrictionsLPr(userId);
9215                    sendAdded = true;
9216                }
9217            }
9218
9219            if (sendAdded) {
9220                sendPackageAddedForUser(packageName, pkgSetting, userId);
9221            }
9222        } finally {
9223            Binder.restoreCallingIdentity(callingId);
9224        }
9225
9226        return PackageManager.INSTALL_SUCCEEDED;
9227    }
9228
9229    boolean isUserRestricted(int userId, String restrictionKey) {
9230        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9231        if (restrictions.getBoolean(restrictionKey, false)) {
9232            Log.w(TAG, "User is restricted: " + restrictionKey);
9233            return true;
9234        }
9235        return false;
9236    }
9237
9238    @Override
9239    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9240        mContext.enforceCallingOrSelfPermission(
9241                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9242                "Only package verification agents can verify applications");
9243
9244        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9245        final PackageVerificationResponse response = new PackageVerificationResponse(
9246                verificationCode, Binder.getCallingUid());
9247        msg.arg1 = id;
9248        msg.obj = response;
9249        mHandler.sendMessage(msg);
9250    }
9251
9252    @Override
9253    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9254            long millisecondsToDelay) {
9255        mContext.enforceCallingOrSelfPermission(
9256                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9257                "Only package verification agents can extend verification timeouts");
9258
9259        final PackageVerificationState state = mPendingVerification.get(id);
9260        final PackageVerificationResponse response = new PackageVerificationResponse(
9261                verificationCodeAtTimeout, Binder.getCallingUid());
9262
9263        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9264            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9265        }
9266        if (millisecondsToDelay < 0) {
9267            millisecondsToDelay = 0;
9268        }
9269        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9270                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9271            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9272        }
9273
9274        if ((state != null) && !state.timeoutExtended()) {
9275            state.extendTimeout();
9276
9277            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9278            msg.arg1 = id;
9279            msg.obj = response;
9280            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9281        }
9282    }
9283
9284    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9285            int verificationCode, UserHandle user) {
9286        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9287        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9288        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9289        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9290        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9291
9292        mContext.sendBroadcastAsUser(intent, user,
9293                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9294    }
9295
9296    private ComponentName matchComponentForVerifier(String packageName,
9297            List<ResolveInfo> receivers) {
9298        ActivityInfo targetReceiver = null;
9299
9300        final int NR = receivers.size();
9301        for (int i = 0; i < NR; i++) {
9302            final ResolveInfo info = receivers.get(i);
9303            if (info.activityInfo == null) {
9304                continue;
9305            }
9306
9307            if (packageName.equals(info.activityInfo.packageName)) {
9308                targetReceiver = info.activityInfo;
9309                break;
9310            }
9311        }
9312
9313        if (targetReceiver == null) {
9314            return null;
9315        }
9316
9317        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9318    }
9319
9320    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9321            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9322        if (pkgInfo.verifiers.length == 0) {
9323            return null;
9324        }
9325
9326        final int N = pkgInfo.verifiers.length;
9327        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9328        for (int i = 0; i < N; i++) {
9329            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9330
9331            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9332                    receivers);
9333            if (comp == null) {
9334                continue;
9335            }
9336
9337            final int verifierUid = getUidForVerifier(verifierInfo);
9338            if (verifierUid == -1) {
9339                continue;
9340            }
9341
9342            if (DEBUG_VERIFY) {
9343                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9344                        + " with the correct signature");
9345            }
9346            sufficientVerifiers.add(comp);
9347            verificationState.addSufficientVerifier(verifierUid);
9348        }
9349
9350        return sufficientVerifiers;
9351    }
9352
9353    private int getUidForVerifier(VerifierInfo verifierInfo) {
9354        synchronized (mPackages) {
9355            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9356            if (pkg == null) {
9357                return -1;
9358            } else if (pkg.mSignatures.length != 1) {
9359                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9360                        + " has more than one signature; ignoring");
9361                return -1;
9362            }
9363
9364            /*
9365             * If the public key of the package's signature does not match
9366             * our expected public key, then this is a different package and
9367             * we should skip.
9368             */
9369
9370            final byte[] expectedPublicKey;
9371            try {
9372                final Signature verifierSig = pkg.mSignatures[0];
9373                final PublicKey publicKey = verifierSig.getPublicKey();
9374                expectedPublicKey = publicKey.getEncoded();
9375            } catch (CertificateException e) {
9376                return -1;
9377            }
9378
9379            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9380
9381            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9382                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9383                        + " does not have the expected public key; ignoring");
9384                return -1;
9385            }
9386
9387            return pkg.applicationInfo.uid;
9388        }
9389    }
9390
9391    @Override
9392    public void finishPackageInstall(int token) {
9393        enforceSystemOrRoot("Only the system is allowed to finish installs");
9394
9395        if (DEBUG_INSTALL) {
9396            Slog.v(TAG, "BM finishing package install for " + token);
9397        }
9398
9399        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9400        mHandler.sendMessage(msg);
9401    }
9402
9403    /**
9404     * Get the verification agent timeout.
9405     *
9406     * @return verification timeout in milliseconds
9407     */
9408    private long getVerificationTimeout() {
9409        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9410                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9411                DEFAULT_VERIFICATION_TIMEOUT);
9412    }
9413
9414    /**
9415     * Get the default verification agent response code.
9416     *
9417     * @return default verification response code
9418     */
9419    private int getDefaultVerificationResponse() {
9420        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9421                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9422                DEFAULT_VERIFICATION_RESPONSE);
9423    }
9424
9425    /**
9426     * Check whether or not package verification has been enabled.
9427     *
9428     * @return true if verification should be performed
9429     */
9430    private boolean isVerificationEnabled(int userId, int installFlags) {
9431        if (!DEFAULT_VERIFY_ENABLE) {
9432            return false;
9433        }
9434
9435        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9436
9437        // Check if installing from ADB
9438        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9439            // Do not run verification in a test harness environment
9440            if (ActivityManager.isRunningInTestHarness()) {
9441                return false;
9442            }
9443            if (ensureVerifyAppsEnabled) {
9444                return true;
9445            }
9446            // Check if the developer does not want package verification for ADB installs
9447            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9448                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9449                return false;
9450            }
9451        }
9452
9453        if (ensureVerifyAppsEnabled) {
9454            return true;
9455        }
9456
9457        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9458                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9459    }
9460
9461    @Override
9462    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9463            throws RemoteException {
9464        mContext.enforceCallingOrSelfPermission(
9465                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9466                "Only intentfilter verification agents can verify applications");
9467
9468        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9469        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9470                Binder.getCallingUid(), verificationCode, failedDomains);
9471        msg.arg1 = id;
9472        msg.obj = response;
9473        mHandler.sendMessage(msg);
9474    }
9475
9476    @Override
9477    public int getIntentVerificationStatus(String packageName, int userId) {
9478        synchronized (mPackages) {
9479            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9480        }
9481    }
9482
9483    @Override
9484    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9485        boolean result = false;
9486        synchronized (mPackages) {
9487            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9488        }
9489        if (result) {
9490            scheduleWritePackageRestrictionsLocked(userId);
9491        }
9492        return result;
9493    }
9494
9495    @Override
9496    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9497        synchronized (mPackages) {
9498            return mSettings.getIntentFilterVerificationsLPr(packageName);
9499        }
9500    }
9501
9502    @Override
9503    public List<IntentFilter> getAllIntentFilters(String packageName) {
9504        if (TextUtils.isEmpty(packageName)) {
9505            return Collections.<IntentFilter>emptyList();
9506        }
9507        synchronized (mPackages) {
9508            PackageParser.Package pkg = mPackages.get(packageName);
9509            if (pkg == null || pkg.activities == null) {
9510                return Collections.<IntentFilter>emptyList();
9511            }
9512            final int count = pkg.activities.size();
9513            ArrayList<IntentFilter> result = new ArrayList<>();
9514            for (int n=0; n<count; n++) {
9515                PackageParser.Activity activity = pkg.activities.get(n);
9516                if (activity.intents != null || activity.intents.size() > 0) {
9517                    result.addAll(activity.intents);
9518                }
9519            }
9520            return result;
9521        }
9522    }
9523
9524    @Override
9525    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9526        synchronized (mPackages) {
9527            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9528            if (packageName != null) {
9529                result |= updateIntentVerificationStatus(packageName,
9530                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9531                        UserHandle.myUserId());
9532            }
9533            return result;
9534        }
9535    }
9536
9537    @Override
9538    public String getDefaultBrowserPackageName(int userId) {
9539        synchronized (mPackages) {
9540            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9541        }
9542    }
9543
9544    /**
9545     * Get the "allow unknown sources" setting.
9546     *
9547     * @return the current "allow unknown sources" setting
9548     */
9549    private int getUnknownSourcesSettings() {
9550        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9551                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9552                -1);
9553    }
9554
9555    @Override
9556    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9557        final int uid = Binder.getCallingUid();
9558        // writer
9559        synchronized (mPackages) {
9560            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9561            if (targetPackageSetting == null) {
9562                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9563            }
9564
9565            PackageSetting installerPackageSetting;
9566            if (installerPackageName != null) {
9567                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9568                if (installerPackageSetting == null) {
9569                    throw new IllegalArgumentException("Unknown installer package: "
9570                            + installerPackageName);
9571                }
9572            } else {
9573                installerPackageSetting = null;
9574            }
9575
9576            Signature[] callerSignature;
9577            Object obj = mSettings.getUserIdLPr(uid);
9578            if (obj != null) {
9579                if (obj instanceof SharedUserSetting) {
9580                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9581                } else if (obj instanceof PackageSetting) {
9582                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9583                } else {
9584                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9585                }
9586            } else {
9587                throw new SecurityException("Unknown calling uid " + uid);
9588            }
9589
9590            // Verify: can't set installerPackageName to a package that is
9591            // not signed with the same cert as the caller.
9592            if (installerPackageSetting != null) {
9593                if (compareSignatures(callerSignature,
9594                        installerPackageSetting.signatures.mSignatures)
9595                        != PackageManager.SIGNATURE_MATCH) {
9596                    throw new SecurityException(
9597                            "Caller does not have same cert as new installer package "
9598                            + installerPackageName);
9599                }
9600            }
9601
9602            // Verify: if target already has an installer package, it must
9603            // be signed with the same cert as the caller.
9604            if (targetPackageSetting.installerPackageName != null) {
9605                PackageSetting setting = mSettings.mPackages.get(
9606                        targetPackageSetting.installerPackageName);
9607                // If the currently set package isn't valid, then it's always
9608                // okay to change it.
9609                if (setting != null) {
9610                    if (compareSignatures(callerSignature,
9611                            setting.signatures.mSignatures)
9612                            != PackageManager.SIGNATURE_MATCH) {
9613                        throw new SecurityException(
9614                                "Caller does not have same cert as old installer package "
9615                                + targetPackageSetting.installerPackageName);
9616                    }
9617                }
9618            }
9619
9620            // Okay!
9621            targetPackageSetting.installerPackageName = installerPackageName;
9622            scheduleWriteSettingsLocked();
9623        }
9624    }
9625
9626    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9627        // Queue up an async operation since the package installation may take a little while.
9628        mHandler.post(new Runnable() {
9629            public void run() {
9630                mHandler.removeCallbacks(this);
9631                 // Result object to be returned
9632                PackageInstalledInfo res = new PackageInstalledInfo();
9633                res.returnCode = currentStatus;
9634                res.uid = -1;
9635                res.pkg = null;
9636                res.removedInfo = new PackageRemovedInfo();
9637                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9638                    args.doPreInstall(res.returnCode);
9639                    synchronized (mInstallLock) {
9640                        installPackageLI(args, res);
9641                    }
9642                    args.doPostInstall(res.returnCode, res.uid);
9643                }
9644
9645                // A restore should be performed at this point if (a) the install
9646                // succeeded, (b) the operation is not an update, and (c) the new
9647                // package has not opted out of backup participation.
9648                final boolean update = res.removedInfo.removedPackage != null;
9649                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9650                boolean doRestore = !update
9651                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9652
9653                // Set up the post-install work request bookkeeping.  This will be used
9654                // and cleaned up by the post-install event handling regardless of whether
9655                // there's a restore pass performed.  Token values are >= 1.
9656                int token;
9657                if (mNextInstallToken < 0) mNextInstallToken = 1;
9658                token = mNextInstallToken++;
9659
9660                PostInstallData data = new PostInstallData(args, res);
9661                mRunningInstalls.put(token, data);
9662                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9663
9664                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9665                    // Pass responsibility to the Backup Manager.  It will perform a
9666                    // restore if appropriate, then pass responsibility back to the
9667                    // Package Manager to run the post-install observer callbacks
9668                    // and broadcasts.
9669                    IBackupManager bm = IBackupManager.Stub.asInterface(
9670                            ServiceManager.getService(Context.BACKUP_SERVICE));
9671                    if (bm != null) {
9672                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9673                                + " to BM for possible restore");
9674                        try {
9675                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9676                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9677                            } else {
9678                                doRestore = false;
9679                            }
9680                        } catch (RemoteException e) {
9681                            // can't happen; the backup manager is local
9682                        } catch (Exception e) {
9683                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9684                            doRestore = false;
9685                        }
9686                    } else {
9687                        Slog.e(TAG, "Backup Manager not found!");
9688                        doRestore = false;
9689                    }
9690                }
9691
9692                if (!doRestore) {
9693                    // No restore possible, or the Backup Manager was mysteriously not
9694                    // available -- just fire the post-install work request directly.
9695                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9696                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9697                    mHandler.sendMessage(msg);
9698                }
9699            }
9700        });
9701    }
9702
9703    private abstract class HandlerParams {
9704        private static final int MAX_RETRIES = 4;
9705
9706        /**
9707         * Number of times startCopy() has been attempted and had a non-fatal
9708         * error.
9709         */
9710        private int mRetries = 0;
9711
9712        /** User handle for the user requesting the information or installation. */
9713        private final UserHandle mUser;
9714
9715        HandlerParams(UserHandle user) {
9716            mUser = user;
9717        }
9718
9719        UserHandle getUser() {
9720            return mUser;
9721        }
9722
9723        final boolean startCopy() {
9724            boolean res;
9725            try {
9726                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9727
9728                if (++mRetries > MAX_RETRIES) {
9729                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9730                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9731                    handleServiceError();
9732                    return false;
9733                } else {
9734                    handleStartCopy();
9735                    res = true;
9736                }
9737            } catch (RemoteException e) {
9738                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9739                mHandler.sendEmptyMessage(MCS_RECONNECT);
9740                res = false;
9741            }
9742            handleReturnCode();
9743            return res;
9744        }
9745
9746        final void serviceError() {
9747            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9748            handleServiceError();
9749            handleReturnCode();
9750        }
9751
9752        abstract void handleStartCopy() throws RemoteException;
9753        abstract void handleServiceError();
9754        abstract void handleReturnCode();
9755    }
9756
9757    class MeasureParams extends HandlerParams {
9758        private final PackageStats mStats;
9759        private boolean mSuccess;
9760
9761        private final IPackageStatsObserver mObserver;
9762
9763        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9764            super(new UserHandle(stats.userHandle));
9765            mObserver = observer;
9766            mStats = stats;
9767        }
9768
9769        @Override
9770        public String toString() {
9771            return "MeasureParams{"
9772                + Integer.toHexString(System.identityHashCode(this))
9773                + " " + mStats.packageName + "}";
9774        }
9775
9776        @Override
9777        void handleStartCopy() throws RemoteException {
9778            synchronized (mInstallLock) {
9779                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9780            }
9781
9782            if (mSuccess) {
9783                final boolean mounted;
9784                if (Environment.isExternalStorageEmulated()) {
9785                    mounted = true;
9786                } else {
9787                    final String status = Environment.getExternalStorageState();
9788                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9789                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9790                }
9791
9792                if (mounted) {
9793                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9794
9795                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9796                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9797
9798                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9799                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9800
9801                    // Always subtract cache size, since it's a subdirectory
9802                    mStats.externalDataSize -= mStats.externalCacheSize;
9803
9804                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9805                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9806
9807                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9808                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9809                }
9810            }
9811        }
9812
9813        @Override
9814        void handleReturnCode() {
9815            if (mObserver != null) {
9816                try {
9817                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9818                } catch (RemoteException e) {
9819                    Slog.i(TAG, "Observer no longer exists.");
9820                }
9821            }
9822        }
9823
9824        @Override
9825        void handleServiceError() {
9826            Slog.e(TAG, "Could not measure application " + mStats.packageName
9827                            + " external storage");
9828        }
9829    }
9830
9831    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9832            throws RemoteException {
9833        long result = 0;
9834        for (File path : paths) {
9835            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9836        }
9837        return result;
9838    }
9839
9840    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9841        for (File path : paths) {
9842            try {
9843                mcs.clearDirectory(path.getAbsolutePath());
9844            } catch (RemoteException e) {
9845            }
9846        }
9847    }
9848
9849    static class OriginInfo {
9850        /**
9851         * Location where install is coming from, before it has been
9852         * copied/renamed into place. This could be a single monolithic APK
9853         * file, or a cluster directory. This location may be untrusted.
9854         */
9855        final File file;
9856        final String cid;
9857
9858        /**
9859         * Flag indicating that {@link #file} or {@link #cid} has already been
9860         * staged, meaning downstream users don't need to defensively copy the
9861         * contents.
9862         */
9863        final boolean staged;
9864
9865        /**
9866         * Flag indicating that {@link #file} or {@link #cid} is an already
9867         * installed app that is being moved.
9868         */
9869        final boolean existing;
9870
9871        final String resolvedPath;
9872        final File resolvedFile;
9873
9874        static OriginInfo fromNothing() {
9875            return new OriginInfo(null, null, false, false);
9876        }
9877
9878        static OriginInfo fromUntrustedFile(File file) {
9879            return new OriginInfo(file, null, false, false);
9880        }
9881
9882        static OriginInfo fromExistingFile(File file) {
9883            return new OriginInfo(file, null, false, true);
9884        }
9885
9886        static OriginInfo fromStagedFile(File file) {
9887            return new OriginInfo(file, null, true, false);
9888        }
9889
9890        static OriginInfo fromStagedContainer(String cid) {
9891            return new OriginInfo(null, cid, true, false);
9892        }
9893
9894        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9895            this.file = file;
9896            this.cid = cid;
9897            this.staged = staged;
9898            this.existing = existing;
9899
9900            if (cid != null) {
9901                resolvedPath = PackageHelper.getSdDir(cid);
9902                resolvedFile = new File(resolvedPath);
9903            } else if (file != null) {
9904                resolvedPath = file.getAbsolutePath();
9905                resolvedFile = file;
9906            } else {
9907                resolvedPath = null;
9908                resolvedFile = null;
9909            }
9910        }
9911    }
9912
9913    class MoveInfo {
9914        final int moveId;
9915        final String fromUuid;
9916        final String toUuid;
9917        final String packageName;
9918        final String dataAppName;
9919        final int appId;
9920        final String seinfo;
9921
9922        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9923                String dataAppName, int appId, String seinfo) {
9924            this.moveId = moveId;
9925            this.fromUuid = fromUuid;
9926            this.toUuid = toUuid;
9927            this.packageName = packageName;
9928            this.dataAppName = dataAppName;
9929            this.appId = appId;
9930            this.seinfo = seinfo;
9931        }
9932    }
9933
9934    class InstallParams extends HandlerParams {
9935        final OriginInfo origin;
9936        final MoveInfo move;
9937        final IPackageInstallObserver2 observer;
9938        int installFlags;
9939        final String installerPackageName;
9940        final String volumeUuid;
9941        final VerificationParams verificationParams;
9942        private InstallArgs mArgs;
9943        private int mRet;
9944        final String packageAbiOverride;
9945
9946        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
9947                int installFlags, String installerPackageName, String volumeUuid,
9948                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9949            super(user);
9950            this.origin = origin;
9951            this.move = move;
9952            this.observer = observer;
9953            this.installFlags = installFlags;
9954            this.installerPackageName = installerPackageName;
9955            this.volumeUuid = volumeUuid;
9956            this.verificationParams = verificationParams;
9957            this.packageAbiOverride = packageAbiOverride;
9958        }
9959
9960        @Override
9961        public String toString() {
9962            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9963                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9964        }
9965
9966        public ManifestDigest getManifestDigest() {
9967            if (verificationParams == null) {
9968                return null;
9969            }
9970            return verificationParams.getManifestDigest();
9971        }
9972
9973        private int installLocationPolicy(PackageInfoLite pkgLite) {
9974            String packageName = pkgLite.packageName;
9975            int installLocation = pkgLite.installLocation;
9976            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9977            // reader
9978            synchronized (mPackages) {
9979                PackageParser.Package pkg = mPackages.get(packageName);
9980                if (pkg != null) {
9981                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9982                        // Check for downgrading.
9983                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9984                            try {
9985                                checkDowngrade(pkg, pkgLite);
9986                            } catch (PackageManagerException e) {
9987                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9988                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9989                            }
9990                        }
9991                        // Check for updated system application.
9992                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9993                            if (onSd) {
9994                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9995                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9996                            }
9997                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9998                        } else {
9999                            if (onSd) {
10000                                // Install flag overrides everything.
10001                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10002                            }
10003                            // If current upgrade specifies particular preference
10004                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10005                                // Application explicitly specified internal.
10006                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10007                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10008                                // App explictly prefers external. Let policy decide
10009                            } else {
10010                                // Prefer previous location
10011                                if (isExternal(pkg)) {
10012                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10013                                }
10014                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10015                            }
10016                        }
10017                    } else {
10018                        // Invalid install. Return error code
10019                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10020                    }
10021                }
10022            }
10023            // All the special cases have been taken care of.
10024            // Return result based on recommended install location.
10025            if (onSd) {
10026                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10027            }
10028            return pkgLite.recommendedInstallLocation;
10029        }
10030
10031        /*
10032         * Invoke remote method to get package information and install
10033         * location values. Override install location based on default
10034         * policy if needed and then create install arguments based
10035         * on the install location.
10036         */
10037        public void handleStartCopy() throws RemoteException {
10038            int ret = PackageManager.INSTALL_SUCCEEDED;
10039
10040            // If we're already staged, we've firmly committed to an install location
10041            if (origin.staged) {
10042                if (origin.file != null) {
10043                    installFlags |= PackageManager.INSTALL_INTERNAL;
10044                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10045                } else if (origin.cid != null) {
10046                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10047                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10048                } else {
10049                    throw new IllegalStateException("Invalid stage location");
10050                }
10051            }
10052
10053            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10054            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10055
10056            PackageInfoLite pkgLite = null;
10057
10058            if (onInt && onSd) {
10059                // Check if both bits are set.
10060                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10061                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10062            } else {
10063                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10064                        packageAbiOverride);
10065
10066                /*
10067                 * If we have too little free space, try to free cache
10068                 * before giving up.
10069                 */
10070                if (!origin.staged && pkgLite.recommendedInstallLocation
10071                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10072                    // TODO: focus freeing disk space on the target device
10073                    final StorageManager storage = StorageManager.from(mContext);
10074                    final long lowThreshold = storage.getStorageLowBytes(
10075                            Environment.getDataDirectory());
10076
10077                    final long sizeBytes = mContainerService.calculateInstalledSize(
10078                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10079
10080                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10081                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10082                                installFlags, packageAbiOverride);
10083                    }
10084
10085                    /*
10086                     * The cache free must have deleted the file we
10087                     * downloaded to install.
10088                     *
10089                     * TODO: fix the "freeCache" call to not delete
10090                     *       the file we care about.
10091                     */
10092                    if (pkgLite.recommendedInstallLocation
10093                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10094                        pkgLite.recommendedInstallLocation
10095                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10096                    }
10097                }
10098            }
10099
10100            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10101                int loc = pkgLite.recommendedInstallLocation;
10102                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10103                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10104                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10105                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10106                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10107                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10108                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10109                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10110                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10111                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10112                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10113                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10114                } else {
10115                    // Override with defaults if needed.
10116                    loc = installLocationPolicy(pkgLite);
10117                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10118                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10119                    } else if (!onSd && !onInt) {
10120                        // Override install location with flags
10121                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10122                            // Set the flag to install on external media.
10123                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10124                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10125                        } else {
10126                            // Make sure the flag for installing on external
10127                            // media is unset
10128                            installFlags |= PackageManager.INSTALL_INTERNAL;
10129                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10130                        }
10131                    }
10132                }
10133            }
10134
10135            final InstallArgs args = createInstallArgs(this);
10136            mArgs = args;
10137
10138            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10139                 /*
10140                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10141                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10142                 */
10143                int userIdentifier = getUser().getIdentifier();
10144                if (userIdentifier == UserHandle.USER_ALL
10145                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10146                    userIdentifier = UserHandle.USER_OWNER;
10147                }
10148
10149                /*
10150                 * Determine if we have any installed package verifiers. If we
10151                 * do, then we'll defer to them to verify the packages.
10152                 */
10153                final int requiredUid = mRequiredVerifierPackage == null ? -1
10154                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10155                if (!origin.existing && requiredUid != -1
10156                        && isVerificationEnabled(userIdentifier, installFlags)) {
10157                    final Intent verification = new Intent(
10158                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10159                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10160                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10161                            PACKAGE_MIME_TYPE);
10162                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10163
10164                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10165                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10166                            0 /* TODO: Which userId? */);
10167
10168                    if (DEBUG_VERIFY) {
10169                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10170                                + verification.toString() + " with " + pkgLite.verifiers.length
10171                                + " optional verifiers");
10172                    }
10173
10174                    final int verificationId = mPendingVerificationToken++;
10175
10176                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10177
10178                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10179                            installerPackageName);
10180
10181                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10182                            installFlags);
10183
10184                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10185                            pkgLite.packageName);
10186
10187                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10188                            pkgLite.versionCode);
10189
10190                    if (verificationParams != null) {
10191                        if (verificationParams.getVerificationURI() != null) {
10192                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10193                                 verificationParams.getVerificationURI());
10194                        }
10195                        if (verificationParams.getOriginatingURI() != null) {
10196                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10197                                  verificationParams.getOriginatingURI());
10198                        }
10199                        if (verificationParams.getReferrer() != null) {
10200                            verification.putExtra(Intent.EXTRA_REFERRER,
10201                                  verificationParams.getReferrer());
10202                        }
10203                        if (verificationParams.getOriginatingUid() >= 0) {
10204                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10205                                  verificationParams.getOriginatingUid());
10206                        }
10207                        if (verificationParams.getInstallerUid() >= 0) {
10208                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10209                                  verificationParams.getInstallerUid());
10210                        }
10211                    }
10212
10213                    final PackageVerificationState verificationState = new PackageVerificationState(
10214                            requiredUid, args);
10215
10216                    mPendingVerification.append(verificationId, verificationState);
10217
10218                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10219                            receivers, verificationState);
10220
10221                    /*
10222                     * If any sufficient verifiers were listed in the package
10223                     * manifest, attempt to ask them.
10224                     */
10225                    if (sufficientVerifiers != null) {
10226                        final int N = sufficientVerifiers.size();
10227                        if (N == 0) {
10228                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10229                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10230                        } else {
10231                            for (int i = 0; i < N; i++) {
10232                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10233
10234                                final Intent sufficientIntent = new Intent(verification);
10235                                sufficientIntent.setComponent(verifierComponent);
10236
10237                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10238                            }
10239                        }
10240                    }
10241
10242                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10243                            mRequiredVerifierPackage, receivers);
10244                    if (ret == PackageManager.INSTALL_SUCCEEDED
10245                            && mRequiredVerifierPackage != null) {
10246                        /*
10247                         * Send the intent to the required verification agent,
10248                         * but only start the verification timeout after the
10249                         * target BroadcastReceivers have run.
10250                         */
10251                        verification.setComponent(requiredVerifierComponent);
10252                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10253                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10254                                new BroadcastReceiver() {
10255                                    @Override
10256                                    public void onReceive(Context context, Intent intent) {
10257                                        final Message msg = mHandler
10258                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10259                                        msg.arg1 = verificationId;
10260                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10261                                    }
10262                                }, null, 0, null, null);
10263
10264                        /*
10265                         * We don't want the copy to proceed until verification
10266                         * succeeds, so null out this field.
10267                         */
10268                        mArgs = null;
10269                    }
10270                } else {
10271                    /*
10272                     * No package verification is enabled, so immediately start
10273                     * the remote call to initiate copy using temporary file.
10274                     */
10275                    ret = args.copyApk(mContainerService, true);
10276                }
10277            }
10278
10279            mRet = ret;
10280        }
10281
10282        @Override
10283        void handleReturnCode() {
10284            // If mArgs is null, then MCS couldn't be reached. When it
10285            // reconnects, it will try again to install. At that point, this
10286            // will succeed.
10287            if (mArgs != null) {
10288                processPendingInstall(mArgs, mRet);
10289            }
10290        }
10291
10292        @Override
10293        void handleServiceError() {
10294            mArgs = createInstallArgs(this);
10295            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10296        }
10297
10298        public boolean isForwardLocked() {
10299            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10300        }
10301    }
10302
10303    /**
10304     * Used during creation of InstallArgs
10305     *
10306     * @param installFlags package installation flags
10307     * @return true if should be installed on external storage
10308     */
10309    private static boolean installOnExternalAsec(int installFlags) {
10310        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10311            return false;
10312        }
10313        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10314            return true;
10315        }
10316        return false;
10317    }
10318
10319    /**
10320     * Used during creation of InstallArgs
10321     *
10322     * @param installFlags package installation flags
10323     * @return true if should be installed as forward locked
10324     */
10325    private static boolean installForwardLocked(int installFlags) {
10326        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10327    }
10328
10329    private InstallArgs createInstallArgs(InstallParams params) {
10330        if (params.move != null) {
10331            return new MoveInstallArgs(params);
10332        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10333            return new AsecInstallArgs(params);
10334        } else {
10335            return new FileInstallArgs(params);
10336        }
10337    }
10338
10339    /**
10340     * Create args that describe an existing installed package. Typically used
10341     * when cleaning up old installs, or used as a move source.
10342     */
10343    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10344            String resourcePath, String[] instructionSets) {
10345        final boolean isInAsec;
10346        if (installOnExternalAsec(installFlags)) {
10347            /* Apps on SD card are always in ASEC containers. */
10348            isInAsec = true;
10349        } else if (installForwardLocked(installFlags)
10350                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10351            /*
10352             * Forward-locked apps are only in ASEC containers if they're the
10353             * new style
10354             */
10355            isInAsec = true;
10356        } else {
10357            isInAsec = false;
10358        }
10359
10360        if (isInAsec) {
10361            return new AsecInstallArgs(codePath, instructionSets,
10362                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10363        } else {
10364            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10365        }
10366    }
10367
10368    static abstract class InstallArgs {
10369        /** @see InstallParams#origin */
10370        final OriginInfo origin;
10371        /** @see InstallParams#move */
10372        final MoveInfo move;
10373
10374        final IPackageInstallObserver2 observer;
10375        // Always refers to PackageManager flags only
10376        final int installFlags;
10377        final String installerPackageName;
10378        final String volumeUuid;
10379        final ManifestDigest manifestDigest;
10380        final UserHandle user;
10381        final String abiOverride;
10382
10383        // The list of instruction sets supported by this app. This is currently
10384        // only used during the rmdex() phase to clean up resources. We can get rid of this
10385        // if we move dex files under the common app path.
10386        /* nullable */ String[] instructionSets;
10387
10388        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10389                int installFlags, String installerPackageName, String volumeUuid,
10390                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10391                String abiOverride) {
10392            this.origin = origin;
10393            this.move = move;
10394            this.installFlags = installFlags;
10395            this.observer = observer;
10396            this.installerPackageName = installerPackageName;
10397            this.volumeUuid = volumeUuid;
10398            this.manifestDigest = manifestDigest;
10399            this.user = user;
10400            this.instructionSets = instructionSets;
10401            this.abiOverride = abiOverride;
10402        }
10403
10404        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10405        abstract int doPreInstall(int status);
10406
10407        /**
10408         * Rename package into final resting place. All paths on the given
10409         * scanned package should be updated to reflect the rename.
10410         */
10411        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10412        abstract int doPostInstall(int status, int uid);
10413
10414        /** @see PackageSettingBase#codePathString */
10415        abstract String getCodePath();
10416        /** @see PackageSettingBase#resourcePathString */
10417        abstract String getResourcePath();
10418
10419        // Need installer lock especially for dex file removal.
10420        abstract void cleanUpResourcesLI();
10421        abstract boolean doPostDeleteLI(boolean delete);
10422
10423        /**
10424         * Called before the source arguments are copied. This is used mostly
10425         * for MoveParams when it needs to read the source file to put it in the
10426         * destination.
10427         */
10428        int doPreCopy() {
10429            return PackageManager.INSTALL_SUCCEEDED;
10430        }
10431
10432        /**
10433         * Called after the source arguments are copied. This is used mostly for
10434         * MoveParams when it needs to read the source file to put it in the
10435         * destination.
10436         *
10437         * @return
10438         */
10439        int doPostCopy(int uid) {
10440            return PackageManager.INSTALL_SUCCEEDED;
10441        }
10442
10443        protected boolean isFwdLocked() {
10444            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10445        }
10446
10447        protected boolean isExternalAsec() {
10448            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10449        }
10450
10451        UserHandle getUser() {
10452            return user;
10453        }
10454    }
10455
10456    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10457        if (!allCodePaths.isEmpty()) {
10458            if (instructionSets == null) {
10459                throw new IllegalStateException("instructionSet == null");
10460            }
10461            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10462            for (String codePath : allCodePaths) {
10463                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10464                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10465                    if (retCode < 0) {
10466                        Slog.w(TAG, "Couldn't remove dex file for package: "
10467                                + " at location " + codePath + ", retcode=" + retCode);
10468                        // we don't consider this to be a failure of the core package deletion
10469                    }
10470                }
10471            }
10472        }
10473    }
10474
10475    /**
10476     * Logic to handle installation of non-ASEC applications, including copying
10477     * and renaming logic.
10478     */
10479    class FileInstallArgs extends InstallArgs {
10480        private File codeFile;
10481        private File resourceFile;
10482
10483        // Example topology:
10484        // /data/app/com.example/base.apk
10485        // /data/app/com.example/split_foo.apk
10486        // /data/app/com.example/lib/arm/libfoo.so
10487        // /data/app/com.example/lib/arm64/libfoo.so
10488        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10489
10490        /** New install */
10491        FileInstallArgs(InstallParams params) {
10492            super(params.origin, params.move, params.observer, params.installFlags,
10493                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10494                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10495            if (isFwdLocked()) {
10496                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10497            }
10498        }
10499
10500        /** Existing install */
10501        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10502            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10503                    null);
10504            this.codeFile = (codePath != null) ? new File(codePath) : null;
10505            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10506        }
10507
10508        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10509            if (origin.staged) {
10510                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10511                codeFile = origin.file;
10512                resourceFile = origin.file;
10513                return PackageManager.INSTALL_SUCCEEDED;
10514            }
10515
10516            try {
10517                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10518                codeFile = tempDir;
10519                resourceFile = tempDir;
10520            } catch (IOException e) {
10521                Slog.w(TAG, "Failed to create copy file: " + e);
10522                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10523            }
10524
10525            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10526                @Override
10527                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10528                    if (!FileUtils.isValidExtFilename(name)) {
10529                        throw new IllegalArgumentException("Invalid filename: " + name);
10530                    }
10531                    try {
10532                        final File file = new File(codeFile, name);
10533                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10534                                O_RDWR | O_CREAT, 0644);
10535                        Os.chmod(file.getAbsolutePath(), 0644);
10536                        return new ParcelFileDescriptor(fd);
10537                    } catch (ErrnoException e) {
10538                        throw new RemoteException("Failed to open: " + e.getMessage());
10539                    }
10540                }
10541            };
10542
10543            int ret = PackageManager.INSTALL_SUCCEEDED;
10544            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10545            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10546                Slog.e(TAG, "Failed to copy package");
10547                return ret;
10548            }
10549
10550            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10551            NativeLibraryHelper.Handle handle = null;
10552            try {
10553                handle = NativeLibraryHelper.Handle.create(codeFile);
10554                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10555                        abiOverride);
10556            } catch (IOException e) {
10557                Slog.e(TAG, "Copying native libraries failed", e);
10558                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10559            } finally {
10560                IoUtils.closeQuietly(handle);
10561            }
10562
10563            return ret;
10564        }
10565
10566        int doPreInstall(int status) {
10567            if (status != PackageManager.INSTALL_SUCCEEDED) {
10568                cleanUp();
10569            }
10570            return status;
10571        }
10572
10573        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10574            if (status != PackageManager.INSTALL_SUCCEEDED) {
10575                cleanUp();
10576                return false;
10577            }
10578
10579            final File targetDir = codeFile.getParentFile();
10580            final File beforeCodeFile = codeFile;
10581            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10582
10583            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10584            try {
10585                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10586            } catch (ErrnoException e) {
10587                Slog.w(TAG, "Failed to rename", e);
10588                return false;
10589            }
10590
10591            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10592                Slog.w(TAG, "Failed to restorecon");
10593                return false;
10594            }
10595
10596            // Reflect the rename internally
10597            codeFile = afterCodeFile;
10598            resourceFile = afterCodeFile;
10599
10600            // Reflect the rename in scanned details
10601            pkg.codePath = afterCodeFile.getAbsolutePath();
10602            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10603                    pkg.baseCodePath);
10604            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10605                    pkg.splitCodePaths);
10606
10607            // Reflect the rename in app info
10608            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10609            pkg.applicationInfo.setCodePath(pkg.codePath);
10610            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10611            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10612            pkg.applicationInfo.setResourcePath(pkg.codePath);
10613            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10614            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10615
10616            return true;
10617        }
10618
10619        int doPostInstall(int status, int uid) {
10620            if (status != PackageManager.INSTALL_SUCCEEDED) {
10621                cleanUp();
10622            }
10623            return status;
10624        }
10625
10626        @Override
10627        String getCodePath() {
10628            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10629        }
10630
10631        @Override
10632        String getResourcePath() {
10633            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10634        }
10635
10636        private boolean cleanUp() {
10637            if (codeFile == null || !codeFile.exists()) {
10638                return false;
10639            }
10640
10641            if (codeFile.isDirectory()) {
10642                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10643            } else {
10644                codeFile.delete();
10645            }
10646
10647            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10648                resourceFile.delete();
10649            }
10650
10651            return true;
10652        }
10653
10654        void cleanUpResourcesLI() {
10655            // Try enumerating all code paths before deleting
10656            List<String> allCodePaths = Collections.EMPTY_LIST;
10657            if (codeFile != null && codeFile.exists()) {
10658                try {
10659                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10660                    allCodePaths = pkg.getAllCodePaths();
10661                } catch (PackageParserException e) {
10662                    // Ignored; we tried our best
10663                }
10664            }
10665
10666            cleanUp();
10667            removeDexFiles(allCodePaths, instructionSets);
10668        }
10669
10670        boolean doPostDeleteLI(boolean delete) {
10671            // XXX err, shouldn't we respect the delete flag?
10672            cleanUpResourcesLI();
10673            return true;
10674        }
10675    }
10676
10677    private boolean isAsecExternal(String cid) {
10678        final String asecPath = PackageHelper.getSdFilesystem(cid);
10679        return !asecPath.startsWith(mAsecInternalPath);
10680    }
10681
10682    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10683            PackageManagerException {
10684        if (copyRet < 0) {
10685            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10686                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10687                throw new PackageManagerException(copyRet, message);
10688            }
10689        }
10690    }
10691
10692    /**
10693     * Extract the MountService "container ID" from the full code path of an
10694     * .apk.
10695     */
10696    static String cidFromCodePath(String fullCodePath) {
10697        int eidx = fullCodePath.lastIndexOf("/");
10698        String subStr1 = fullCodePath.substring(0, eidx);
10699        int sidx = subStr1.lastIndexOf("/");
10700        return subStr1.substring(sidx+1, eidx);
10701    }
10702
10703    /**
10704     * Logic to handle installation of ASEC applications, including copying and
10705     * renaming logic.
10706     */
10707    class AsecInstallArgs extends InstallArgs {
10708        static final String RES_FILE_NAME = "pkg.apk";
10709        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10710
10711        String cid;
10712        String packagePath;
10713        String resourcePath;
10714
10715        /** New install */
10716        AsecInstallArgs(InstallParams params) {
10717            super(params.origin, params.move, params.observer, params.installFlags,
10718                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10719                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10720        }
10721
10722        /** Existing install */
10723        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10724                        boolean isExternal, boolean isForwardLocked) {
10725            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10726                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10727                    instructionSets, null);
10728            // Hackily pretend we're still looking at a full code path
10729            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10730                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10731            }
10732
10733            // Extract cid from fullCodePath
10734            int eidx = fullCodePath.lastIndexOf("/");
10735            String subStr1 = fullCodePath.substring(0, eidx);
10736            int sidx = subStr1.lastIndexOf("/");
10737            cid = subStr1.substring(sidx+1, eidx);
10738            setMountPath(subStr1);
10739        }
10740
10741        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10742            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10743                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10744                    instructionSets, null);
10745            this.cid = cid;
10746            setMountPath(PackageHelper.getSdDir(cid));
10747        }
10748
10749        void createCopyFile() {
10750            cid = mInstallerService.allocateExternalStageCidLegacy();
10751        }
10752
10753        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10754            if (origin.staged) {
10755                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
10756                cid = origin.cid;
10757                setMountPath(PackageHelper.getSdDir(cid));
10758                return PackageManager.INSTALL_SUCCEEDED;
10759            }
10760
10761            if (temp) {
10762                createCopyFile();
10763            } else {
10764                /*
10765                 * Pre-emptively destroy the container since it's destroyed if
10766                 * copying fails due to it existing anyway.
10767                 */
10768                PackageHelper.destroySdDir(cid);
10769            }
10770
10771            final String newMountPath = imcs.copyPackageToContainer(
10772                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10773                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10774
10775            if (newMountPath != null) {
10776                setMountPath(newMountPath);
10777                return PackageManager.INSTALL_SUCCEEDED;
10778            } else {
10779                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10780            }
10781        }
10782
10783        @Override
10784        String getCodePath() {
10785            return packagePath;
10786        }
10787
10788        @Override
10789        String getResourcePath() {
10790            return resourcePath;
10791        }
10792
10793        int doPreInstall(int status) {
10794            if (status != PackageManager.INSTALL_SUCCEEDED) {
10795                // Destroy container
10796                PackageHelper.destroySdDir(cid);
10797            } else {
10798                boolean mounted = PackageHelper.isContainerMounted(cid);
10799                if (!mounted) {
10800                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10801                            Process.SYSTEM_UID);
10802                    if (newMountPath != null) {
10803                        setMountPath(newMountPath);
10804                    } else {
10805                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10806                    }
10807                }
10808            }
10809            return status;
10810        }
10811
10812        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10813            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10814            String newMountPath = null;
10815            if (PackageHelper.isContainerMounted(cid)) {
10816                // Unmount the container
10817                if (!PackageHelper.unMountSdDir(cid)) {
10818                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10819                    return false;
10820                }
10821            }
10822            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10823                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10824                        " which might be stale. Will try to clean up.");
10825                // Clean up the stale container and proceed to recreate.
10826                if (!PackageHelper.destroySdDir(newCacheId)) {
10827                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10828                    return false;
10829                }
10830                // Successfully cleaned up stale container. Try to rename again.
10831                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10832                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10833                            + " inspite of cleaning it up.");
10834                    return false;
10835                }
10836            }
10837            if (!PackageHelper.isContainerMounted(newCacheId)) {
10838                Slog.w(TAG, "Mounting container " + newCacheId);
10839                newMountPath = PackageHelper.mountSdDir(newCacheId,
10840                        getEncryptKey(), Process.SYSTEM_UID);
10841            } else {
10842                newMountPath = PackageHelper.getSdDir(newCacheId);
10843            }
10844            if (newMountPath == null) {
10845                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10846                return false;
10847            }
10848            Log.i(TAG, "Succesfully renamed " + cid +
10849                    " to " + newCacheId +
10850                    " at new path: " + newMountPath);
10851            cid = newCacheId;
10852
10853            final File beforeCodeFile = new File(packagePath);
10854            setMountPath(newMountPath);
10855            final File afterCodeFile = new File(packagePath);
10856
10857            // Reflect the rename in scanned details
10858            pkg.codePath = afterCodeFile.getAbsolutePath();
10859            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10860                    pkg.baseCodePath);
10861            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10862                    pkg.splitCodePaths);
10863
10864            // Reflect the rename in app info
10865            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10866            pkg.applicationInfo.setCodePath(pkg.codePath);
10867            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10868            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10869            pkg.applicationInfo.setResourcePath(pkg.codePath);
10870            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10871            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10872
10873            return true;
10874        }
10875
10876        private void setMountPath(String mountPath) {
10877            final File mountFile = new File(mountPath);
10878
10879            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10880            if (monolithicFile.exists()) {
10881                packagePath = monolithicFile.getAbsolutePath();
10882                if (isFwdLocked()) {
10883                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10884                } else {
10885                    resourcePath = packagePath;
10886                }
10887            } else {
10888                packagePath = mountFile.getAbsolutePath();
10889                resourcePath = packagePath;
10890            }
10891        }
10892
10893        int doPostInstall(int status, int uid) {
10894            if (status != PackageManager.INSTALL_SUCCEEDED) {
10895                cleanUp();
10896            } else {
10897                final int groupOwner;
10898                final String protectedFile;
10899                if (isFwdLocked()) {
10900                    groupOwner = UserHandle.getSharedAppGid(uid);
10901                    protectedFile = RES_FILE_NAME;
10902                } else {
10903                    groupOwner = -1;
10904                    protectedFile = null;
10905                }
10906
10907                if (uid < Process.FIRST_APPLICATION_UID
10908                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10909                    Slog.e(TAG, "Failed to finalize " + cid);
10910                    PackageHelper.destroySdDir(cid);
10911                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10912                }
10913
10914                boolean mounted = PackageHelper.isContainerMounted(cid);
10915                if (!mounted) {
10916                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10917                }
10918            }
10919            return status;
10920        }
10921
10922        private void cleanUp() {
10923            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10924
10925            // Destroy secure container
10926            PackageHelper.destroySdDir(cid);
10927        }
10928
10929        private List<String> getAllCodePaths() {
10930            final File codeFile = new File(getCodePath());
10931            if (codeFile != null && codeFile.exists()) {
10932                try {
10933                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10934                    return pkg.getAllCodePaths();
10935                } catch (PackageParserException e) {
10936                    // Ignored; we tried our best
10937                }
10938            }
10939            return Collections.EMPTY_LIST;
10940        }
10941
10942        void cleanUpResourcesLI() {
10943            // Enumerate all code paths before deleting
10944            cleanUpResourcesLI(getAllCodePaths());
10945        }
10946
10947        private void cleanUpResourcesLI(List<String> allCodePaths) {
10948            cleanUp();
10949            removeDexFiles(allCodePaths, instructionSets);
10950        }
10951
10952        String getPackageName() {
10953            return getAsecPackageName(cid);
10954        }
10955
10956        boolean doPostDeleteLI(boolean delete) {
10957            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10958            final List<String> allCodePaths = getAllCodePaths();
10959            boolean mounted = PackageHelper.isContainerMounted(cid);
10960            if (mounted) {
10961                // Unmount first
10962                if (PackageHelper.unMountSdDir(cid)) {
10963                    mounted = false;
10964                }
10965            }
10966            if (!mounted && delete) {
10967                cleanUpResourcesLI(allCodePaths);
10968            }
10969            return !mounted;
10970        }
10971
10972        @Override
10973        int doPreCopy() {
10974            if (isFwdLocked()) {
10975                if (!PackageHelper.fixSdPermissions(cid,
10976                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10977                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10978                }
10979            }
10980
10981            return PackageManager.INSTALL_SUCCEEDED;
10982        }
10983
10984        @Override
10985        int doPostCopy(int uid) {
10986            if (isFwdLocked()) {
10987                if (uid < Process.FIRST_APPLICATION_UID
10988                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10989                                RES_FILE_NAME)) {
10990                    Slog.e(TAG, "Failed to finalize " + cid);
10991                    PackageHelper.destroySdDir(cid);
10992                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10993                }
10994            }
10995
10996            return PackageManager.INSTALL_SUCCEEDED;
10997        }
10998    }
10999
11000    /**
11001     * Logic to handle movement of existing installed applications.
11002     */
11003    class MoveInstallArgs extends InstallArgs {
11004        private File codeFile;
11005        private File resourceFile;
11006
11007        /** New install */
11008        MoveInstallArgs(InstallParams params) {
11009            super(params.origin, params.move, params.observer, params.installFlags,
11010                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11011                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11012        }
11013
11014        int copyApk(IMediaContainerService imcs, boolean temp) {
11015            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11016                    + move.fromUuid + " to " + move.toUuid);
11017            synchronized (mInstaller) {
11018                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11019                        move.dataAppName, move.appId, move.seinfo) != 0) {
11020                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11021                }
11022            }
11023
11024            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11025            resourceFile = codeFile;
11026            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11027
11028            return PackageManager.INSTALL_SUCCEEDED;
11029        }
11030
11031        int doPreInstall(int status) {
11032            if (status != PackageManager.INSTALL_SUCCEEDED) {
11033                cleanUp();
11034            }
11035            return status;
11036        }
11037
11038        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11039            if (status != PackageManager.INSTALL_SUCCEEDED) {
11040                cleanUp();
11041                return false;
11042            }
11043
11044            // Reflect the move in app info
11045            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11046            pkg.applicationInfo.setCodePath(pkg.codePath);
11047            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11048            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11049            pkg.applicationInfo.setResourcePath(pkg.codePath);
11050            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11051            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11052
11053            return true;
11054        }
11055
11056        int doPostInstall(int status, int uid) {
11057            if (status != PackageManager.INSTALL_SUCCEEDED) {
11058                cleanUp();
11059            }
11060            return status;
11061        }
11062
11063        @Override
11064        String getCodePath() {
11065            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11066        }
11067
11068        @Override
11069        String getResourcePath() {
11070            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11071        }
11072
11073        private boolean cleanUp() {
11074            if (codeFile == null || !codeFile.exists()) {
11075                return false;
11076            }
11077
11078            if (codeFile.isDirectory()) {
11079                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11080            } else {
11081                codeFile.delete();
11082            }
11083
11084            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11085                resourceFile.delete();
11086            }
11087
11088            return true;
11089        }
11090
11091        void cleanUpResourcesLI() {
11092            cleanUp();
11093        }
11094
11095        boolean doPostDeleteLI(boolean delete) {
11096            // XXX err, shouldn't we respect the delete flag?
11097            cleanUpResourcesLI();
11098            return true;
11099        }
11100    }
11101
11102    static String getAsecPackageName(String packageCid) {
11103        int idx = packageCid.lastIndexOf("-");
11104        if (idx == -1) {
11105            return packageCid;
11106        }
11107        return packageCid.substring(0, idx);
11108    }
11109
11110    // Utility method used to create code paths based on package name and available index.
11111    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11112        String idxStr = "";
11113        int idx = 1;
11114        // Fall back to default value of idx=1 if prefix is not
11115        // part of oldCodePath
11116        if (oldCodePath != null) {
11117            String subStr = oldCodePath;
11118            // Drop the suffix right away
11119            if (suffix != null && subStr.endsWith(suffix)) {
11120                subStr = subStr.substring(0, subStr.length() - suffix.length());
11121            }
11122            // If oldCodePath already contains prefix find out the
11123            // ending index to either increment or decrement.
11124            int sidx = subStr.lastIndexOf(prefix);
11125            if (sidx != -1) {
11126                subStr = subStr.substring(sidx + prefix.length());
11127                if (subStr != null) {
11128                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11129                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11130                    }
11131                    try {
11132                        idx = Integer.parseInt(subStr);
11133                        if (idx <= 1) {
11134                            idx++;
11135                        } else {
11136                            idx--;
11137                        }
11138                    } catch(NumberFormatException e) {
11139                    }
11140                }
11141            }
11142        }
11143        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11144        return prefix + idxStr;
11145    }
11146
11147    private File getNextCodePath(File targetDir, String packageName) {
11148        int suffix = 1;
11149        File result;
11150        do {
11151            result = new File(targetDir, packageName + "-" + suffix);
11152            suffix++;
11153        } while (result.exists());
11154        return result;
11155    }
11156
11157    // Utility method that returns the relative package path with respect
11158    // to the installation directory. Like say for /data/data/com.test-1.apk
11159    // string com.test-1 is returned.
11160    static String deriveCodePathName(String codePath) {
11161        if (codePath == null) {
11162            return null;
11163        }
11164        final File codeFile = new File(codePath);
11165        final String name = codeFile.getName();
11166        if (codeFile.isDirectory()) {
11167            return name;
11168        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11169            final int lastDot = name.lastIndexOf('.');
11170            return name.substring(0, lastDot);
11171        } else {
11172            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11173            return null;
11174        }
11175    }
11176
11177    class PackageInstalledInfo {
11178        String name;
11179        int uid;
11180        // The set of users that originally had this package installed.
11181        int[] origUsers;
11182        // The set of users that now have this package installed.
11183        int[] newUsers;
11184        PackageParser.Package pkg;
11185        int returnCode;
11186        String returnMsg;
11187        PackageRemovedInfo removedInfo;
11188
11189        public void setError(int code, String msg) {
11190            returnCode = code;
11191            returnMsg = msg;
11192            Slog.w(TAG, msg);
11193        }
11194
11195        public void setError(String msg, PackageParserException e) {
11196            returnCode = e.error;
11197            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11198            Slog.w(TAG, msg, e);
11199        }
11200
11201        public void setError(String msg, PackageManagerException e) {
11202            returnCode = e.error;
11203            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11204            Slog.w(TAG, msg, e);
11205        }
11206
11207        // In some error cases we want to convey more info back to the observer
11208        String origPackage;
11209        String origPermission;
11210    }
11211
11212    /*
11213     * Install a non-existing package.
11214     */
11215    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11216            UserHandle user, String installerPackageName, String volumeUuid,
11217            PackageInstalledInfo res) {
11218        // Remember this for later, in case we need to rollback this install
11219        String pkgName = pkg.packageName;
11220
11221        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11222        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11223                UserHandle.USER_OWNER).exists();
11224        synchronized(mPackages) {
11225            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11226                // A package with the same name is already installed, though
11227                // it has been renamed to an older name.  The package we
11228                // are trying to install should be installed as an update to
11229                // the existing one, but that has not been requested, so bail.
11230                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11231                        + " without first uninstalling package running as "
11232                        + mSettings.mRenamedPackages.get(pkgName));
11233                return;
11234            }
11235            if (mPackages.containsKey(pkgName)) {
11236                // Don't allow installation over an existing package with the same name.
11237                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11238                        + " without first uninstalling.");
11239                return;
11240            }
11241        }
11242
11243        try {
11244            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11245                    System.currentTimeMillis(), user);
11246
11247            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11248            // delete the partially installed application. the data directory will have to be
11249            // restored if it was already existing
11250            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11251                // remove package from internal structures.  Note that we want deletePackageX to
11252                // delete the package data and cache directories that it created in
11253                // scanPackageLocked, unless those directories existed before we even tried to
11254                // install.
11255                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11256                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11257                                res.removedInfo, true);
11258            }
11259
11260        } catch (PackageManagerException e) {
11261            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11262        }
11263    }
11264
11265    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11266        // Can't rotate keys during boot or if sharedUser.
11267        if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null
11268                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11269            return false;
11270        }
11271        // app is using upgradeKeySets; make sure all are valid
11272        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11273        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11274        for (int i = 0; i < upgradeKeySets.length; i++) {
11275            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11276                Slog.wtf(TAG, "Package "
11277                         + (oldPs.name != null ? oldPs.name : "<null>")
11278                         + " contains upgrade-key-set reference to unknown key-set: "
11279                         + upgradeKeySets[i]
11280                         + " reverting to signatures check.");
11281                return false;
11282            }
11283        }
11284        return true;
11285    }
11286
11287    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11288        // Upgrade keysets are being used.  Determine if new package has a superset of the
11289        // required keys.
11290        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11291        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11292        for (int i = 0; i < upgradeKeySets.length; i++) {
11293            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11294            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11295                return true;
11296            }
11297        }
11298        return false;
11299    }
11300
11301    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11302            UserHandle user, String installerPackageName, String volumeUuid,
11303            PackageInstalledInfo res) {
11304        final PackageParser.Package oldPackage;
11305        final String pkgName = pkg.packageName;
11306        final int[] allUsers;
11307        final boolean[] perUserInstalled;
11308        final boolean weFroze;
11309
11310        // First find the old package info and check signatures
11311        synchronized(mPackages) {
11312            oldPackage = mPackages.get(pkgName);
11313            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11314            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11315            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11316                if(!checkUpgradeKeySetLP(ps, pkg)) {
11317                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11318                            "New package not signed by keys specified by upgrade-keysets: "
11319                            + pkgName);
11320                    return;
11321                }
11322            } else {
11323                // default to original signature matching
11324                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11325                    != PackageManager.SIGNATURE_MATCH) {
11326                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11327                            "New package has a different signature: " + pkgName);
11328                    return;
11329                }
11330            }
11331
11332            // In case of rollback, remember per-user/profile install state
11333            allUsers = sUserManager.getUserIds();
11334            perUserInstalled = new boolean[allUsers.length];
11335            for (int i = 0; i < allUsers.length; i++) {
11336                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11337            }
11338
11339            // Mark the app as frozen to prevent launching during the upgrade
11340            // process, and then kill all running instances
11341            if (!ps.frozen) {
11342                ps.frozen = true;
11343                weFroze = true;
11344            } else {
11345                weFroze = false;
11346            }
11347        }
11348
11349        // Now that we're guarded by frozen state, kill app during upgrade
11350        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11351
11352        try {
11353            boolean sysPkg = (isSystemApp(oldPackage));
11354            if (sysPkg) {
11355                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11356                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11357            } else {
11358                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11359                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11360            }
11361        } finally {
11362            // Regardless of success or failure of upgrade steps above, always
11363            // unfreeze the package if we froze it
11364            if (weFroze) {
11365                unfreezePackage(pkgName);
11366            }
11367        }
11368    }
11369
11370    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11371            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11372            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11373            String volumeUuid, PackageInstalledInfo res) {
11374        String pkgName = deletedPackage.packageName;
11375        boolean deletedPkg = true;
11376        boolean updatedSettings = false;
11377
11378        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11379                + deletedPackage);
11380        long origUpdateTime;
11381        if (pkg.mExtras != null) {
11382            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11383        } else {
11384            origUpdateTime = 0;
11385        }
11386
11387        // First delete the existing package while retaining the data directory
11388        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11389                res.removedInfo, true)) {
11390            // If the existing package wasn't successfully deleted
11391            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11392            deletedPkg = false;
11393        } else {
11394            // Successfully deleted the old package; proceed with replace.
11395
11396            // If deleted package lived in a container, give users a chance to
11397            // relinquish resources before killing.
11398            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11399                if (DEBUG_INSTALL) {
11400                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11401                }
11402                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11403                final ArrayList<String> pkgList = new ArrayList<String>(1);
11404                pkgList.add(deletedPackage.applicationInfo.packageName);
11405                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11406            }
11407
11408            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11409            try {
11410                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11411                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11412                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11413                        perUserInstalled, res, user);
11414                updatedSettings = true;
11415            } catch (PackageManagerException e) {
11416                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11417            }
11418        }
11419
11420        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11421            // remove package from internal structures.  Note that we want deletePackageX to
11422            // delete the package data and cache directories that it created in
11423            // scanPackageLocked, unless those directories existed before we even tried to
11424            // install.
11425            if(updatedSettings) {
11426                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11427                deletePackageLI(
11428                        pkgName, null, true, allUsers, perUserInstalled,
11429                        PackageManager.DELETE_KEEP_DATA,
11430                                res.removedInfo, true);
11431            }
11432            // Since we failed to install the new package we need to restore the old
11433            // package that we deleted.
11434            if (deletedPkg) {
11435                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11436                File restoreFile = new File(deletedPackage.codePath);
11437                // Parse old package
11438                boolean oldExternal = isExternal(deletedPackage);
11439                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11440                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11441                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11442                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11443                try {
11444                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11445                } catch (PackageManagerException e) {
11446                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11447                            + e.getMessage());
11448                    return;
11449                }
11450                // Restore of old package succeeded. Update permissions.
11451                // writer
11452                synchronized (mPackages) {
11453                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11454                            UPDATE_PERMISSIONS_ALL);
11455                    // can downgrade to reader
11456                    mSettings.writeLPr();
11457                }
11458                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11459            }
11460        }
11461    }
11462
11463    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11464            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11465            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11466            String volumeUuid, PackageInstalledInfo res) {
11467        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11468                + ", old=" + deletedPackage);
11469        boolean disabledSystem = false;
11470        boolean updatedSettings = false;
11471        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11472        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11473                != 0) {
11474            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11475        }
11476        String packageName = deletedPackage.packageName;
11477        if (packageName == null) {
11478            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11479                    "Attempt to delete null packageName.");
11480            return;
11481        }
11482        PackageParser.Package oldPkg;
11483        PackageSetting oldPkgSetting;
11484        // reader
11485        synchronized (mPackages) {
11486            oldPkg = mPackages.get(packageName);
11487            oldPkgSetting = mSettings.mPackages.get(packageName);
11488            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11489                    (oldPkgSetting == null)) {
11490                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11491                        "Couldn't find package:" + packageName + " information");
11492                return;
11493            }
11494        }
11495
11496        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11497        res.removedInfo.removedPackage = packageName;
11498        // Remove existing system package
11499        removePackageLI(oldPkgSetting, true);
11500        // writer
11501        synchronized (mPackages) {
11502            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11503            if (!disabledSystem && deletedPackage != null) {
11504                // We didn't need to disable the .apk as a current system package,
11505                // which means we are replacing another update that is already
11506                // installed.  We need to make sure to delete the older one's .apk.
11507                res.removedInfo.args = createInstallArgsForExisting(0,
11508                        deletedPackage.applicationInfo.getCodePath(),
11509                        deletedPackage.applicationInfo.getResourcePath(),
11510                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11511            } else {
11512                res.removedInfo.args = null;
11513            }
11514        }
11515
11516        // Successfully disabled the old package. Now proceed with re-installation
11517        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11518
11519        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11520        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11521
11522        PackageParser.Package newPackage = null;
11523        try {
11524            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11525            if (newPackage.mExtras != null) {
11526                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11527                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11528                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11529
11530                // is the update attempting to change shared user? that isn't going to work...
11531                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11532                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11533                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11534                            + " to " + newPkgSetting.sharedUser);
11535                    updatedSettings = true;
11536                }
11537            }
11538
11539            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11540                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11541                        perUserInstalled, res, user);
11542                updatedSettings = true;
11543            }
11544
11545        } catch (PackageManagerException e) {
11546            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11547        }
11548
11549        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11550            // Re installation failed. Restore old information
11551            // Remove new pkg information
11552            if (newPackage != null) {
11553                removeInstalledPackageLI(newPackage, true);
11554            }
11555            // Add back the old system package
11556            try {
11557                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11558            } catch (PackageManagerException e) {
11559                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11560            }
11561            // Restore the old system information in Settings
11562            synchronized (mPackages) {
11563                if (disabledSystem) {
11564                    mSettings.enableSystemPackageLPw(packageName);
11565                }
11566                if (updatedSettings) {
11567                    mSettings.setInstallerPackageName(packageName,
11568                            oldPkgSetting.installerPackageName);
11569                }
11570                mSettings.writeLPr();
11571            }
11572        }
11573    }
11574
11575    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11576            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11577            UserHandle user) {
11578        String pkgName = newPackage.packageName;
11579        synchronized (mPackages) {
11580            //write settings. the installStatus will be incomplete at this stage.
11581            //note that the new package setting would have already been
11582            //added to mPackages. It hasn't been persisted yet.
11583            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11584            mSettings.writeLPr();
11585        }
11586
11587        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11588
11589        synchronized (mPackages) {
11590            updatePermissionsLPw(newPackage.packageName, newPackage,
11591                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11592                            ? UPDATE_PERMISSIONS_ALL : 0));
11593            // For system-bundled packages, we assume that installing an upgraded version
11594            // of the package implies that the user actually wants to run that new code,
11595            // so we enable the package.
11596            PackageSetting ps = mSettings.mPackages.get(pkgName);
11597            if (ps != null) {
11598                if (isSystemApp(newPackage)) {
11599                    // NB: implicit assumption that system package upgrades apply to all users
11600                    if (DEBUG_INSTALL) {
11601                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11602                    }
11603                    if (res.origUsers != null) {
11604                        for (int userHandle : res.origUsers) {
11605                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11606                                    userHandle, installerPackageName);
11607                        }
11608                    }
11609                    // Also convey the prior install/uninstall state
11610                    if (allUsers != null && perUserInstalled != null) {
11611                        for (int i = 0; i < allUsers.length; i++) {
11612                            if (DEBUG_INSTALL) {
11613                                Slog.d(TAG, "    user " + allUsers[i]
11614                                        + " => " + perUserInstalled[i]);
11615                            }
11616                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11617                        }
11618                        // these install state changes will be persisted in the
11619                        // upcoming call to mSettings.writeLPr().
11620                    }
11621                }
11622                // It's implied that when a user requests installation, they want the app to be
11623                // installed and enabled.
11624                int userId = user.getIdentifier();
11625                if (userId != UserHandle.USER_ALL) {
11626                    ps.setInstalled(true, userId);
11627                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11628                }
11629            }
11630            res.name = pkgName;
11631            res.uid = newPackage.applicationInfo.uid;
11632            res.pkg = newPackage;
11633            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11634            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11635            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11636            //to update install status
11637            mSettings.writeLPr();
11638        }
11639    }
11640
11641    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11642        final int installFlags = args.installFlags;
11643        final String installerPackageName = args.installerPackageName;
11644        final String volumeUuid = args.volumeUuid;
11645        final File tmpPackageFile = new File(args.getCodePath());
11646        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11647        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11648                || (args.volumeUuid != null));
11649        boolean replace = false;
11650        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11651        // Result object to be returned
11652        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11653
11654        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11655        // Retrieve PackageSettings and parse package
11656        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11657                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11658                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11659        PackageParser pp = new PackageParser();
11660        pp.setSeparateProcesses(mSeparateProcesses);
11661        pp.setDisplayMetrics(mMetrics);
11662
11663        final PackageParser.Package pkg;
11664        try {
11665            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11666        } catch (PackageParserException e) {
11667            res.setError("Failed parse during installPackageLI", e);
11668            return;
11669        }
11670
11671        // Mark that we have an install time CPU ABI override.
11672        pkg.cpuAbiOverride = args.abiOverride;
11673
11674        String pkgName = res.name = pkg.packageName;
11675        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11676            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11677                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11678                return;
11679            }
11680        }
11681
11682        try {
11683            pp.collectCertificates(pkg, parseFlags);
11684            pp.collectManifestDigest(pkg);
11685        } catch (PackageParserException e) {
11686            res.setError("Failed collect during installPackageLI", e);
11687            return;
11688        }
11689
11690        /* If the installer passed in a manifest digest, compare it now. */
11691        if (args.manifestDigest != null) {
11692            if (DEBUG_INSTALL) {
11693                final String parsedManifest = pkg.manifestDigest == null ? "null"
11694                        : pkg.manifestDigest.toString();
11695                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11696                        + parsedManifest);
11697            }
11698
11699            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11700                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11701                return;
11702            }
11703        } else if (DEBUG_INSTALL) {
11704            final String parsedManifest = pkg.manifestDigest == null
11705                    ? "null" : pkg.manifestDigest.toString();
11706            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11707        }
11708
11709        // Get rid of all references to package scan path via parser.
11710        pp = null;
11711        String oldCodePath = null;
11712        boolean systemApp = false;
11713        synchronized (mPackages) {
11714            // Check if installing already existing package
11715            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11716                String oldName = mSettings.mRenamedPackages.get(pkgName);
11717                if (pkg.mOriginalPackages != null
11718                        && pkg.mOriginalPackages.contains(oldName)
11719                        && mPackages.containsKey(oldName)) {
11720                    // This package is derived from an original package,
11721                    // and this device has been updating from that original
11722                    // name.  We must continue using the original name, so
11723                    // rename the new package here.
11724                    pkg.setPackageName(oldName);
11725                    pkgName = pkg.packageName;
11726                    replace = true;
11727                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11728                            + oldName + " pkgName=" + pkgName);
11729                } else if (mPackages.containsKey(pkgName)) {
11730                    // This package, under its official name, already exists
11731                    // on the device; we should replace it.
11732                    replace = true;
11733                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11734                }
11735
11736                // Prevent apps opting out from runtime permissions
11737                if (replace) {
11738                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11739                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11740                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11741                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11742                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11743                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11744                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11745                                        + " doesn't support runtime permissions but the old"
11746                                        + " target SDK " + oldTargetSdk + " does.");
11747                        return;
11748                    }
11749                }
11750            }
11751
11752            PackageSetting ps = mSettings.mPackages.get(pkgName);
11753            if (ps != null) {
11754                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11755
11756                // Quick sanity check that we're signed correctly if updating;
11757                // we'll check this again later when scanning, but we want to
11758                // bail early here before tripping over redefined permissions.
11759                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11760                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11761                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11762                                + pkg.packageName + " upgrade keys do not match the "
11763                                + "previously installed version");
11764                        return;
11765                    }
11766                } else {
11767                    try {
11768                        verifySignaturesLP(ps, pkg);
11769                    } catch (PackageManagerException e) {
11770                        res.setError(e.error, e.getMessage());
11771                        return;
11772                    }
11773                }
11774
11775                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11776                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11777                    systemApp = (ps.pkg.applicationInfo.flags &
11778                            ApplicationInfo.FLAG_SYSTEM) != 0;
11779                }
11780                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11781            }
11782
11783            // Check whether the newly-scanned package wants to define an already-defined perm
11784            int N = pkg.permissions.size();
11785            for (int i = N-1; i >= 0; i--) {
11786                PackageParser.Permission perm = pkg.permissions.get(i);
11787                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11788                if (bp != null) {
11789                    // If the defining package is signed with our cert, it's okay.  This
11790                    // also includes the "updating the same package" case, of course.
11791                    // "updating same package" could also involve key-rotation.
11792                    final boolean sigsOk;
11793                    if (bp.sourcePackage.equals(pkg.packageName)
11794                            && (bp.packageSetting instanceof PackageSetting)
11795                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
11796                                    scanFlags))) {
11797                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11798                    } else {
11799                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11800                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11801                    }
11802                    if (!sigsOk) {
11803                        // If the owning package is the system itself, we log but allow
11804                        // install to proceed; we fail the install on all other permission
11805                        // redefinitions.
11806                        if (!bp.sourcePackage.equals("android")) {
11807                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11808                                    + pkg.packageName + " attempting to redeclare permission "
11809                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11810                            res.origPermission = perm.info.name;
11811                            res.origPackage = bp.sourcePackage;
11812                            return;
11813                        } else {
11814                            Slog.w(TAG, "Package " + pkg.packageName
11815                                    + " attempting to redeclare system permission "
11816                                    + perm.info.name + "; ignoring new declaration");
11817                            pkg.permissions.remove(i);
11818                        }
11819                    }
11820                }
11821            }
11822
11823        }
11824
11825        if (systemApp && onExternal) {
11826            // Disable updates to system apps on sdcard
11827            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11828                    "Cannot install updates to system apps on sdcard");
11829            return;
11830        }
11831
11832        if (args.move != null) {
11833            // We did an in-place move, so dex is ready to roll
11834            scanFlags |= SCAN_NO_DEX;
11835            scanFlags |= SCAN_MOVE;
11836        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11837            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11838            scanFlags |= SCAN_NO_DEX;
11839
11840            try {
11841                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
11842                        true /* extract libs */);
11843            } catch (PackageManagerException pme) {
11844                Slog.e(TAG, "Error deriving application ABI", pme);
11845                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
11846                return;
11847            }
11848
11849            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11850            int result = mPackageDexOptimizer
11851                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
11852                            false /* defer */, false /* inclDependencies */);
11853            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11854                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11855                return;
11856            }
11857        }
11858
11859        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11860            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11861            return;
11862        }
11863
11864        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11865
11866        if (replace) {
11867            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11868                    installerPackageName, volumeUuid, res);
11869        } else {
11870            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11871                    args.user, installerPackageName, volumeUuid, res);
11872        }
11873        synchronized (mPackages) {
11874            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11875            if (ps != null) {
11876                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11877            }
11878        }
11879    }
11880
11881    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11882        if (mIntentFilterVerifierComponent == null) {
11883            Slog.w(TAG, "No IntentFilter verification will not be done as "
11884                    + "there is no IntentFilterVerifier available!");
11885            return;
11886        }
11887
11888        final int verifierUid = getPackageUid(
11889                mIntentFilterVerifierComponent.getPackageName(),
11890                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11891
11892        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11893        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11894        msg.obj = pkg;
11895        msg.arg1 = userId;
11896        msg.arg2 = verifierUid;
11897
11898        mHandler.sendMessage(msg);
11899    }
11900
11901    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11902            PackageParser.Package pkg) {
11903        int size = pkg.activities.size();
11904        if (size == 0) {
11905            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11906                    "No activity, so no need to verify any IntentFilter!");
11907            return;
11908        }
11909
11910        final boolean hasDomainURLs = hasDomainURLs(pkg);
11911        if (!hasDomainURLs) {
11912            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11913                    "No domain URLs, so no need to verify any IntentFilter!");
11914            return;
11915        }
11916
11917        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
11918                + " if any IntentFilter from the " + size
11919                + " Activities needs verification ...");
11920
11921        final int verificationId = mIntentFilterVerificationToken++;
11922        int count = 0;
11923        final String packageName = pkg.packageName;
11924        boolean needToVerify = false;
11925
11926        synchronized (mPackages) {
11927            // If any filters need to be verified, then all need to be.
11928            for (PackageParser.Activity a : pkg.activities) {
11929                for (ActivityIntentInfo filter : a.intents) {
11930                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
11931                        if (DEBUG_DOMAIN_VERIFICATION) {
11932                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
11933                        }
11934                        needToVerify = true;
11935                        break;
11936                    }
11937                }
11938            }
11939            if (needToVerify) {
11940                for (PackageParser.Activity a : pkg.activities) {
11941                    for (ActivityIntentInfo filter : a.intents) {
11942                        boolean needsFilterVerification = filter.hasWebDataURI();
11943                        if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11944                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11945                                    "Verification needed for IntentFilter:" + filter.toString());
11946                            mIntentFilterVerifier.addOneIntentFilterVerification(
11947                                    verifierUid, userId, verificationId, filter, packageName);
11948                            count++;
11949                        }
11950                    }
11951                }
11952            }
11953        }
11954
11955        if (count > 0) {
11956            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
11957                    + " IntentFilter verification" + (count > 1 ? "s" : "")
11958                    +  " for userId:" + userId);
11959            mIntentFilterVerifier.startVerifications(userId);
11960        } else {
11961            if (DEBUG_DOMAIN_VERIFICATION) {
11962                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
11963            }
11964        }
11965    }
11966
11967    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11968        final ComponentName cn  = filter.activity.getComponentName();
11969        final String packageName = cn.getPackageName();
11970
11971        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11972                packageName);
11973        if (ivi == null) {
11974            return true;
11975        }
11976        int status = ivi.getStatus();
11977        switch (status) {
11978            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11979            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11980                return true;
11981
11982            default:
11983                // Nothing to do
11984                return false;
11985        }
11986    }
11987
11988    private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) {
11989        return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID
11990                || ((pkg.applicationInfo.privateFlags
11991                        & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0
11992                && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0);
11993    }
11994
11995    private static boolean isMultiArch(PackageSetting ps) {
11996        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11997    }
11998
11999    private static boolean isMultiArch(ApplicationInfo info) {
12000        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12001    }
12002
12003    private static boolean isExternal(PackageParser.Package pkg) {
12004        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12005    }
12006
12007    private static boolean isExternal(PackageSetting ps) {
12008        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12009    }
12010
12011    private static boolean isExternal(ApplicationInfo info) {
12012        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12013    }
12014
12015    private static boolean isSystemApp(PackageParser.Package pkg) {
12016        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12017    }
12018
12019    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12020        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12021    }
12022
12023    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12024        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12025    }
12026
12027    private static boolean isSystemApp(PackageSetting ps) {
12028        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12029    }
12030
12031    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12032        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12033    }
12034
12035    private int packageFlagsToInstallFlags(PackageSetting ps) {
12036        int installFlags = 0;
12037        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12038            // This existing package was an external ASEC install when we have
12039            // the external flag without a UUID
12040            installFlags |= PackageManager.INSTALL_EXTERNAL;
12041        }
12042        if (ps.isForwardLocked()) {
12043            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12044        }
12045        return installFlags;
12046    }
12047
12048    private void deleteTempPackageFiles() {
12049        final FilenameFilter filter = new FilenameFilter() {
12050            public boolean accept(File dir, String name) {
12051                return name.startsWith("vmdl") && name.endsWith(".tmp");
12052            }
12053        };
12054        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12055            file.delete();
12056        }
12057    }
12058
12059    @Override
12060    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12061            int flags) {
12062        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12063                flags);
12064    }
12065
12066    @Override
12067    public void deletePackage(final String packageName,
12068            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12069        mContext.enforceCallingOrSelfPermission(
12070                android.Manifest.permission.DELETE_PACKAGES, null);
12071        final int uid = Binder.getCallingUid();
12072        if (UserHandle.getUserId(uid) != userId) {
12073            mContext.enforceCallingPermission(
12074                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12075                    "deletePackage for user " + userId);
12076        }
12077        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12078            try {
12079                observer.onPackageDeleted(packageName,
12080                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12081            } catch (RemoteException re) {
12082            }
12083            return;
12084        }
12085
12086        boolean uninstallBlocked = false;
12087        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12088            int[] users = sUserManager.getUserIds();
12089            for (int i = 0; i < users.length; ++i) {
12090                if (getBlockUninstallForUser(packageName, users[i])) {
12091                    uninstallBlocked = true;
12092                    break;
12093                }
12094            }
12095        } else {
12096            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12097        }
12098        if (uninstallBlocked) {
12099            try {
12100                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12101                        null);
12102            } catch (RemoteException re) {
12103            }
12104            return;
12105        }
12106
12107        if (DEBUG_REMOVE) {
12108            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12109        }
12110        // Queue up an async operation since the package deletion may take a little while.
12111        mHandler.post(new Runnable() {
12112            public void run() {
12113                mHandler.removeCallbacks(this);
12114                final int returnCode = deletePackageX(packageName, userId, flags);
12115                if (observer != null) {
12116                    try {
12117                        observer.onPackageDeleted(packageName, returnCode, null);
12118                    } catch (RemoteException e) {
12119                        Log.i(TAG, "Observer no longer exists.");
12120                    } //end catch
12121                } //end if
12122            } //end run
12123        });
12124    }
12125
12126    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12127        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12128                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12129        try {
12130            if (dpm != null) {
12131                if (dpm.isDeviceOwner(packageName)) {
12132                    return true;
12133                }
12134                int[] users;
12135                if (userId == UserHandle.USER_ALL) {
12136                    users = sUserManager.getUserIds();
12137                } else {
12138                    users = new int[]{userId};
12139                }
12140                for (int i = 0; i < users.length; ++i) {
12141                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12142                        return true;
12143                    }
12144                }
12145            }
12146        } catch (RemoteException e) {
12147        }
12148        return false;
12149    }
12150
12151    /**
12152     *  This method is an internal method that could be get invoked either
12153     *  to delete an installed package or to clean up a failed installation.
12154     *  After deleting an installed package, a broadcast is sent to notify any
12155     *  listeners that the package has been installed. For cleaning up a failed
12156     *  installation, the broadcast is not necessary since the package's
12157     *  installation wouldn't have sent the initial broadcast either
12158     *  The key steps in deleting a package are
12159     *  deleting the package information in internal structures like mPackages,
12160     *  deleting the packages base directories through installd
12161     *  updating mSettings to reflect current status
12162     *  persisting settings for later use
12163     *  sending a broadcast if necessary
12164     */
12165    private int deletePackageX(String packageName, int userId, int flags) {
12166        final PackageRemovedInfo info = new PackageRemovedInfo();
12167        final boolean res;
12168
12169        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12170                ? UserHandle.ALL : new UserHandle(userId);
12171
12172        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12173            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12174            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12175        }
12176
12177        boolean removedForAllUsers = false;
12178        boolean systemUpdate = false;
12179
12180        // for the uninstall-updates case and restricted profiles, remember the per-
12181        // userhandle installed state
12182        int[] allUsers;
12183        boolean[] perUserInstalled;
12184        synchronized (mPackages) {
12185            PackageSetting ps = mSettings.mPackages.get(packageName);
12186            allUsers = sUserManager.getUserIds();
12187            perUserInstalled = new boolean[allUsers.length];
12188            for (int i = 0; i < allUsers.length; i++) {
12189                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12190            }
12191        }
12192
12193        synchronized (mInstallLock) {
12194            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12195            res = deletePackageLI(packageName, removeForUser,
12196                    true, allUsers, perUserInstalled,
12197                    flags | REMOVE_CHATTY, info, true);
12198            systemUpdate = info.isRemovedPackageSystemUpdate;
12199            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12200                removedForAllUsers = true;
12201            }
12202            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12203                    + " removedForAllUsers=" + removedForAllUsers);
12204        }
12205
12206        if (res) {
12207            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12208
12209            // If the removed package was a system update, the old system package
12210            // was re-enabled; we need to broadcast this information
12211            if (systemUpdate) {
12212                Bundle extras = new Bundle(1);
12213                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12214                        ? info.removedAppId : info.uid);
12215                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12216
12217                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12218                        extras, null, null, null);
12219                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12220                        extras, null, null, null);
12221                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12222                        null, packageName, null, null);
12223            }
12224        }
12225        // Force a gc here.
12226        Runtime.getRuntime().gc();
12227        // Delete the resources here after sending the broadcast to let
12228        // other processes clean up before deleting resources.
12229        if (info.args != null) {
12230            synchronized (mInstallLock) {
12231                info.args.doPostDeleteLI(true);
12232            }
12233        }
12234
12235        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12236    }
12237
12238    class PackageRemovedInfo {
12239        String removedPackage;
12240        int uid = -1;
12241        int removedAppId = -1;
12242        int[] removedUsers = null;
12243        boolean isRemovedPackageSystemUpdate = false;
12244        // Clean up resources deleted packages.
12245        InstallArgs args = null;
12246
12247        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12248            Bundle extras = new Bundle(1);
12249            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12250            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12251            if (replacing) {
12252                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12253            }
12254            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12255            if (removedPackage != null) {
12256                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12257                        extras, null, null, removedUsers);
12258                if (fullRemove && !replacing) {
12259                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12260                            extras, null, null, removedUsers);
12261                }
12262            }
12263            if (removedAppId >= 0) {
12264                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12265                        removedUsers);
12266            }
12267        }
12268    }
12269
12270    /*
12271     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12272     * flag is not set, the data directory is removed as well.
12273     * make sure this flag is set for partially installed apps. If not its meaningless to
12274     * delete a partially installed application.
12275     */
12276    private void removePackageDataLI(PackageSetting ps,
12277            int[] allUserHandles, boolean[] perUserInstalled,
12278            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12279        String packageName = ps.name;
12280        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12281        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12282        // Retrieve object to delete permissions for shared user later on
12283        final PackageSetting deletedPs;
12284        // reader
12285        synchronized (mPackages) {
12286            deletedPs = mSettings.mPackages.get(packageName);
12287            if (outInfo != null) {
12288                outInfo.removedPackage = packageName;
12289                outInfo.removedUsers = deletedPs != null
12290                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12291                        : null;
12292            }
12293        }
12294        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12295            removeDataDirsLI(ps.volumeUuid, packageName);
12296            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12297        }
12298        // writer
12299        synchronized (mPackages) {
12300            if (deletedPs != null) {
12301                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12302                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12303                    clearDefaultBrowserIfNeeded(packageName);
12304                    if (outInfo != null) {
12305                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12306                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12307                    }
12308                    updatePermissionsLPw(deletedPs.name, null, 0);
12309                    if (deletedPs.sharedUser != null) {
12310                        // Remove permissions associated with package. Since runtime
12311                        // permissions are per user we have to kill the removed package
12312                        // or packages running under the shared user of the removed
12313                        // package if revoking the permissions requested only by the removed
12314                        // package is successful and this causes a change in gids.
12315                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12316                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12317                                    userId);
12318                            if (userIdToKill == UserHandle.USER_ALL
12319                                    || userIdToKill >= UserHandle.USER_OWNER) {
12320                                // If gids changed for this user, kill all affected packages.
12321                                mHandler.post(new Runnable() {
12322                                    @Override
12323                                    public void run() {
12324                                        // This has to happen with no lock held.
12325                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12326                                                KILL_APP_REASON_GIDS_CHANGED);
12327                                    }
12328                                });
12329                            break;
12330                            }
12331                        }
12332                    }
12333                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12334                }
12335                // make sure to preserve per-user disabled state if this removal was just
12336                // a downgrade of a system app to the factory package
12337                if (allUserHandles != null && perUserInstalled != null) {
12338                    if (DEBUG_REMOVE) {
12339                        Slog.d(TAG, "Propagating install state across downgrade");
12340                    }
12341                    for (int i = 0; i < allUserHandles.length; i++) {
12342                        if (DEBUG_REMOVE) {
12343                            Slog.d(TAG, "    user " + allUserHandles[i]
12344                                    + " => " + perUserInstalled[i]);
12345                        }
12346                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12347                    }
12348                }
12349            }
12350            // can downgrade to reader
12351            if (writeSettings) {
12352                // Save settings now
12353                mSettings.writeLPr();
12354            }
12355        }
12356        if (outInfo != null) {
12357            // A user ID was deleted here. Go through all users and remove it
12358            // from KeyStore.
12359            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12360        }
12361    }
12362
12363    static boolean locationIsPrivileged(File path) {
12364        try {
12365            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12366                    .getCanonicalPath();
12367            return path.getCanonicalPath().startsWith(privilegedAppDir);
12368        } catch (IOException e) {
12369            Slog.e(TAG, "Unable to access code path " + path);
12370        }
12371        return false;
12372    }
12373
12374    /*
12375     * Tries to delete system package.
12376     */
12377    private boolean deleteSystemPackageLI(PackageSetting newPs,
12378            int[] allUserHandles, boolean[] perUserInstalled,
12379            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12380        final boolean applyUserRestrictions
12381                = (allUserHandles != null) && (perUserInstalled != null);
12382        PackageSetting disabledPs = null;
12383        // Confirm if the system package has been updated
12384        // An updated system app can be deleted. This will also have to restore
12385        // the system pkg from system partition
12386        // reader
12387        synchronized (mPackages) {
12388            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12389        }
12390        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12391                + " disabledPs=" + disabledPs);
12392        if (disabledPs == null) {
12393            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12394            return false;
12395        } else if (DEBUG_REMOVE) {
12396            Slog.d(TAG, "Deleting system pkg from data partition");
12397        }
12398        if (DEBUG_REMOVE) {
12399            if (applyUserRestrictions) {
12400                Slog.d(TAG, "Remembering install states:");
12401                for (int i = 0; i < allUserHandles.length; i++) {
12402                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12403                }
12404            }
12405        }
12406        // Delete the updated package
12407        outInfo.isRemovedPackageSystemUpdate = true;
12408        if (disabledPs.versionCode < newPs.versionCode) {
12409            // Delete data for downgrades
12410            flags &= ~PackageManager.DELETE_KEEP_DATA;
12411        } else {
12412            // Preserve data by setting flag
12413            flags |= PackageManager.DELETE_KEEP_DATA;
12414        }
12415        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12416                allUserHandles, perUserInstalled, outInfo, writeSettings);
12417        if (!ret) {
12418            return false;
12419        }
12420        // writer
12421        synchronized (mPackages) {
12422            // Reinstate the old system package
12423            mSettings.enableSystemPackageLPw(newPs.name);
12424            // Remove any native libraries from the upgraded package.
12425            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12426        }
12427        // Install the system package
12428        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12429        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12430        if (locationIsPrivileged(disabledPs.codePath)) {
12431            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12432        }
12433
12434        final PackageParser.Package newPkg;
12435        try {
12436            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12437        } catch (PackageManagerException e) {
12438            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12439            return false;
12440        }
12441
12442        // writer
12443        synchronized (mPackages) {
12444            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12445            updatePermissionsLPw(newPkg.packageName, newPkg,
12446                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12447            if (applyUserRestrictions) {
12448                if (DEBUG_REMOVE) {
12449                    Slog.d(TAG, "Propagating install state across reinstall");
12450                }
12451                for (int i = 0; i < allUserHandles.length; i++) {
12452                    if (DEBUG_REMOVE) {
12453                        Slog.d(TAG, "    user " + allUserHandles[i]
12454                                + " => " + perUserInstalled[i]);
12455                    }
12456                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12457                }
12458                // Regardless of writeSettings we need to ensure that this restriction
12459                // state propagation is persisted
12460                mSettings.writeAllUsersPackageRestrictionsLPr();
12461            }
12462            // can downgrade to reader here
12463            if (writeSettings) {
12464                mSettings.writeLPr();
12465            }
12466        }
12467        return true;
12468    }
12469
12470    private boolean deleteInstalledPackageLI(PackageSetting ps,
12471            boolean deleteCodeAndResources, int flags,
12472            int[] allUserHandles, boolean[] perUserInstalled,
12473            PackageRemovedInfo outInfo, boolean writeSettings) {
12474        if (outInfo != null) {
12475            outInfo.uid = ps.appId;
12476        }
12477
12478        // Delete package data from internal structures and also remove data if flag is set
12479        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12480
12481        // Delete application code and resources
12482        if (deleteCodeAndResources && (outInfo != null)) {
12483            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12484                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12485            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12486        }
12487        return true;
12488    }
12489
12490    @Override
12491    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12492            int userId) {
12493        mContext.enforceCallingOrSelfPermission(
12494                android.Manifest.permission.DELETE_PACKAGES, null);
12495        synchronized (mPackages) {
12496            PackageSetting ps = mSettings.mPackages.get(packageName);
12497            if (ps == null) {
12498                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12499                return false;
12500            }
12501            if (!ps.getInstalled(userId)) {
12502                // Can't block uninstall for an app that is not installed or enabled.
12503                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12504                return false;
12505            }
12506            ps.setBlockUninstall(blockUninstall, userId);
12507            mSettings.writePackageRestrictionsLPr(userId);
12508        }
12509        return true;
12510    }
12511
12512    @Override
12513    public boolean getBlockUninstallForUser(String packageName, int userId) {
12514        synchronized (mPackages) {
12515            PackageSetting ps = mSettings.mPackages.get(packageName);
12516            if (ps == null) {
12517                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12518                return false;
12519            }
12520            return ps.getBlockUninstall(userId);
12521        }
12522    }
12523
12524    /*
12525     * This method handles package deletion in general
12526     */
12527    private boolean deletePackageLI(String packageName, UserHandle user,
12528            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12529            int flags, PackageRemovedInfo outInfo,
12530            boolean writeSettings) {
12531        if (packageName == null) {
12532            Slog.w(TAG, "Attempt to delete null packageName.");
12533            return false;
12534        }
12535        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12536        PackageSetting ps;
12537        boolean dataOnly = false;
12538        int removeUser = -1;
12539        int appId = -1;
12540        synchronized (mPackages) {
12541            ps = mSettings.mPackages.get(packageName);
12542            if (ps == null) {
12543                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12544                return false;
12545            }
12546            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12547                    && user.getIdentifier() != UserHandle.USER_ALL) {
12548                // The caller is asking that the package only be deleted for a single
12549                // user.  To do this, we just mark its uninstalled state and delete
12550                // its data.  If this is a system app, we only allow this to happen if
12551                // they have set the special DELETE_SYSTEM_APP which requests different
12552                // semantics than normal for uninstalling system apps.
12553                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12554                ps.setUserState(user.getIdentifier(),
12555                        COMPONENT_ENABLED_STATE_DEFAULT,
12556                        false, //installed
12557                        true,  //stopped
12558                        true,  //notLaunched
12559                        false, //hidden
12560                        null, null, null,
12561                        false, // blockUninstall
12562                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12563                if (!isSystemApp(ps)) {
12564                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12565                        // Other user still have this package installed, so all
12566                        // we need to do is clear this user's data and save that
12567                        // it is uninstalled.
12568                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12569                        removeUser = user.getIdentifier();
12570                        appId = ps.appId;
12571                        scheduleWritePackageRestrictionsLocked(removeUser);
12572                    } else {
12573                        // We need to set it back to 'installed' so the uninstall
12574                        // broadcasts will be sent correctly.
12575                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12576                        ps.setInstalled(true, user.getIdentifier());
12577                    }
12578                } else {
12579                    // This is a system app, so we assume that the
12580                    // other users still have this package installed, so all
12581                    // we need to do is clear this user's data and save that
12582                    // it is uninstalled.
12583                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12584                    removeUser = user.getIdentifier();
12585                    appId = ps.appId;
12586                    scheduleWritePackageRestrictionsLocked(removeUser);
12587                }
12588            }
12589        }
12590
12591        if (removeUser >= 0) {
12592            // From above, we determined that we are deleting this only
12593            // for a single user.  Continue the work here.
12594            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12595            if (outInfo != null) {
12596                outInfo.removedPackage = packageName;
12597                outInfo.removedAppId = appId;
12598                outInfo.removedUsers = new int[] {removeUser};
12599            }
12600            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12601            removeKeystoreDataIfNeeded(removeUser, appId);
12602            schedulePackageCleaning(packageName, removeUser, false);
12603            synchronized (mPackages) {
12604                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12605                    scheduleWritePackageRestrictionsLocked(removeUser);
12606                }
12607            }
12608            return true;
12609        }
12610
12611        if (dataOnly) {
12612            // Delete application data first
12613            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12614            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12615            return true;
12616        }
12617
12618        boolean ret = false;
12619        if (isSystemApp(ps)) {
12620            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12621            // When an updated system application is deleted we delete the existing resources as well and
12622            // fall back to existing code in system partition
12623            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12624                    flags, outInfo, writeSettings);
12625        } else {
12626            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12627            // Kill application pre-emptively especially for apps on sd.
12628            killApplication(packageName, ps.appId, "uninstall pkg");
12629            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12630                    allUserHandles, perUserInstalled,
12631                    outInfo, writeSettings);
12632        }
12633
12634        return ret;
12635    }
12636
12637    private final class ClearStorageConnection implements ServiceConnection {
12638        IMediaContainerService mContainerService;
12639
12640        @Override
12641        public void onServiceConnected(ComponentName name, IBinder service) {
12642            synchronized (this) {
12643                mContainerService = IMediaContainerService.Stub.asInterface(service);
12644                notifyAll();
12645            }
12646        }
12647
12648        @Override
12649        public void onServiceDisconnected(ComponentName name) {
12650        }
12651    }
12652
12653    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12654        final boolean mounted;
12655        if (Environment.isExternalStorageEmulated()) {
12656            mounted = true;
12657        } else {
12658            final String status = Environment.getExternalStorageState();
12659
12660            mounted = status.equals(Environment.MEDIA_MOUNTED)
12661                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12662        }
12663
12664        if (!mounted) {
12665            return;
12666        }
12667
12668        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12669        int[] users;
12670        if (userId == UserHandle.USER_ALL) {
12671            users = sUserManager.getUserIds();
12672        } else {
12673            users = new int[] { userId };
12674        }
12675        final ClearStorageConnection conn = new ClearStorageConnection();
12676        if (mContext.bindServiceAsUser(
12677                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12678            try {
12679                for (int curUser : users) {
12680                    long timeout = SystemClock.uptimeMillis() + 5000;
12681                    synchronized (conn) {
12682                        long now = SystemClock.uptimeMillis();
12683                        while (conn.mContainerService == null && now < timeout) {
12684                            try {
12685                                conn.wait(timeout - now);
12686                            } catch (InterruptedException e) {
12687                            }
12688                        }
12689                    }
12690                    if (conn.mContainerService == null) {
12691                        return;
12692                    }
12693
12694                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12695                    clearDirectory(conn.mContainerService,
12696                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12697                    if (allData) {
12698                        clearDirectory(conn.mContainerService,
12699                                userEnv.buildExternalStorageAppDataDirs(packageName));
12700                        clearDirectory(conn.mContainerService,
12701                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12702                    }
12703                }
12704            } finally {
12705                mContext.unbindService(conn);
12706            }
12707        }
12708    }
12709
12710    @Override
12711    public void clearApplicationUserData(final String packageName,
12712            final IPackageDataObserver observer, final int userId) {
12713        mContext.enforceCallingOrSelfPermission(
12714                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12715        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12716        // Queue up an async operation since the package deletion may take a little while.
12717        mHandler.post(new Runnable() {
12718            public void run() {
12719                mHandler.removeCallbacks(this);
12720                final boolean succeeded;
12721                synchronized (mInstallLock) {
12722                    succeeded = clearApplicationUserDataLI(packageName, userId);
12723                }
12724                clearExternalStorageDataSync(packageName, userId, true);
12725                if (succeeded) {
12726                    // invoke DeviceStorageMonitor's update method to clear any notifications
12727                    DeviceStorageMonitorInternal
12728                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12729                    if (dsm != null) {
12730                        dsm.checkMemory();
12731                    }
12732                }
12733                if(observer != null) {
12734                    try {
12735                        observer.onRemoveCompleted(packageName, succeeded);
12736                    } catch (RemoteException e) {
12737                        Log.i(TAG, "Observer no longer exists.");
12738                    }
12739                } //end if observer
12740            } //end run
12741        });
12742    }
12743
12744    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12745        if (packageName == null) {
12746            Slog.w(TAG, "Attempt to delete null packageName.");
12747            return false;
12748        }
12749
12750        // Try finding details about the requested package
12751        PackageParser.Package pkg;
12752        synchronized (mPackages) {
12753            pkg = mPackages.get(packageName);
12754            if (pkg == null) {
12755                final PackageSetting ps = mSettings.mPackages.get(packageName);
12756                if (ps != null) {
12757                    pkg = ps.pkg;
12758                }
12759            }
12760
12761            if (pkg == null) {
12762                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12763                return false;
12764            }
12765
12766            PackageSetting ps = (PackageSetting) pkg.mExtras;
12767            PermissionsState permissionsState = ps.getPermissionsState();
12768            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
12769        }
12770
12771        // Always delete data directories for package, even if we found no other
12772        // record of app. This helps users recover from UID mismatches without
12773        // resorting to a full data wipe.
12774        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12775        if (retCode < 0) {
12776            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12777            return false;
12778        }
12779
12780        final int appId = pkg.applicationInfo.uid;
12781        removeKeystoreDataIfNeeded(userId, appId);
12782
12783        // Create a native library symlink only if we have native libraries
12784        // and if the native libraries are 32 bit libraries. We do not provide
12785        // this symlink for 64 bit libraries.
12786        if (pkg.applicationInfo.primaryCpuAbi != null &&
12787                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12788            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12789            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12790                    nativeLibPath, userId) < 0) {
12791                Slog.w(TAG, "Failed linking native library dir");
12792                return false;
12793            }
12794        }
12795
12796        return true;
12797    }
12798
12799
12800    /**
12801     * Revokes granted runtime permissions and clears resettable flags
12802     * which are flags that can be set by a user interaction.
12803     *
12804     * @param permissionsState The permission state to reset.
12805     * @param userId The device user for which to do a reset.
12806     */
12807    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
12808            PermissionsState permissionsState, int userId) {
12809        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
12810                | PackageManager.FLAG_PERMISSION_USER_FIXED
12811                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12812
12813        boolean needsWrite = false;
12814
12815        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
12816            BasePermission bp = mSettings.mPermissions.get(state.getName());
12817            if (bp != null) {
12818                permissionsState.revokeRuntimePermission(bp, userId);
12819                permissionsState.updatePermissionFlags(bp, userId, userSetFlags, 0);
12820                needsWrite = true;
12821            }
12822        }
12823
12824        if (needsWrite) {
12825            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
12826        }
12827    }
12828
12829    /**
12830     * Remove entries from the keystore daemon. Will only remove it if the
12831     * {@code appId} is valid.
12832     */
12833    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12834        if (appId < 0) {
12835            return;
12836        }
12837
12838        final KeyStore keyStore = KeyStore.getInstance();
12839        if (keyStore != null) {
12840            if (userId == UserHandle.USER_ALL) {
12841                for (final int individual : sUserManager.getUserIds()) {
12842                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12843                }
12844            } else {
12845                keyStore.clearUid(UserHandle.getUid(userId, appId));
12846            }
12847        } else {
12848            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12849        }
12850    }
12851
12852    @Override
12853    public void deleteApplicationCacheFiles(final String packageName,
12854            final IPackageDataObserver observer) {
12855        mContext.enforceCallingOrSelfPermission(
12856                android.Manifest.permission.DELETE_CACHE_FILES, null);
12857        // Queue up an async operation since the package deletion may take a little while.
12858        final int userId = UserHandle.getCallingUserId();
12859        mHandler.post(new Runnable() {
12860            public void run() {
12861                mHandler.removeCallbacks(this);
12862                final boolean succeded;
12863                synchronized (mInstallLock) {
12864                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12865                }
12866                clearExternalStorageDataSync(packageName, userId, false);
12867                if (observer != null) {
12868                    try {
12869                        observer.onRemoveCompleted(packageName, succeded);
12870                    } catch (RemoteException e) {
12871                        Log.i(TAG, "Observer no longer exists.");
12872                    }
12873                } //end if observer
12874            } //end run
12875        });
12876    }
12877
12878    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12879        if (packageName == null) {
12880            Slog.w(TAG, "Attempt to delete null packageName.");
12881            return false;
12882        }
12883        PackageParser.Package p;
12884        synchronized (mPackages) {
12885            p = mPackages.get(packageName);
12886        }
12887        if (p == null) {
12888            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12889            return false;
12890        }
12891        final ApplicationInfo applicationInfo = p.applicationInfo;
12892        if (applicationInfo == null) {
12893            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12894            return false;
12895        }
12896        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12897        if (retCode < 0) {
12898            Slog.w(TAG, "Couldn't remove cache files for package: "
12899                       + packageName + " u" + userId);
12900            return false;
12901        }
12902        return true;
12903    }
12904
12905    @Override
12906    public void getPackageSizeInfo(final String packageName, int userHandle,
12907            final IPackageStatsObserver observer) {
12908        mContext.enforceCallingOrSelfPermission(
12909                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12910        if (packageName == null) {
12911            throw new IllegalArgumentException("Attempt to get size of null packageName");
12912        }
12913
12914        PackageStats stats = new PackageStats(packageName, userHandle);
12915
12916        /*
12917         * Queue up an async operation since the package measurement may take a
12918         * little while.
12919         */
12920        Message msg = mHandler.obtainMessage(INIT_COPY);
12921        msg.obj = new MeasureParams(stats, observer);
12922        mHandler.sendMessage(msg);
12923    }
12924
12925    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12926            PackageStats pStats) {
12927        if (packageName == null) {
12928            Slog.w(TAG, "Attempt to get size of null packageName.");
12929            return false;
12930        }
12931        PackageParser.Package p;
12932        boolean dataOnly = false;
12933        String libDirRoot = null;
12934        String asecPath = null;
12935        PackageSetting ps = null;
12936        synchronized (mPackages) {
12937            p = mPackages.get(packageName);
12938            ps = mSettings.mPackages.get(packageName);
12939            if(p == null) {
12940                dataOnly = true;
12941                if((ps == null) || (ps.pkg == null)) {
12942                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12943                    return false;
12944                }
12945                p = ps.pkg;
12946            }
12947            if (ps != null) {
12948                libDirRoot = ps.legacyNativeLibraryPathString;
12949            }
12950            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12951                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12952                if (secureContainerId != null) {
12953                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12954                }
12955            }
12956        }
12957        String publicSrcDir = null;
12958        if(!dataOnly) {
12959            final ApplicationInfo applicationInfo = p.applicationInfo;
12960            if (applicationInfo == null) {
12961                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12962                return false;
12963            }
12964            if (p.isForwardLocked()) {
12965                publicSrcDir = applicationInfo.getBaseResourcePath();
12966            }
12967        }
12968        // TODO: extend to measure size of split APKs
12969        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12970        // not just the first level.
12971        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12972        // just the primary.
12973        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12974        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
12975                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12976        if (res < 0) {
12977            return false;
12978        }
12979
12980        // Fix-up for forward-locked applications in ASEC containers.
12981        if (!isExternal(p)) {
12982            pStats.codeSize += pStats.externalCodeSize;
12983            pStats.externalCodeSize = 0L;
12984        }
12985
12986        return true;
12987    }
12988
12989
12990    @Override
12991    public void addPackageToPreferred(String packageName) {
12992        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12993    }
12994
12995    @Override
12996    public void removePackageFromPreferred(String packageName) {
12997        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12998    }
12999
13000    @Override
13001    public List<PackageInfo> getPreferredPackages(int flags) {
13002        return new ArrayList<PackageInfo>();
13003    }
13004
13005    private int getUidTargetSdkVersionLockedLPr(int uid) {
13006        Object obj = mSettings.getUserIdLPr(uid);
13007        if (obj instanceof SharedUserSetting) {
13008            final SharedUserSetting sus = (SharedUserSetting) obj;
13009            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13010            final Iterator<PackageSetting> it = sus.packages.iterator();
13011            while (it.hasNext()) {
13012                final PackageSetting ps = it.next();
13013                if (ps.pkg != null) {
13014                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13015                    if (v < vers) vers = v;
13016                }
13017            }
13018            return vers;
13019        } else if (obj instanceof PackageSetting) {
13020            final PackageSetting ps = (PackageSetting) obj;
13021            if (ps.pkg != null) {
13022                return ps.pkg.applicationInfo.targetSdkVersion;
13023            }
13024        }
13025        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13026    }
13027
13028    @Override
13029    public void addPreferredActivity(IntentFilter filter, int match,
13030            ComponentName[] set, ComponentName activity, int userId) {
13031        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13032                "Adding preferred");
13033    }
13034
13035    private void addPreferredActivityInternal(IntentFilter filter, int match,
13036            ComponentName[] set, ComponentName activity, boolean always, int userId,
13037            String opname) {
13038        // writer
13039        int callingUid = Binder.getCallingUid();
13040        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13041        if (filter.countActions() == 0) {
13042            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13043            return;
13044        }
13045        synchronized (mPackages) {
13046            if (mContext.checkCallingOrSelfPermission(
13047                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13048                    != PackageManager.PERMISSION_GRANTED) {
13049                if (getUidTargetSdkVersionLockedLPr(callingUid)
13050                        < Build.VERSION_CODES.FROYO) {
13051                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13052                            + callingUid);
13053                    return;
13054                }
13055                mContext.enforceCallingOrSelfPermission(
13056                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13057            }
13058
13059            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13060            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13061                    + userId + ":");
13062            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13063            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13064            scheduleWritePackageRestrictionsLocked(userId);
13065        }
13066    }
13067
13068    @Override
13069    public void replacePreferredActivity(IntentFilter filter, int match,
13070            ComponentName[] set, ComponentName activity, int userId) {
13071        if (filter.countActions() != 1) {
13072            throw new IllegalArgumentException(
13073                    "replacePreferredActivity expects filter to have only 1 action.");
13074        }
13075        if (filter.countDataAuthorities() != 0
13076                || filter.countDataPaths() != 0
13077                || filter.countDataSchemes() > 1
13078                || filter.countDataTypes() != 0) {
13079            throw new IllegalArgumentException(
13080                    "replacePreferredActivity expects filter to have no data authorities, " +
13081                    "paths, or types; and at most one scheme.");
13082        }
13083
13084        final int callingUid = Binder.getCallingUid();
13085        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13086        synchronized (mPackages) {
13087            if (mContext.checkCallingOrSelfPermission(
13088                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13089                    != PackageManager.PERMISSION_GRANTED) {
13090                if (getUidTargetSdkVersionLockedLPr(callingUid)
13091                        < Build.VERSION_CODES.FROYO) {
13092                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13093                            + Binder.getCallingUid());
13094                    return;
13095                }
13096                mContext.enforceCallingOrSelfPermission(
13097                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13098            }
13099
13100            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13101            if (pir != null) {
13102                // Get all of the existing entries that exactly match this filter.
13103                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13104                if (existing != null && existing.size() == 1) {
13105                    PreferredActivity cur = existing.get(0);
13106                    if (DEBUG_PREFERRED) {
13107                        Slog.i(TAG, "Checking replace of preferred:");
13108                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13109                        if (!cur.mPref.mAlways) {
13110                            Slog.i(TAG, "  -- CUR; not mAlways!");
13111                        } else {
13112                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13113                            Slog.i(TAG, "  -- CUR: mSet="
13114                                    + Arrays.toString(cur.mPref.mSetComponents));
13115                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13116                            Slog.i(TAG, "  -- NEW: mMatch="
13117                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13118                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13119                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13120                        }
13121                    }
13122                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13123                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13124                            && cur.mPref.sameSet(set)) {
13125                        // Setting the preferred activity to what it happens to be already
13126                        if (DEBUG_PREFERRED) {
13127                            Slog.i(TAG, "Replacing with same preferred activity "
13128                                    + cur.mPref.mShortComponent + " for user "
13129                                    + userId + ":");
13130                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13131                        }
13132                        return;
13133                    }
13134                }
13135
13136                if (existing != null) {
13137                    if (DEBUG_PREFERRED) {
13138                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13139                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13140                    }
13141                    for (int i = 0; i < existing.size(); i++) {
13142                        PreferredActivity pa = existing.get(i);
13143                        if (DEBUG_PREFERRED) {
13144                            Slog.i(TAG, "Removing existing preferred activity "
13145                                    + pa.mPref.mComponent + ":");
13146                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13147                        }
13148                        pir.removeFilter(pa);
13149                    }
13150                }
13151            }
13152            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13153                    "Replacing preferred");
13154        }
13155    }
13156
13157    @Override
13158    public void clearPackagePreferredActivities(String packageName) {
13159        final int uid = Binder.getCallingUid();
13160        // writer
13161        synchronized (mPackages) {
13162            PackageParser.Package pkg = mPackages.get(packageName);
13163            if (pkg == null || pkg.applicationInfo.uid != uid) {
13164                if (mContext.checkCallingOrSelfPermission(
13165                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13166                        != PackageManager.PERMISSION_GRANTED) {
13167                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13168                            < Build.VERSION_CODES.FROYO) {
13169                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13170                                + Binder.getCallingUid());
13171                        return;
13172                    }
13173                    mContext.enforceCallingOrSelfPermission(
13174                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13175                }
13176            }
13177
13178            int user = UserHandle.getCallingUserId();
13179            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13180                scheduleWritePackageRestrictionsLocked(user);
13181            }
13182        }
13183    }
13184
13185    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13186    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13187        ArrayList<PreferredActivity> removed = null;
13188        boolean changed = false;
13189        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13190            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13191            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13192            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13193                continue;
13194            }
13195            Iterator<PreferredActivity> it = pir.filterIterator();
13196            while (it.hasNext()) {
13197                PreferredActivity pa = it.next();
13198                // Mark entry for removal only if it matches the package name
13199                // and the entry is of type "always".
13200                if (packageName == null ||
13201                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13202                                && pa.mPref.mAlways)) {
13203                    if (removed == null) {
13204                        removed = new ArrayList<PreferredActivity>();
13205                    }
13206                    removed.add(pa);
13207                }
13208            }
13209            if (removed != null) {
13210                for (int j=0; j<removed.size(); j++) {
13211                    PreferredActivity pa = removed.get(j);
13212                    pir.removeFilter(pa);
13213                }
13214                changed = true;
13215            }
13216        }
13217        return changed;
13218    }
13219
13220    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13221    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13222        if (userId == UserHandle.USER_ALL) {
13223            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13224                    sUserManager.getUserIds())) {
13225                for (int oneUserId : sUserManager.getUserIds()) {
13226                    scheduleWritePackageRestrictionsLocked(oneUserId);
13227                }
13228            }
13229        } else {
13230            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13231                scheduleWritePackageRestrictionsLocked(userId);
13232            }
13233        }
13234    }
13235
13236
13237    void clearDefaultBrowserIfNeeded(String packageName) {
13238        for (int oneUserId : sUserManager.getUserIds()) {
13239            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13240            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13241            if (packageName.equals(defaultBrowserPackageName)) {
13242                setDefaultBrowserPackageName(null, oneUserId);
13243            }
13244        }
13245    }
13246
13247    @Override
13248    public void resetPreferredActivities(int userId) {
13249        /* TODO: Actually use userId. Why is it being passed in? */
13250        mContext.enforceCallingOrSelfPermission(
13251                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13252        // writer
13253        synchronized (mPackages) {
13254            int user = UserHandle.getCallingUserId();
13255            clearPackagePreferredActivitiesLPw(null, user);
13256            mSettings.readDefaultPreferredAppsLPw(this, user);
13257            scheduleWritePackageRestrictionsLocked(user);
13258        }
13259    }
13260
13261    @Override
13262    public int getPreferredActivities(List<IntentFilter> outFilters,
13263            List<ComponentName> outActivities, String packageName) {
13264
13265        int num = 0;
13266        final int userId = UserHandle.getCallingUserId();
13267        // reader
13268        synchronized (mPackages) {
13269            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13270            if (pir != null) {
13271                final Iterator<PreferredActivity> it = pir.filterIterator();
13272                while (it.hasNext()) {
13273                    final PreferredActivity pa = it.next();
13274                    if (packageName == null
13275                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13276                                    && pa.mPref.mAlways)) {
13277                        if (outFilters != null) {
13278                            outFilters.add(new IntentFilter(pa));
13279                        }
13280                        if (outActivities != null) {
13281                            outActivities.add(pa.mPref.mComponent);
13282                        }
13283                    }
13284                }
13285            }
13286        }
13287
13288        return num;
13289    }
13290
13291    @Override
13292    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13293            int userId) {
13294        int callingUid = Binder.getCallingUid();
13295        if (callingUid != Process.SYSTEM_UID) {
13296            throw new SecurityException(
13297                    "addPersistentPreferredActivity can only be run by the system");
13298        }
13299        if (filter.countActions() == 0) {
13300            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13301            return;
13302        }
13303        synchronized (mPackages) {
13304            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13305                    " :");
13306            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13307            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13308                    new PersistentPreferredActivity(filter, activity));
13309            scheduleWritePackageRestrictionsLocked(userId);
13310        }
13311    }
13312
13313    @Override
13314    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13315        int callingUid = Binder.getCallingUid();
13316        if (callingUid != Process.SYSTEM_UID) {
13317            throw new SecurityException(
13318                    "clearPackagePersistentPreferredActivities can only be run by the system");
13319        }
13320        ArrayList<PersistentPreferredActivity> removed = null;
13321        boolean changed = false;
13322        synchronized (mPackages) {
13323            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13324                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13325                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13326                        .valueAt(i);
13327                if (userId != thisUserId) {
13328                    continue;
13329                }
13330                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13331                while (it.hasNext()) {
13332                    PersistentPreferredActivity ppa = it.next();
13333                    // Mark entry for removal only if it matches the package name.
13334                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13335                        if (removed == null) {
13336                            removed = new ArrayList<PersistentPreferredActivity>();
13337                        }
13338                        removed.add(ppa);
13339                    }
13340                }
13341                if (removed != null) {
13342                    for (int j=0; j<removed.size(); j++) {
13343                        PersistentPreferredActivity ppa = removed.get(j);
13344                        ppir.removeFilter(ppa);
13345                    }
13346                    changed = true;
13347                }
13348            }
13349
13350            if (changed) {
13351                scheduleWritePackageRestrictionsLocked(userId);
13352            }
13353        }
13354    }
13355
13356    /**
13357     * Non-Binder method, support for the backup/restore mechanism: write the
13358     * full set of preferred activities in its canonical XML format.  Returns true
13359     * on success; false otherwise.
13360     */
13361    @Override
13362    public byte[] getPreferredActivityBackup(int userId) {
13363        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13364            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13365        }
13366
13367        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13368        try {
13369            final XmlSerializer serializer = new FastXmlSerializer();
13370            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13371            serializer.startDocument(null, true);
13372            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13373
13374            synchronized (mPackages) {
13375                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13376            }
13377
13378            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13379            serializer.endDocument();
13380            serializer.flush();
13381        } catch (Exception e) {
13382            if (DEBUG_BACKUP) {
13383                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13384            }
13385            return null;
13386        }
13387
13388        return dataStream.toByteArray();
13389    }
13390
13391    @Override
13392    public void restorePreferredActivities(byte[] backup, int userId) {
13393        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13394            throw new SecurityException("Only the system may call restorePreferredActivities()");
13395        }
13396
13397        try {
13398            final XmlPullParser parser = Xml.newPullParser();
13399            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13400
13401            int type;
13402            while ((type = parser.next()) != XmlPullParser.START_TAG
13403                    && type != XmlPullParser.END_DOCUMENT) {
13404            }
13405            if (type != XmlPullParser.START_TAG) {
13406                // oops didn't find a start tag?!
13407                if (DEBUG_BACKUP) {
13408                    Slog.e(TAG, "Didn't find start tag during restore");
13409                }
13410                return;
13411            }
13412
13413            // this is supposed to be TAG_PREFERRED_BACKUP
13414            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
13415                if (DEBUG_BACKUP) {
13416                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
13417                }
13418                return;
13419            }
13420
13421            // skip interfering stuff, then we're aligned with the backing implementation
13422            while ((type = parser.next()) == XmlPullParser.TEXT) { }
13423            synchronized (mPackages) {
13424                mSettings.readPreferredActivitiesLPw(parser, userId);
13425            }
13426        } catch (Exception e) {
13427            if (DEBUG_BACKUP) {
13428                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13429            }
13430        }
13431    }
13432
13433    @Override
13434    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13435            int sourceUserId, int targetUserId, int flags) {
13436        mContext.enforceCallingOrSelfPermission(
13437                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13438        int callingUid = Binder.getCallingUid();
13439        enforceOwnerRights(ownerPackage, callingUid);
13440        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13441        if (intentFilter.countActions() == 0) {
13442            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13443            return;
13444        }
13445        synchronized (mPackages) {
13446            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13447                    ownerPackage, targetUserId, flags);
13448            CrossProfileIntentResolver resolver =
13449                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13450            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13451            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13452            if (existing != null) {
13453                int size = existing.size();
13454                for (int i = 0; i < size; i++) {
13455                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13456                        return;
13457                    }
13458                }
13459            }
13460            resolver.addFilter(newFilter);
13461            scheduleWritePackageRestrictionsLocked(sourceUserId);
13462        }
13463    }
13464
13465    @Override
13466    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13467        mContext.enforceCallingOrSelfPermission(
13468                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13469        int callingUid = Binder.getCallingUid();
13470        enforceOwnerRights(ownerPackage, callingUid);
13471        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13472        synchronized (mPackages) {
13473            CrossProfileIntentResolver resolver =
13474                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13475            ArraySet<CrossProfileIntentFilter> set =
13476                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13477            for (CrossProfileIntentFilter filter : set) {
13478                if (filter.getOwnerPackage().equals(ownerPackage)) {
13479                    resolver.removeFilter(filter);
13480                }
13481            }
13482            scheduleWritePackageRestrictionsLocked(sourceUserId);
13483        }
13484    }
13485
13486    // Enforcing that callingUid is owning pkg on userId
13487    private void enforceOwnerRights(String pkg, int callingUid) {
13488        // The system owns everything.
13489        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13490            return;
13491        }
13492        int callingUserId = UserHandle.getUserId(callingUid);
13493        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13494        if (pi == null) {
13495            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13496                    + callingUserId);
13497        }
13498        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13499            throw new SecurityException("Calling uid " + callingUid
13500                    + " does not own package " + pkg);
13501        }
13502    }
13503
13504    @Override
13505    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13506        Intent intent = new Intent(Intent.ACTION_MAIN);
13507        intent.addCategory(Intent.CATEGORY_HOME);
13508
13509        final int callingUserId = UserHandle.getCallingUserId();
13510        List<ResolveInfo> list = queryIntentActivities(intent, null,
13511                PackageManager.GET_META_DATA, callingUserId);
13512        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13513                true, false, false, callingUserId);
13514
13515        allHomeCandidates.clear();
13516        if (list != null) {
13517            for (ResolveInfo ri : list) {
13518                allHomeCandidates.add(ri);
13519            }
13520        }
13521        return (preferred == null || preferred.activityInfo == null)
13522                ? null
13523                : new ComponentName(preferred.activityInfo.packageName,
13524                        preferred.activityInfo.name);
13525    }
13526
13527    @Override
13528    public void setApplicationEnabledSetting(String appPackageName,
13529            int newState, int flags, int userId, String callingPackage) {
13530        if (!sUserManager.exists(userId)) return;
13531        if (callingPackage == null) {
13532            callingPackage = Integer.toString(Binder.getCallingUid());
13533        }
13534        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13535    }
13536
13537    @Override
13538    public void setComponentEnabledSetting(ComponentName componentName,
13539            int newState, int flags, int userId) {
13540        if (!sUserManager.exists(userId)) return;
13541        setEnabledSetting(componentName.getPackageName(),
13542                componentName.getClassName(), newState, flags, userId, null);
13543    }
13544
13545    private void setEnabledSetting(final String packageName, String className, int newState,
13546            final int flags, int userId, String callingPackage) {
13547        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13548              || newState == COMPONENT_ENABLED_STATE_ENABLED
13549              || newState == COMPONENT_ENABLED_STATE_DISABLED
13550              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13551              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13552            throw new IllegalArgumentException("Invalid new component state: "
13553                    + newState);
13554        }
13555        PackageSetting pkgSetting;
13556        final int uid = Binder.getCallingUid();
13557        final int permission = mContext.checkCallingOrSelfPermission(
13558                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13559        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13560        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13561        boolean sendNow = false;
13562        boolean isApp = (className == null);
13563        String componentName = isApp ? packageName : className;
13564        int packageUid = -1;
13565        ArrayList<String> components;
13566
13567        // writer
13568        synchronized (mPackages) {
13569            pkgSetting = mSettings.mPackages.get(packageName);
13570            if (pkgSetting == null) {
13571                if (className == null) {
13572                    throw new IllegalArgumentException(
13573                            "Unknown package: " + packageName);
13574                }
13575                throw new IllegalArgumentException(
13576                        "Unknown component: " + packageName
13577                        + "/" + className);
13578            }
13579            // Allow root and verify that userId is not being specified by a different user
13580            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13581                throw new SecurityException(
13582                        "Permission Denial: attempt to change component state from pid="
13583                        + Binder.getCallingPid()
13584                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13585            }
13586            if (className == null) {
13587                // We're dealing with an application/package level state change
13588                if (pkgSetting.getEnabled(userId) == newState) {
13589                    // Nothing to do
13590                    return;
13591                }
13592                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13593                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13594                    // Don't care about who enables an app.
13595                    callingPackage = null;
13596                }
13597                pkgSetting.setEnabled(newState, userId, callingPackage);
13598                // pkgSetting.pkg.mSetEnabled = newState;
13599            } else {
13600                // We're dealing with a component level state change
13601                // First, verify that this is a valid class name.
13602                PackageParser.Package pkg = pkgSetting.pkg;
13603                if (pkg == null || !pkg.hasComponentClassName(className)) {
13604                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13605                        throw new IllegalArgumentException("Component class " + className
13606                                + " does not exist in " + packageName);
13607                    } else {
13608                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13609                                + className + " does not exist in " + packageName);
13610                    }
13611                }
13612                switch (newState) {
13613                case COMPONENT_ENABLED_STATE_ENABLED:
13614                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13615                        return;
13616                    }
13617                    break;
13618                case COMPONENT_ENABLED_STATE_DISABLED:
13619                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13620                        return;
13621                    }
13622                    break;
13623                case COMPONENT_ENABLED_STATE_DEFAULT:
13624                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13625                        return;
13626                    }
13627                    break;
13628                default:
13629                    Slog.e(TAG, "Invalid new component state: " + newState);
13630                    return;
13631                }
13632            }
13633            scheduleWritePackageRestrictionsLocked(userId);
13634            components = mPendingBroadcasts.get(userId, packageName);
13635            final boolean newPackage = components == null;
13636            if (newPackage) {
13637                components = new ArrayList<String>();
13638            }
13639            if (!components.contains(componentName)) {
13640                components.add(componentName);
13641            }
13642            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13643                sendNow = true;
13644                // Purge entry from pending broadcast list if another one exists already
13645                // since we are sending one right away.
13646                mPendingBroadcasts.remove(userId, packageName);
13647            } else {
13648                if (newPackage) {
13649                    mPendingBroadcasts.put(userId, packageName, components);
13650                }
13651                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13652                    // Schedule a message
13653                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13654                }
13655            }
13656        }
13657
13658        long callingId = Binder.clearCallingIdentity();
13659        try {
13660            if (sendNow) {
13661                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13662                sendPackageChangedBroadcast(packageName,
13663                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13664            }
13665        } finally {
13666            Binder.restoreCallingIdentity(callingId);
13667        }
13668    }
13669
13670    private void sendPackageChangedBroadcast(String packageName,
13671            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13672        if (DEBUG_INSTALL)
13673            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13674                    + componentNames);
13675        Bundle extras = new Bundle(4);
13676        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13677        String nameList[] = new String[componentNames.size()];
13678        componentNames.toArray(nameList);
13679        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13680        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13681        extras.putInt(Intent.EXTRA_UID, packageUid);
13682        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13683                new int[] {UserHandle.getUserId(packageUid)});
13684    }
13685
13686    @Override
13687    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13688        if (!sUserManager.exists(userId)) return;
13689        final int uid = Binder.getCallingUid();
13690        final int permission = mContext.checkCallingOrSelfPermission(
13691                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13692        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13693        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13694        // writer
13695        synchronized (mPackages) {
13696            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13697                    allowedByPermission, uid, userId)) {
13698                scheduleWritePackageRestrictionsLocked(userId);
13699            }
13700        }
13701    }
13702
13703    @Override
13704    public String getInstallerPackageName(String packageName) {
13705        // reader
13706        synchronized (mPackages) {
13707            return mSettings.getInstallerPackageNameLPr(packageName);
13708        }
13709    }
13710
13711    @Override
13712    public int getApplicationEnabledSetting(String packageName, int userId) {
13713        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13714        int uid = Binder.getCallingUid();
13715        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13716        // reader
13717        synchronized (mPackages) {
13718            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13719        }
13720    }
13721
13722    @Override
13723    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13724        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13725        int uid = Binder.getCallingUid();
13726        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13727        // reader
13728        synchronized (mPackages) {
13729            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13730        }
13731    }
13732
13733    @Override
13734    public void enterSafeMode() {
13735        enforceSystemOrRoot("Only the system can request entering safe mode");
13736
13737        if (!mSystemReady) {
13738            mSafeMode = true;
13739        }
13740    }
13741
13742    @Override
13743    public void systemReady() {
13744        mSystemReady = true;
13745
13746        // Read the compatibilty setting when the system is ready.
13747        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13748                mContext.getContentResolver(),
13749                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13750        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13751        if (DEBUG_SETTINGS) {
13752            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13753        }
13754
13755        synchronized (mPackages) {
13756            // Verify that all of the preferred activity components actually
13757            // exist.  It is possible for applications to be updated and at
13758            // that point remove a previously declared activity component that
13759            // had been set as a preferred activity.  We try to clean this up
13760            // the next time we encounter that preferred activity, but it is
13761            // possible for the user flow to never be able to return to that
13762            // situation so here we do a sanity check to make sure we haven't
13763            // left any junk around.
13764            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13765            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13766                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13767                removed.clear();
13768                for (PreferredActivity pa : pir.filterSet()) {
13769                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13770                        removed.add(pa);
13771                    }
13772                }
13773                if (removed.size() > 0) {
13774                    for (int r=0; r<removed.size(); r++) {
13775                        PreferredActivity pa = removed.get(r);
13776                        Slog.w(TAG, "Removing dangling preferred activity: "
13777                                + pa.mPref.mComponent);
13778                        pir.removeFilter(pa);
13779                    }
13780                    mSettings.writePackageRestrictionsLPr(
13781                            mSettings.mPreferredActivities.keyAt(i));
13782                }
13783            }
13784        }
13785        sUserManager.systemReady();
13786
13787        // Kick off any messages waiting for system ready
13788        if (mPostSystemReadyMessages != null) {
13789            for (Message msg : mPostSystemReadyMessages) {
13790                msg.sendToTarget();
13791            }
13792            mPostSystemReadyMessages = null;
13793        }
13794
13795        // Watch for external volumes that come and go over time
13796        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13797        storage.registerListener(mStorageListener);
13798
13799        mInstallerService.systemReady();
13800        mPackageDexOptimizer.systemReady();
13801    }
13802
13803    @Override
13804    public boolean isSafeMode() {
13805        return mSafeMode;
13806    }
13807
13808    @Override
13809    public boolean hasSystemUidErrors() {
13810        return mHasSystemUidErrors;
13811    }
13812
13813    static String arrayToString(int[] array) {
13814        StringBuffer buf = new StringBuffer(128);
13815        buf.append('[');
13816        if (array != null) {
13817            for (int i=0; i<array.length; i++) {
13818                if (i > 0) buf.append(", ");
13819                buf.append(array[i]);
13820            }
13821        }
13822        buf.append(']');
13823        return buf.toString();
13824    }
13825
13826    static class DumpState {
13827        public static final int DUMP_LIBS = 1 << 0;
13828        public static final int DUMP_FEATURES = 1 << 1;
13829        public static final int DUMP_RESOLVERS = 1 << 2;
13830        public static final int DUMP_PERMISSIONS = 1 << 3;
13831        public static final int DUMP_PACKAGES = 1 << 4;
13832        public static final int DUMP_SHARED_USERS = 1 << 5;
13833        public static final int DUMP_MESSAGES = 1 << 6;
13834        public static final int DUMP_PROVIDERS = 1 << 7;
13835        public static final int DUMP_VERIFIERS = 1 << 8;
13836        public static final int DUMP_PREFERRED = 1 << 9;
13837        public static final int DUMP_PREFERRED_XML = 1 << 10;
13838        public static final int DUMP_KEYSETS = 1 << 11;
13839        public static final int DUMP_VERSION = 1 << 12;
13840        public static final int DUMP_INSTALLS = 1 << 13;
13841        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13842        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13843
13844        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13845
13846        private int mTypes;
13847
13848        private int mOptions;
13849
13850        private boolean mTitlePrinted;
13851
13852        private SharedUserSetting mSharedUser;
13853
13854        public boolean isDumping(int type) {
13855            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13856                return true;
13857            }
13858
13859            return (mTypes & type) != 0;
13860        }
13861
13862        public void setDump(int type) {
13863            mTypes |= type;
13864        }
13865
13866        public boolean isOptionEnabled(int option) {
13867            return (mOptions & option) != 0;
13868        }
13869
13870        public void setOptionEnabled(int option) {
13871            mOptions |= option;
13872        }
13873
13874        public boolean onTitlePrinted() {
13875            final boolean printed = mTitlePrinted;
13876            mTitlePrinted = true;
13877            return printed;
13878        }
13879
13880        public boolean getTitlePrinted() {
13881            return mTitlePrinted;
13882        }
13883
13884        public void setTitlePrinted(boolean enabled) {
13885            mTitlePrinted = enabled;
13886        }
13887
13888        public SharedUserSetting getSharedUser() {
13889            return mSharedUser;
13890        }
13891
13892        public void setSharedUser(SharedUserSetting user) {
13893            mSharedUser = user;
13894        }
13895    }
13896
13897    @Override
13898    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13899        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13900                != PackageManager.PERMISSION_GRANTED) {
13901            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13902                    + Binder.getCallingPid()
13903                    + ", uid=" + Binder.getCallingUid()
13904                    + " without permission "
13905                    + android.Manifest.permission.DUMP);
13906            return;
13907        }
13908
13909        DumpState dumpState = new DumpState();
13910        boolean fullPreferred = false;
13911        boolean checkin = false;
13912
13913        String packageName = null;
13914
13915        int opti = 0;
13916        while (opti < args.length) {
13917            String opt = args[opti];
13918            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13919                break;
13920            }
13921            opti++;
13922
13923            if ("-a".equals(opt)) {
13924                // Right now we only know how to print all.
13925            } else if ("-h".equals(opt)) {
13926                pw.println("Package manager dump options:");
13927                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13928                pw.println("    --checkin: dump for a checkin");
13929                pw.println("    -f: print details of intent filters");
13930                pw.println("    -h: print this help");
13931                pw.println("  cmd may be one of:");
13932                pw.println("    l[ibraries]: list known shared libraries");
13933                pw.println("    f[ibraries]: list device features");
13934                pw.println("    k[eysets]: print known keysets");
13935                pw.println("    r[esolvers]: dump intent resolvers");
13936                pw.println("    perm[issions]: dump permissions");
13937                pw.println("    pref[erred]: print preferred package settings");
13938                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13939                pw.println("    prov[iders]: dump content providers");
13940                pw.println("    p[ackages]: dump installed packages");
13941                pw.println("    s[hared-users]: dump shared user IDs");
13942                pw.println("    m[essages]: print collected runtime messages");
13943                pw.println("    v[erifiers]: print package verifier info");
13944                pw.println("    version: print database version info");
13945                pw.println("    write: write current settings now");
13946                pw.println("    <package.name>: info about given package");
13947                pw.println("    installs: details about install sessions");
13948                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13949                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13950                return;
13951            } else if ("--checkin".equals(opt)) {
13952                checkin = true;
13953            } else if ("-f".equals(opt)) {
13954                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13955            } else {
13956                pw.println("Unknown argument: " + opt + "; use -h for help");
13957            }
13958        }
13959
13960        // Is the caller requesting to dump a particular piece of data?
13961        if (opti < args.length) {
13962            String cmd = args[opti];
13963            opti++;
13964            // Is this a package name?
13965            if ("android".equals(cmd) || cmd.contains(".")) {
13966                packageName = cmd;
13967                // When dumping a single package, we always dump all of its
13968                // filter information since the amount of data will be reasonable.
13969                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13970            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13971                dumpState.setDump(DumpState.DUMP_LIBS);
13972            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13973                dumpState.setDump(DumpState.DUMP_FEATURES);
13974            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13975                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13976            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13977                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13978            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13979                dumpState.setDump(DumpState.DUMP_PREFERRED);
13980            } else if ("preferred-xml".equals(cmd)) {
13981                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13982                if (opti < args.length && "--full".equals(args[opti])) {
13983                    fullPreferred = true;
13984                    opti++;
13985                }
13986            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13987                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13988            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13989                dumpState.setDump(DumpState.DUMP_PACKAGES);
13990            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13991                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13992            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13993                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13994            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13995                dumpState.setDump(DumpState.DUMP_MESSAGES);
13996            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13997                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13998            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13999                    || "intent-filter-verifiers".equals(cmd)) {
14000                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14001            } else if ("version".equals(cmd)) {
14002                dumpState.setDump(DumpState.DUMP_VERSION);
14003            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14004                dumpState.setDump(DumpState.DUMP_KEYSETS);
14005            } else if ("installs".equals(cmd)) {
14006                dumpState.setDump(DumpState.DUMP_INSTALLS);
14007            } else if ("write".equals(cmd)) {
14008                synchronized (mPackages) {
14009                    mSettings.writeLPr();
14010                    pw.println("Settings written.");
14011                    return;
14012                }
14013            }
14014        }
14015
14016        if (checkin) {
14017            pw.println("vers,1");
14018        }
14019
14020        // reader
14021        synchronized (mPackages) {
14022            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14023                if (!checkin) {
14024                    if (dumpState.onTitlePrinted())
14025                        pw.println();
14026                    pw.println("Database versions:");
14027                    pw.print("  SDK Version:");
14028                    pw.print(" internal=");
14029                    pw.print(mSettings.mInternalSdkPlatform);
14030                    pw.print(" external=");
14031                    pw.println(mSettings.mExternalSdkPlatform);
14032                    pw.print("  DB Version:");
14033                    pw.print(" internal=");
14034                    pw.print(mSettings.mInternalDatabaseVersion);
14035                    pw.print(" external=");
14036                    pw.println(mSettings.mExternalDatabaseVersion);
14037                }
14038            }
14039
14040            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14041                if (!checkin) {
14042                    if (dumpState.onTitlePrinted())
14043                        pw.println();
14044                    pw.println("Verifiers:");
14045                    pw.print("  Required: ");
14046                    pw.print(mRequiredVerifierPackage);
14047                    pw.print(" (uid=");
14048                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14049                    pw.println(")");
14050                } else if (mRequiredVerifierPackage != null) {
14051                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14052                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14053                }
14054            }
14055
14056            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14057                    packageName == null) {
14058                if (mIntentFilterVerifierComponent != null) {
14059                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14060                    if (!checkin) {
14061                        if (dumpState.onTitlePrinted())
14062                            pw.println();
14063                        pw.println("Intent Filter Verifier:");
14064                        pw.print("  Using: ");
14065                        pw.print(verifierPackageName);
14066                        pw.print(" (uid=");
14067                        pw.print(getPackageUid(verifierPackageName, 0));
14068                        pw.println(")");
14069                    } else if (verifierPackageName != null) {
14070                        pw.print("ifv,"); pw.print(verifierPackageName);
14071                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14072                    }
14073                } else {
14074                    pw.println();
14075                    pw.println("No Intent Filter Verifier available!");
14076                }
14077            }
14078
14079            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14080                boolean printedHeader = false;
14081                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14082                while (it.hasNext()) {
14083                    String name = it.next();
14084                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14085                    if (!checkin) {
14086                        if (!printedHeader) {
14087                            if (dumpState.onTitlePrinted())
14088                                pw.println();
14089                            pw.println("Libraries:");
14090                            printedHeader = true;
14091                        }
14092                        pw.print("  ");
14093                    } else {
14094                        pw.print("lib,");
14095                    }
14096                    pw.print(name);
14097                    if (!checkin) {
14098                        pw.print(" -> ");
14099                    }
14100                    if (ent.path != null) {
14101                        if (!checkin) {
14102                            pw.print("(jar) ");
14103                            pw.print(ent.path);
14104                        } else {
14105                            pw.print(",jar,");
14106                            pw.print(ent.path);
14107                        }
14108                    } else {
14109                        if (!checkin) {
14110                            pw.print("(apk) ");
14111                            pw.print(ent.apk);
14112                        } else {
14113                            pw.print(",apk,");
14114                            pw.print(ent.apk);
14115                        }
14116                    }
14117                    pw.println();
14118                }
14119            }
14120
14121            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14122                if (dumpState.onTitlePrinted())
14123                    pw.println();
14124                if (!checkin) {
14125                    pw.println("Features:");
14126                }
14127                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14128                while (it.hasNext()) {
14129                    String name = it.next();
14130                    if (!checkin) {
14131                        pw.print("  ");
14132                    } else {
14133                        pw.print("feat,");
14134                    }
14135                    pw.println(name);
14136                }
14137            }
14138
14139            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14140                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14141                        : "Activity Resolver Table:", "  ", packageName,
14142                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14143                    dumpState.setTitlePrinted(true);
14144                }
14145                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14146                        : "Receiver Resolver Table:", "  ", packageName,
14147                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14148                    dumpState.setTitlePrinted(true);
14149                }
14150                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14151                        : "Service Resolver Table:", "  ", packageName,
14152                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14153                    dumpState.setTitlePrinted(true);
14154                }
14155                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14156                        : "Provider Resolver Table:", "  ", packageName,
14157                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14158                    dumpState.setTitlePrinted(true);
14159                }
14160            }
14161
14162            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14163                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14164                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14165                    int user = mSettings.mPreferredActivities.keyAt(i);
14166                    if (pir.dump(pw,
14167                            dumpState.getTitlePrinted()
14168                                ? "\nPreferred Activities User " + user + ":"
14169                                : "Preferred Activities User " + user + ":", "  ",
14170                            packageName, true, false)) {
14171                        dumpState.setTitlePrinted(true);
14172                    }
14173                }
14174            }
14175
14176            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14177                pw.flush();
14178                FileOutputStream fout = new FileOutputStream(fd);
14179                BufferedOutputStream str = new BufferedOutputStream(fout);
14180                XmlSerializer serializer = new FastXmlSerializer();
14181                try {
14182                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14183                    serializer.startDocument(null, true);
14184                    serializer.setFeature(
14185                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14186                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14187                    serializer.endDocument();
14188                    serializer.flush();
14189                } catch (IllegalArgumentException e) {
14190                    pw.println("Failed writing: " + e);
14191                } catch (IllegalStateException e) {
14192                    pw.println("Failed writing: " + e);
14193                } catch (IOException e) {
14194                    pw.println("Failed writing: " + e);
14195                }
14196            }
14197
14198            if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) {
14199                pw.println();
14200                int count = mSettings.mPackages.size();
14201                if (count == 0) {
14202                    pw.println("No domain preferred apps!");
14203                    pw.println();
14204                } else {
14205                    final String prefix = "  ";
14206                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14207                    if (allPackageSettings.size() == 0) {
14208                        pw.println("No domain preferred apps!");
14209                        pw.println();
14210                    } else {
14211                        pw.println("Domain preferred apps status:");
14212                        pw.println();
14213                        count = 0;
14214                        for (PackageSetting ps : allPackageSettings) {
14215                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14216                            if (ivi == null || ivi.getPackageName() == null) continue;
14217                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14218                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14219                            pw.println(prefix + "Status: " + ivi.getStatusString());
14220                            pw.println();
14221                            count++;
14222                        }
14223                        if (count == 0) {
14224                            pw.println(prefix + "No domain preferred app status!");
14225                            pw.println();
14226                        }
14227                        for (int userId : sUserManager.getUserIds()) {
14228                            pw.println("Domain preferred apps for User " + userId + ":");
14229                            pw.println();
14230                            count = 0;
14231                            for (PackageSetting ps : allPackageSettings) {
14232                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14233                                if (ivi == null || ivi.getPackageName() == null) {
14234                                    continue;
14235                                }
14236                                final int status = ps.getDomainVerificationStatusForUser(userId);
14237                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14238                                    continue;
14239                                }
14240                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14241                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14242                                String statusStr = IntentFilterVerificationInfo.
14243                                        getStatusStringFromValue(status);
14244                                pw.println(prefix + "Status: " + statusStr);
14245                                pw.println();
14246                                count++;
14247                            }
14248                            if (count == 0) {
14249                                pw.println(prefix + "No domain preferred apps!");
14250                                pw.println();
14251                            }
14252                        }
14253                    }
14254                }
14255            }
14256
14257            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14258                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
14259                if (packageName == null) {
14260                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14261                        if (iperm == 0) {
14262                            if (dumpState.onTitlePrinted())
14263                                pw.println();
14264                            pw.println("AppOp Permissions:");
14265                        }
14266                        pw.print("  AppOp Permission ");
14267                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14268                        pw.println(":");
14269                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14270                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14271                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14272                        }
14273                    }
14274                }
14275            }
14276
14277            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14278                boolean printedSomething = false;
14279                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14280                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14281                        continue;
14282                    }
14283                    if (!printedSomething) {
14284                        if (dumpState.onTitlePrinted())
14285                            pw.println();
14286                        pw.println("Registered ContentProviders:");
14287                        printedSomething = true;
14288                    }
14289                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14290                    pw.print("    "); pw.println(p.toString());
14291                }
14292                printedSomething = false;
14293                for (Map.Entry<String, PackageParser.Provider> entry :
14294                        mProvidersByAuthority.entrySet()) {
14295                    PackageParser.Provider p = entry.getValue();
14296                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14297                        continue;
14298                    }
14299                    if (!printedSomething) {
14300                        if (dumpState.onTitlePrinted())
14301                            pw.println();
14302                        pw.println("ContentProvider Authorities:");
14303                        printedSomething = true;
14304                    }
14305                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14306                    pw.print("    "); pw.println(p.toString());
14307                    if (p.info != null && p.info.applicationInfo != null) {
14308                        final String appInfo = p.info.applicationInfo.toString();
14309                        pw.print("      applicationInfo="); pw.println(appInfo);
14310                    }
14311                }
14312            }
14313
14314            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14315                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14316            }
14317
14318            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14319                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
14320            }
14321
14322            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14323                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
14324            }
14325
14326            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14327                // XXX should handle packageName != null by dumping only install data that
14328                // the given package is involved with.
14329                if (dumpState.onTitlePrinted()) pw.println();
14330                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14331            }
14332
14333            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14334                if (dumpState.onTitlePrinted()) pw.println();
14335                mSettings.dumpReadMessagesLPr(pw, dumpState);
14336
14337                pw.println();
14338                pw.println("Package warning messages:");
14339                BufferedReader in = null;
14340                String line = null;
14341                try {
14342                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14343                    while ((line = in.readLine()) != null) {
14344                        if (line.contains("ignored: updated version")) continue;
14345                        pw.println(line);
14346                    }
14347                } catch (IOException ignored) {
14348                } finally {
14349                    IoUtils.closeQuietly(in);
14350                }
14351            }
14352
14353            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14354                BufferedReader in = null;
14355                String line = null;
14356                try {
14357                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14358                    while ((line = in.readLine()) != null) {
14359                        if (line.contains("ignored: updated version")) continue;
14360                        pw.print("msg,");
14361                        pw.println(line);
14362                    }
14363                } catch (IOException ignored) {
14364                } finally {
14365                    IoUtils.closeQuietly(in);
14366                }
14367            }
14368        }
14369    }
14370
14371    // ------- apps on sdcard specific code -------
14372    static final boolean DEBUG_SD_INSTALL = false;
14373
14374    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14375
14376    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14377
14378    private boolean mMediaMounted = false;
14379
14380    static String getEncryptKey() {
14381        try {
14382            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14383                    SD_ENCRYPTION_KEYSTORE_NAME);
14384            if (sdEncKey == null) {
14385                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14386                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14387                if (sdEncKey == null) {
14388                    Slog.e(TAG, "Failed to create encryption keys");
14389                    return null;
14390                }
14391            }
14392            return sdEncKey;
14393        } catch (NoSuchAlgorithmException nsae) {
14394            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14395            return null;
14396        } catch (IOException ioe) {
14397            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14398            return null;
14399        }
14400    }
14401
14402    /*
14403     * Update media status on PackageManager.
14404     */
14405    @Override
14406    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14407        int callingUid = Binder.getCallingUid();
14408        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14409            throw new SecurityException("Media status can only be updated by the system");
14410        }
14411        // reader; this apparently protects mMediaMounted, but should probably
14412        // be a different lock in that case.
14413        synchronized (mPackages) {
14414            Log.i(TAG, "Updating external media status from "
14415                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14416                    + (mediaStatus ? "mounted" : "unmounted"));
14417            if (DEBUG_SD_INSTALL)
14418                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14419                        + ", mMediaMounted=" + mMediaMounted);
14420            if (mediaStatus == mMediaMounted) {
14421                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14422                        : 0, -1);
14423                mHandler.sendMessage(msg);
14424                return;
14425            }
14426            mMediaMounted = mediaStatus;
14427        }
14428        // Queue up an async operation since the package installation may take a
14429        // little while.
14430        mHandler.post(new Runnable() {
14431            public void run() {
14432                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14433            }
14434        });
14435    }
14436
14437    /**
14438     * Called by MountService when the initial ASECs to scan are available.
14439     * Should block until all the ASEC containers are finished being scanned.
14440     */
14441    public void scanAvailableAsecs() {
14442        updateExternalMediaStatusInner(true, false, false);
14443        if (mShouldRestoreconData) {
14444            SELinuxMMAC.setRestoreconDone();
14445            mShouldRestoreconData = false;
14446        }
14447    }
14448
14449    /*
14450     * Collect information of applications on external media, map them against
14451     * existing containers and update information based on current mount status.
14452     * Please note that we always have to report status if reportStatus has been
14453     * set to true especially when unloading packages.
14454     */
14455    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14456            boolean externalStorage) {
14457        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14458        int[] uidArr = EmptyArray.INT;
14459
14460        final String[] list = PackageHelper.getSecureContainerList();
14461        if (ArrayUtils.isEmpty(list)) {
14462            Log.i(TAG, "No secure containers found");
14463        } else {
14464            // Process list of secure containers and categorize them
14465            // as active or stale based on their package internal state.
14466
14467            // reader
14468            synchronized (mPackages) {
14469                for (String cid : list) {
14470                    // Leave stages untouched for now; installer service owns them
14471                    if (PackageInstallerService.isStageName(cid)) continue;
14472
14473                    if (DEBUG_SD_INSTALL)
14474                        Log.i(TAG, "Processing container " + cid);
14475                    String pkgName = getAsecPackageName(cid);
14476                    if (pkgName == null) {
14477                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14478                        continue;
14479                    }
14480                    if (DEBUG_SD_INSTALL)
14481                        Log.i(TAG, "Looking for pkg : " + pkgName);
14482
14483                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14484                    if (ps == null) {
14485                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14486                        continue;
14487                    }
14488
14489                    /*
14490                     * Skip packages that are not external if we're unmounting
14491                     * external storage.
14492                     */
14493                    if (externalStorage && !isMounted && !isExternal(ps)) {
14494                        continue;
14495                    }
14496
14497                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14498                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14499                    // The package status is changed only if the code path
14500                    // matches between settings and the container id.
14501                    if (ps.codePathString != null
14502                            && ps.codePathString.startsWith(args.getCodePath())) {
14503                        if (DEBUG_SD_INSTALL) {
14504                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14505                                    + " at code path: " + ps.codePathString);
14506                        }
14507
14508                        // We do have a valid package installed on sdcard
14509                        processCids.put(args, ps.codePathString);
14510                        final int uid = ps.appId;
14511                        if (uid != -1) {
14512                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14513                        }
14514                    } else {
14515                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14516                                + ps.codePathString);
14517                    }
14518                }
14519            }
14520
14521            Arrays.sort(uidArr);
14522        }
14523
14524        // Process packages with valid entries.
14525        if (isMounted) {
14526            if (DEBUG_SD_INSTALL)
14527                Log.i(TAG, "Loading packages");
14528            loadMediaPackages(processCids, uidArr);
14529            startCleaningPackages();
14530            mInstallerService.onSecureContainersAvailable();
14531        } else {
14532            if (DEBUG_SD_INSTALL)
14533                Log.i(TAG, "Unloading packages");
14534            unloadMediaPackages(processCids, uidArr, reportStatus);
14535        }
14536    }
14537
14538    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14539            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14540        final int size = infos.size();
14541        final String[] packageNames = new String[size];
14542        final int[] packageUids = new int[size];
14543        for (int i = 0; i < size; i++) {
14544            final ApplicationInfo info = infos.get(i);
14545            packageNames[i] = info.packageName;
14546            packageUids[i] = info.uid;
14547        }
14548        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14549                finishedReceiver);
14550    }
14551
14552    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14553            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14554        sendResourcesChangedBroadcast(mediaStatus, replacing,
14555                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14556    }
14557
14558    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14559            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14560        int size = pkgList.length;
14561        if (size > 0) {
14562            // Send broadcasts here
14563            Bundle extras = new Bundle();
14564            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14565            if (uidArr != null) {
14566                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14567            }
14568            if (replacing) {
14569                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14570            }
14571            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14572                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14573            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14574        }
14575    }
14576
14577   /*
14578     * Look at potentially valid container ids from processCids If package
14579     * information doesn't match the one on record or package scanning fails,
14580     * the cid is added to list of removeCids. We currently don't delete stale
14581     * containers.
14582     */
14583    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14584        ArrayList<String> pkgList = new ArrayList<String>();
14585        Set<AsecInstallArgs> keys = processCids.keySet();
14586
14587        for (AsecInstallArgs args : keys) {
14588            String codePath = processCids.get(args);
14589            if (DEBUG_SD_INSTALL)
14590                Log.i(TAG, "Loading container : " + args.cid);
14591            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14592            try {
14593                // Make sure there are no container errors first.
14594                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14595                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14596                            + " when installing from sdcard");
14597                    continue;
14598                }
14599                // Check code path here.
14600                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14601                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14602                            + " does not match one in settings " + codePath);
14603                    continue;
14604                }
14605                // Parse package
14606                int parseFlags = mDefParseFlags;
14607                if (args.isExternalAsec()) {
14608                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14609                }
14610                if (args.isFwdLocked()) {
14611                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14612                }
14613
14614                synchronized (mInstallLock) {
14615                    PackageParser.Package pkg = null;
14616                    try {
14617                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14618                    } catch (PackageManagerException e) {
14619                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14620                    }
14621                    // Scan the package
14622                    if (pkg != null) {
14623                        /*
14624                         * TODO why is the lock being held? doPostInstall is
14625                         * called in other places without the lock. This needs
14626                         * to be straightened out.
14627                         */
14628                        // writer
14629                        synchronized (mPackages) {
14630                            retCode = PackageManager.INSTALL_SUCCEEDED;
14631                            pkgList.add(pkg.packageName);
14632                            // Post process args
14633                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14634                                    pkg.applicationInfo.uid);
14635                        }
14636                    } else {
14637                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14638                    }
14639                }
14640
14641            } finally {
14642                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14643                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14644                }
14645            }
14646        }
14647        // writer
14648        synchronized (mPackages) {
14649            // If the platform SDK has changed since the last time we booted,
14650            // we need to re-grant app permission to catch any new ones that
14651            // appear. This is really a hack, and means that apps can in some
14652            // cases get permissions that the user didn't initially explicitly
14653            // allow... it would be nice to have some better way to handle
14654            // this situation.
14655            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14656            if (regrantPermissions)
14657                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14658                        + mSdkVersion + "; regranting permissions for external storage");
14659            mSettings.mExternalSdkPlatform = mSdkVersion;
14660
14661            // Make sure group IDs have been assigned, and any permission
14662            // changes in other apps are accounted for
14663            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14664                    | (regrantPermissions
14665                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14666                            : 0));
14667
14668            mSettings.updateExternalDatabaseVersion();
14669
14670            // can downgrade to reader
14671            // Persist settings
14672            mSettings.writeLPr();
14673        }
14674        // Send a broadcast to let everyone know we are done processing
14675        if (pkgList.size() > 0) {
14676            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14677        }
14678    }
14679
14680   /*
14681     * Utility method to unload a list of specified containers
14682     */
14683    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14684        // Just unmount all valid containers.
14685        for (AsecInstallArgs arg : cidArgs) {
14686            synchronized (mInstallLock) {
14687                arg.doPostDeleteLI(false);
14688           }
14689       }
14690   }
14691
14692    /*
14693     * Unload packages mounted on external media. This involves deleting package
14694     * data from internal structures, sending broadcasts about diabled packages,
14695     * gc'ing to free up references, unmounting all secure containers
14696     * corresponding to packages on external media, and posting a
14697     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14698     * that we always have to post this message if status has been requested no
14699     * matter what.
14700     */
14701    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14702            final boolean reportStatus) {
14703        if (DEBUG_SD_INSTALL)
14704            Log.i(TAG, "unloading media packages");
14705        ArrayList<String> pkgList = new ArrayList<String>();
14706        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14707        final Set<AsecInstallArgs> keys = processCids.keySet();
14708        for (AsecInstallArgs args : keys) {
14709            String pkgName = args.getPackageName();
14710            if (DEBUG_SD_INSTALL)
14711                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14712            // Delete package internally
14713            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14714            synchronized (mInstallLock) {
14715                boolean res = deletePackageLI(pkgName, null, false, null, null,
14716                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14717                if (res) {
14718                    pkgList.add(pkgName);
14719                } else {
14720                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14721                    failedList.add(args);
14722                }
14723            }
14724        }
14725
14726        // reader
14727        synchronized (mPackages) {
14728            // We didn't update the settings after removing each package;
14729            // write them now for all packages.
14730            mSettings.writeLPr();
14731        }
14732
14733        // We have to absolutely send UPDATED_MEDIA_STATUS only
14734        // after confirming that all the receivers processed the ordered
14735        // broadcast when packages get disabled, force a gc to clean things up.
14736        // and unload all the containers.
14737        if (pkgList.size() > 0) {
14738            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14739                    new IIntentReceiver.Stub() {
14740                public void performReceive(Intent intent, int resultCode, String data,
14741                        Bundle extras, boolean ordered, boolean sticky,
14742                        int sendingUser) throws RemoteException {
14743                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14744                            reportStatus ? 1 : 0, 1, keys);
14745                    mHandler.sendMessage(msg);
14746                }
14747            });
14748        } else {
14749            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14750                    keys);
14751            mHandler.sendMessage(msg);
14752        }
14753    }
14754
14755    private void loadPrivatePackages(VolumeInfo vol) {
14756        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14757        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14758        synchronized (mInstallLock) {
14759        synchronized (mPackages) {
14760            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14761            for (PackageSetting ps : packages) {
14762                final PackageParser.Package pkg;
14763                try {
14764                    pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14765                    loaded.add(pkg.applicationInfo);
14766                } catch (PackageManagerException e) {
14767                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14768                }
14769            }
14770
14771            // TODO: regrant any permissions that changed based since original install
14772
14773            mSettings.writeLPr();
14774        }
14775        }
14776
14777        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
14778        sendResourcesChangedBroadcast(true, false, loaded, null);
14779    }
14780
14781    private void unloadPrivatePackages(VolumeInfo vol) {
14782        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14783        synchronized (mInstallLock) {
14784        synchronized (mPackages) {
14785            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14786            for (PackageSetting ps : packages) {
14787                if (ps.pkg == null) continue;
14788
14789                final ApplicationInfo info = ps.pkg.applicationInfo;
14790                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14791                if (deletePackageLI(ps.name, null, false, null, null,
14792                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14793                    unloaded.add(info);
14794                } else {
14795                    Slog.w(TAG, "Failed to unload " + ps.codePath);
14796                }
14797            }
14798
14799            mSettings.writeLPr();
14800        }
14801        }
14802
14803        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
14804        sendResourcesChangedBroadcast(false, false, unloaded, null);
14805    }
14806
14807    private void unfreezePackage(String packageName) {
14808        synchronized (mPackages) {
14809            final PackageSetting ps = mSettings.mPackages.get(packageName);
14810            if (ps != null) {
14811                ps.frozen = false;
14812            }
14813        }
14814    }
14815
14816    @Override
14817    public int movePackage(final String packageName, final String volumeUuid) {
14818        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14819
14820        final int moveId = mNextMoveId.getAndIncrement();
14821        try {
14822            movePackageInternal(packageName, volumeUuid, moveId);
14823        } catch (PackageManagerException e) {
14824            Slog.w(TAG, "Failed to move " + packageName, e);
14825            mMoveCallbacks.notifyStatusChanged(moveId,
14826                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14827        }
14828        return moveId;
14829    }
14830
14831    private void movePackageInternal(final String packageName, final String volumeUuid,
14832            final int moveId) throws PackageManagerException {
14833        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14834        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14835        final PackageManager pm = mContext.getPackageManager();
14836
14837        final boolean currentAsec;
14838        final String currentVolumeUuid;
14839        final File codeFile;
14840        final String installerPackageName;
14841        final String packageAbiOverride;
14842        final int appId;
14843        final String seinfo;
14844        final String label;
14845
14846        // reader
14847        synchronized (mPackages) {
14848            final PackageParser.Package pkg = mPackages.get(packageName);
14849            final PackageSetting ps = mSettings.mPackages.get(packageName);
14850            if (pkg == null || ps == null) {
14851                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14852            }
14853
14854            if (pkg.applicationInfo.isSystemApp()) {
14855                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14856                        "Cannot move system application");
14857            }
14858
14859            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
14860                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14861                        "Package already moved to " + volumeUuid);
14862            }
14863
14864            final File probe = new File(pkg.codePath);
14865            final File probeOat = new File(probe, "oat");
14866            if (!probe.isDirectory() || !probeOat.isDirectory()) {
14867                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14868                        "Move only supported for modern cluster style installs");
14869            }
14870
14871            if (ps.frozen) {
14872                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14873                        "Failed to move already frozen package");
14874            }
14875            ps.frozen = true;
14876
14877            currentAsec = pkg.applicationInfo.isForwardLocked()
14878                    || pkg.applicationInfo.isExternalAsec();
14879            currentVolumeUuid = ps.volumeUuid;
14880            codeFile = new File(pkg.codePath);
14881            installerPackageName = ps.installerPackageName;
14882            packageAbiOverride = ps.cpuAbiOverrideString;
14883            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14884            seinfo = pkg.applicationInfo.seinfo;
14885            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
14886        }
14887
14888        // Now that we're guarded by frozen state, kill app during move
14889        killApplication(packageName, appId, "move pkg");
14890
14891        final Bundle extras = new Bundle();
14892        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
14893        extras.putString(Intent.EXTRA_TITLE, label);
14894        mMoveCallbacks.notifyCreated(moveId, extras);
14895
14896        int installFlags;
14897        final boolean moveCompleteApp;
14898        final File measurePath;
14899
14900        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
14901            installFlags = INSTALL_INTERNAL;
14902            moveCompleteApp = !currentAsec;
14903            measurePath = Environment.getDataAppDirectory(volumeUuid);
14904        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
14905            installFlags = INSTALL_EXTERNAL;
14906            moveCompleteApp = false;
14907            measurePath = storage.getPrimaryPhysicalVolume().getPath();
14908        } else {
14909            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
14910            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
14911                    || !volume.isMountedWritable()) {
14912                unfreezePackage(packageName);
14913                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14914                        "Move location not mounted private volume");
14915            }
14916
14917            Preconditions.checkState(!currentAsec);
14918
14919            installFlags = INSTALL_INTERNAL;
14920            moveCompleteApp = true;
14921            measurePath = Environment.getDataAppDirectory(volumeUuid);
14922        }
14923
14924        final PackageStats stats = new PackageStats(null, -1);
14925        synchronized (mInstaller) {
14926            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
14927                unfreezePackage(packageName);
14928                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14929                        "Failed to measure package size");
14930            }
14931        }
14932
14933        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
14934                + stats.dataSize);
14935
14936        final long startFreeBytes = measurePath.getFreeSpace();
14937        final long sizeBytes;
14938        if (moveCompleteApp) {
14939            sizeBytes = stats.codeSize + stats.dataSize;
14940        } else {
14941            sizeBytes = stats.codeSize;
14942        }
14943
14944        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
14945            unfreezePackage(packageName);
14946            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14947                    "Not enough free space to move");
14948        }
14949
14950        mMoveCallbacks.notifyStatusChanged(moveId, 10);
14951
14952        final CountDownLatch installedLatch = new CountDownLatch(1);
14953        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14954            @Override
14955            public void onUserActionRequired(Intent intent) throws RemoteException {
14956                throw new IllegalStateException();
14957            }
14958
14959            @Override
14960            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14961                    Bundle extras) throws RemoteException {
14962                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
14963                        + PackageManager.installStatusToString(returnCode, msg));
14964
14965                installedLatch.countDown();
14966
14967                // Regardless of success or failure of the move operation,
14968                // always unfreeze the package
14969                unfreezePackage(packageName);
14970
14971                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14972                switch (status) {
14973                    case PackageInstaller.STATUS_SUCCESS:
14974                        mMoveCallbacks.notifyStatusChanged(moveId,
14975                                PackageManager.MOVE_SUCCEEDED);
14976                        break;
14977                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14978                        mMoveCallbacks.notifyStatusChanged(moveId,
14979                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14980                        break;
14981                    default:
14982                        mMoveCallbacks.notifyStatusChanged(moveId,
14983                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14984                        break;
14985                }
14986            }
14987        };
14988
14989        final MoveInfo move;
14990        if (moveCompleteApp) {
14991            // Kick off a thread to report progress estimates
14992            new Thread() {
14993                @Override
14994                public void run() {
14995                    while (true) {
14996                        try {
14997                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
14998                                break;
14999                            }
15000                        } catch (InterruptedException ignored) {
15001                        }
15002
15003                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15004                        final int progress = 10 + (int) MathUtils.constrain(
15005                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15006                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15007                    }
15008                }
15009            }.start();
15010
15011            final String dataAppName = codeFile.getName();
15012            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15013                    dataAppName, appId, seinfo);
15014        } else {
15015            move = null;
15016        }
15017
15018        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15019
15020        final Message msg = mHandler.obtainMessage(INIT_COPY);
15021        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15022        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15023                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15024        mHandler.sendMessage(msg);
15025    }
15026
15027    @Override
15028    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15029        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15030
15031        final int realMoveId = mNextMoveId.getAndIncrement();
15032        final Bundle extras = new Bundle();
15033        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15034        mMoveCallbacks.notifyCreated(realMoveId, extras);
15035
15036        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15037            @Override
15038            public void onCreated(int moveId, Bundle extras) {
15039                // Ignored
15040            }
15041
15042            @Override
15043            public void onStatusChanged(int moveId, int status, long estMillis) {
15044                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15045            }
15046        };
15047
15048        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15049        storage.setPrimaryStorageUuid(volumeUuid, callback);
15050        return realMoveId;
15051    }
15052
15053    @Override
15054    public int getMoveStatus(int moveId) {
15055        mContext.enforceCallingOrSelfPermission(
15056                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15057        return mMoveCallbacks.mLastStatus.get(moveId);
15058    }
15059
15060    @Override
15061    public void registerMoveCallback(IPackageMoveObserver callback) {
15062        mContext.enforceCallingOrSelfPermission(
15063                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15064        mMoveCallbacks.register(callback);
15065    }
15066
15067    @Override
15068    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15069        mContext.enforceCallingOrSelfPermission(
15070                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15071        mMoveCallbacks.unregister(callback);
15072    }
15073
15074    @Override
15075    public boolean setInstallLocation(int loc) {
15076        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15077                null);
15078        if (getInstallLocation() == loc) {
15079            return true;
15080        }
15081        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15082                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15083            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15084                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15085            return true;
15086        }
15087        return false;
15088   }
15089
15090    @Override
15091    public int getInstallLocation() {
15092        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15093                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15094                PackageHelper.APP_INSTALL_AUTO);
15095    }
15096
15097    /** Called by UserManagerService */
15098    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15099        mDirtyUsers.remove(userHandle);
15100        mSettings.removeUserLPw(userHandle);
15101        mPendingBroadcasts.remove(userHandle);
15102        if (mInstaller != null) {
15103            // Technically, we shouldn't be doing this with the package lock
15104            // held.  However, this is very rare, and there is already so much
15105            // other disk I/O going on, that we'll let it slide for now.
15106            final StorageManager storage = StorageManager.from(mContext);
15107            final List<VolumeInfo> vols = storage.getVolumes();
15108            for (VolumeInfo vol : vols) {
15109                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
15110                    final String volumeUuid = vol.getFsUuid();
15111                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15112                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15113                }
15114            }
15115        }
15116        mUserNeedsBadging.delete(userHandle);
15117        removeUnusedPackagesLILPw(userManager, userHandle);
15118    }
15119
15120    /**
15121     * We're removing userHandle and would like to remove any downloaded packages
15122     * that are no longer in use by any other user.
15123     * @param userHandle the user being removed
15124     */
15125    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15126        final boolean DEBUG_CLEAN_APKS = false;
15127        int [] users = userManager.getUserIdsLPr();
15128        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15129        while (psit.hasNext()) {
15130            PackageSetting ps = psit.next();
15131            if (ps.pkg == null) {
15132                continue;
15133            }
15134            final String packageName = ps.pkg.packageName;
15135            // Skip over if system app
15136            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15137                continue;
15138            }
15139            if (DEBUG_CLEAN_APKS) {
15140                Slog.i(TAG, "Checking package " + packageName);
15141            }
15142            boolean keep = false;
15143            for (int i = 0; i < users.length; i++) {
15144                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15145                    keep = true;
15146                    if (DEBUG_CLEAN_APKS) {
15147                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15148                                + users[i]);
15149                    }
15150                    break;
15151                }
15152            }
15153            if (!keep) {
15154                if (DEBUG_CLEAN_APKS) {
15155                    Slog.i(TAG, "  Removing package " + packageName);
15156                }
15157                mHandler.post(new Runnable() {
15158                    public void run() {
15159                        deletePackageX(packageName, userHandle, 0);
15160                    } //end run
15161                });
15162            }
15163        }
15164    }
15165
15166    /** Called by UserManagerService */
15167    void createNewUserLILPw(int userHandle, File path) {
15168        if (mInstaller != null) {
15169            mInstaller.createUserConfig(userHandle);
15170            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
15171        }
15172    }
15173
15174    void newUserCreatedLILPw(int userHandle) {
15175        // Adding a user requires updating runtime permissions for system apps.
15176        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
15177    }
15178
15179    @Override
15180    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15181        mContext.enforceCallingOrSelfPermission(
15182                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15183                "Only package verification agents can read the verifier device identity");
15184
15185        synchronized (mPackages) {
15186            return mSettings.getVerifierDeviceIdentityLPw();
15187        }
15188    }
15189
15190    @Override
15191    public void setPermissionEnforced(String permission, boolean enforced) {
15192        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15193        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15194            synchronized (mPackages) {
15195                if (mSettings.mReadExternalStorageEnforced == null
15196                        || mSettings.mReadExternalStorageEnforced != enforced) {
15197                    mSettings.mReadExternalStorageEnforced = enforced;
15198                    mSettings.writeLPr();
15199                }
15200            }
15201            // kill any non-foreground processes so we restart them and
15202            // grant/revoke the GID.
15203            final IActivityManager am = ActivityManagerNative.getDefault();
15204            if (am != null) {
15205                final long token = Binder.clearCallingIdentity();
15206                try {
15207                    am.killProcessesBelowForeground("setPermissionEnforcement");
15208                } catch (RemoteException e) {
15209                } finally {
15210                    Binder.restoreCallingIdentity(token);
15211                }
15212            }
15213        } else {
15214            throw new IllegalArgumentException("No selective enforcement for " + permission);
15215        }
15216    }
15217
15218    @Override
15219    @Deprecated
15220    public boolean isPermissionEnforced(String permission) {
15221        return true;
15222    }
15223
15224    @Override
15225    public boolean isStorageLow() {
15226        final long token = Binder.clearCallingIdentity();
15227        try {
15228            final DeviceStorageMonitorInternal
15229                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15230            if (dsm != null) {
15231                return dsm.isMemoryLow();
15232            } else {
15233                return false;
15234            }
15235        } finally {
15236            Binder.restoreCallingIdentity(token);
15237        }
15238    }
15239
15240    @Override
15241    public IPackageInstaller getPackageInstaller() {
15242        return mInstallerService;
15243    }
15244
15245    private boolean userNeedsBadging(int userId) {
15246        int index = mUserNeedsBadging.indexOfKey(userId);
15247        if (index < 0) {
15248            final UserInfo userInfo;
15249            final long token = Binder.clearCallingIdentity();
15250            try {
15251                userInfo = sUserManager.getUserInfo(userId);
15252            } finally {
15253                Binder.restoreCallingIdentity(token);
15254            }
15255            final boolean b;
15256            if (userInfo != null && userInfo.isManagedProfile()) {
15257                b = true;
15258            } else {
15259                b = false;
15260            }
15261            mUserNeedsBadging.put(userId, b);
15262            return b;
15263        }
15264        return mUserNeedsBadging.valueAt(index);
15265    }
15266
15267    @Override
15268    public KeySet getKeySetByAlias(String packageName, String alias) {
15269        if (packageName == null || alias == null) {
15270            return null;
15271        }
15272        synchronized(mPackages) {
15273            final PackageParser.Package pkg = mPackages.get(packageName);
15274            if (pkg == null) {
15275                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15276                throw new IllegalArgumentException("Unknown package: " + packageName);
15277            }
15278            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15279            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15280        }
15281    }
15282
15283    @Override
15284    public KeySet getSigningKeySet(String packageName) {
15285        if (packageName == null) {
15286            return null;
15287        }
15288        synchronized(mPackages) {
15289            final PackageParser.Package pkg = mPackages.get(packageName);
15290            if (pkg == null) {
15291                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15292                throw new IllegalArgumentException("Unknown package: " + packageName);
15293            }
15294            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15295                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15296                throw new SecurityException("May not access signing KeySet of other apps.");
15297            }
15298            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15299            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15300        }
15301    }
15302
15303    @Override
15304    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15305        if (packageName == null || ks == null) {
15306            return false;
15307        }
15308        synchronized(mPackages) {
15309            final PackageParser.Package pkg = mPackages.get(packageName);
15310            if (pkg == null) {
15311                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15312                throw new IllegalArgumentException("Unknown package: " + packageName);
15313            }
15314            IBinder ksh = ks.getToken();
15315            if (ksh instanceof KeySetHandle) {
15316                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15317                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15318            }
15319            return false;
15320        }
15321    }
15322
15323    @Override
15324    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15325        if (packageName == null || ks == null) {
15326            return false;
15327        }
15328        synchronized(mPackages) {
15329            final PackageParser.Package pkg = mPackages.get(packageName);
15330            if (pkg == null) {
15331                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15332                throw new IllegalArgumentException("Unknown package: " + packageName);
15333            }
15334            IBinder ksh = ks.getToken();
15335            if (ksh instanceof KeySetHandle) {
15336                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15337                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15338            }
15339            return false;
15340        }
15341    }
15342
15343    public void getUsageStatsIfNoPackageUsageInfo() {
15344        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15345            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15346            if (usm == null) {
15347                throw new IllegalStateException("UsageStatsManager must be initialized");
15348            }
15349            long now = System.currentTimeMillis();
15350            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15351            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15352                String packageName = entry.getKey();
15353                PackageParser.Package pkg = mPackages.get(packageName);
15354                if (pkg == null) {
15355                    continue;
15356                }
15357                UsageStats usage = entry.getValue();
15358                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15359                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15360            }
15361        }
15362    }
15363
15364    /**
15365     * Check and throw if the given before/after packages would be considered a
15366     * downgrade.
15367     */
15368    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15369            throws PackageManagerException {
15370        if (after.versionCode < before.mVersionCode) {
15371            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15372                    "Update version code " + after.versionCode + " is older than current "
15373                    + before.mVersionCode);
15374        } else if (after.versionCode == before.mVersionCode) {
15375            if (after.baseRevisionCode < before.baseRevisionCode) {
15376                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15377                        "Update base revision code " + after.baseRevisionCode
15378                        + " is older than current " + before.baseRevisionCode);
15379            }
15380
15381            if (!ArrayUtils.isEmpty(after.splitNames)) {
15382                for (int i = 0; i < after.splitNames.length; i++) {
15383                    final String splitName = after.splitNames[i];
15384                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15385                    if (j != -1) {
15386                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15387                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15388                                    "Update split " + splitName + " revision code "
15389                                    + after.splitRevisionCodes[i] + " is older than current "
15390                                    + before.splitRevisionCodes[j]);
15391                        }
15392                    }
15393                }
15394            }
15395        }
15396    }
15397
15398    private static class MoveCallbacks extends Handler {
15399        private static final int MSG_CREATED = 1;
15400        private static final int MSG_STATUS_CHANGED = 2;
15401
15402        private final RemoteCallbackList<IPackageMoveObserver>
15403                mCallbacks = new RemoteCallbackList<>();
15404
15405        private final SparseIntArray mLastStatus = new SparseIntArray();
15406
15407        public MoveCallbacks(Looper looper) {
15408            super(looper);
15409        }
15410
15411        public void register(IPackageMoveObserver callback) {
15412            mCallbacks.register(callback);
15413        }
15414
15415        public void unregister(IPackageMoveObserver callback) {
15416            mCallbacks.unregister(callback);
15417        }
15418
15419        @Override
15420        public void handleMessage(Message msg) {
15421            final SomeArgs args = (SomeArgs) msg.obj;
15422            final int n = mCallbacks.beginBroadcast();
15423            for (int i = 0; i < n; i++) {
15424                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15425                try {
15426                    invokeCallback(callback, msg.what, args);
15427                } catch (RemoteException ignored) {
15428                }
15429            }
15430            mCallbacks.finishBroadcast();
15431            args.recycle();
15432        }
15433
15434        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15435                throws RemoteException {
15436            switch (what) {
15437                case MSG_CREATED: {
15438                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15439                    break;
15440                }
15441                case MSG_STATUS_CHANGED: {
15442                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15443                    break;
15444                }
15445            }
15446        }
15447
15448        private void notifyCreated(int moveId, Bundle extras) {
15449            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15450
15451            final SomeArgs args = SomeArgs.obtain();
15452            args.argi1 = moveId;
15453            args.arg2 = extras;
15454            obtainMessage(MSG_CREATED, args).sendToTarget();
15455        }
15456
15457        private void notifyStatusChanged(int moveId, int status) {
15458            notifyStatusChanged(moveId, status, -1);
15459        }
15460
15461        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15462            Slog.v(TAG, "Move " + moveId + " status " + status);
15463
15464            final SomeArgs args = SomeArgs.obtain();
15465            args.argi1 = moveId;
15466            args.argi2 = status;
15467            args.arg3 = estMillis;
15468            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15469
15470            synchronized (mLastStatus) {
15471                mLastStatus.put(moveId, status);
15472            }
15473        }
15474    }
15475
15476    private final class OnPermissionChangeListeners extends Handler {
15477        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
15478
15479        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
15480                new RemoteCallbackList<>();
15481
15482        public OnPermissionChangeListeners(Looper looper) {
15483            super(looper);
15484        }
15485
15486        @Override
15487        public void handleMessage(Message msg) {
15488            switch (msg.what) {
15489                case MSG_ON_PERMISSIONS_CHANGED: {
15490                    final int uid = msg.arg1;
15491                    handleOnPermissionsChanged(uid);
15492                } break;
15493            }
15494        }
15495
15496        public void addListenerLocked(IOnPermissionsChangeListener listener) {
15497            mPermissionListeners.register(listener);
15498
15499        }
15500
15501        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
15502            mPermissionListeners.unregister(listener);
15503        }
15504
15505        public void onPermissionsChanged(int uid) {
15506            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
15507                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
15508            }
15509        }
15510
15511        private void handleOnPermissionsChanged(int uid) {
15512            final int count = mPermissionListeners.beginBroadcast();
15513            try {
15514                for (int i = 0; i < count; i++) {
15515                    IOnPermissionsChangeListener callback = mPermissionListeners
15516                            .getBroadcastItem(i);
15517                    try {
15518                        callback.onPermissionsChanged(uid);
15519                    } catch (RemoteException e) {
15520                        Log.e(TAG, "Permission listener is dead", e);
15521                    }
15522                }
15523            } finally {
15524                mPermissionListeners.finishBroadcast();
15525            }
15526        }
15527    }
15528}
15529