PackageManagerService.java revision 8ef631de47d4e52cafe5f9182633892b480dfcdb
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.PACKAGE_INFO_GID;
59import static android.os.Process.SYSTEM_UID;
60import static android.system.OsConstants.O_CREAT;
61import static android.system.OsConstants.O_RDWR;
62import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
64import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
65import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
66import static com.android.internal.util.ArrayUtils.appendInt;
67import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
68import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
70import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
71import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
72
73import android.Manifest;
74import android.app.ActivityManager;
75import android.app.ActivityManagerNative;
76import android.app.AppGlobals;
77import android.app.IActivityManager;
78import android.app.admin.IDevicePolicyManager;
79import android.app.backup.IBackupManager;
80import android.app.usage.UsageStats;
81import android.app.usage.UsageStatsManager;
82import android.content.BroadcastReceiver;
83import android.content.ComponentName;
84import android.content.Context;
85import android.content.IIntentReceiver;
86import android.content.Intent;
87import android.content.IntentFilter;
88import android.content.IntentSender;
89import android.content.IntentSender.SendIntentException;
90import android.content.ServiceConnection;
91import android.content.pm.ActivityInfo;
92import android.content.pm.ApplicationInfo;
93import android.content.pm.FeatureInfo;
94import android.content.pm.IPackageDataObserver;
95import android.content.pm.IPackageDeleteObserver;
96import android.content.pm.IPackageDeleteObserver2;
97import android.content.pm.IPackageInstallObserver2;
98import android.content.pm.IPackageInstaller;
99import android.content.pm.IPackageManager;
100import android.content.pm.IPackageMoveObserver;
101import android.content.pm.IPackageStatsObserver;
102import android.content.pm.InstrumentationInfo;
103import android.content.pm.IntentFilterVerificationInfo;
104import android.content.pm.KeySet;
105import android.content.pm.ManifestDigest;
106import android.content.pm.PackageCleanItem;
107import android.content.pm.PackageInfo;
108import android.content.pm.PackageInfoLite;
109import android.content.pm.PackageInstaller;
110import android.content.pm.PackageManager;
111import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
112import android.content.pm.PackageParser;
113import android.content.pm.PackageParser.ActivityIntentInfo;
114import android.content.pm.PackageParser.PackageLite;
115import android.content.pm.PackageParser.PackageParserException;
116import android.content.pm.PackageStats;
117import android.content.pm.PackageUserState;
118import android.content.pm.ParceledListSlice;
119import android.content.pm.PermissionGroupInfo;
120import android.content.pm.PermissionInfo;
121import android.content.pm.ProviderInfo;
122import android.content.pm.ResolveInfo;
123import android.content.pm.ServiceInfo;
124import android.content.pm.Signature;
125import android.content.pm.UserInfo;
126import android.content.pm.VerificationParams;
127import android.content.pm.VerifierDeviceIdentity;
128import android.content.pm.VerifierInfo;
129import android.content.res.Resources;
130import android.hardware.display.DisplayManager;
131import android.net.Uri;
132import android.os.Binder;
133import android.os.Build;
134import android.os.Bundle;
135import android.os.Debug;
136import android.os.Environment;
137import android.os.Environment.UserEnvironment;
138import android.os.FileUtils;
139import android.os.Handler;
140import android.os.IBinder;
141import android.os.Looper;
142import android.os.Message;
143import android.os.Parcel;
144import android.os.ParcelFileDescriptor;
145import android.os.Process;
146import android.os.RemoteCallbackList;
147import android.os.RemoteException;
148import android.os.SELinux;
149import android.os.ServiceManager;
150import android.os.SystemClock;
151import android.os.SystemProperties;
152import android.os.UserHandle;
153import android.os.UserManager;
154import android.os.storage.IMountService;
155import android.os.storage.StorageEventListener;
156import android.os.storage.StorageManager;
157import android.os.storage.VolumeInfo;
158import android.os.storage.VolumeRecord;
159import android.security.KeyStore;
160import android.security.SystemKeyStore;
161import android.system.ErrnoException;
162import android.system.Os;
163import android.system.StructStat;
164import android.text.TextUtils;
165import android.text.format.DateUtils;
166import android.util.ArrayMap;
167import android.util.ArraySet;
168import android.util.AtomicFile;
169import android.util.DisplayMetrics;
170import android.util.EventLog;
171import android.util.ExceptionUtils;
172import android.util.Log;
173import android.util.LogPrinter;
174import android.util.MathUtils;
175import android.util.PrintStreamPrinter;
176import android.util.Slog;
177import android.util.SparseArray;
178import android.util.SparseBooleanArray;
179import android.util.SparseIntArray;
180import android.util.Xml;
181import android.view.Display;
182
183import dalvik.system.DexFile;
184import dalvik.system.VMRuntime;
185
186import libcore.io.IoUtils;
187import libcore.util.EmptyArray;
188
189import com.android.internal.R;
190import com.android.internal.app.IMediaContainerService;
191import com.android.internal.app.ResolverActivity;
192import com.android.internal.content.NativeLibraryHelper;
193import com.android.internal.content.PackageHelper;
194import com.android.internal.os.IParcelFileDescriptorFactory;
195import com.android.internal.os.SomeArgs;
196import com.android.internal.util.ArrayUtils;
197import com.android.internal.util.FastPrintWriter;
198import com.android.internal.util.FastXmlSerializer;
199import com.android.internal.util.IndentingPrintWriter;
200import com.android.internal.util.Preconditions;
201import com.android.server.EventLogTags;
202import com.android.server.FgThread;
203import com.android.server.IntentResolver;
204import com.android.server.LocalServices;
205import com.android.server.ServiceThread;
206import com.android.server.SystemConfig;
207import com.android.server.Watchdog;
208import com.android.server.pm.Settings.DatabaseVersion;
209import com.android.server.storage.DeviceStorageMonitorInternal;
210
211import org.xmlpull.v1.XmlPullParser;
212import org.xmlpull.v1.XmlSerializer;
213
214import java.io.BufferedInputStream;
215import java.io.BufferedOutputStream;
216import java.io.BufferedReader;
217import java.io.ByteArrayInputStream;
218import java.io.ByteArrayOutputStream;
219import java.io.File;
220import java.io.FileDescriptor;
221import java.io.FileNotFoundException;
222import java.io.FileOutputStream;
223import java.io.FileReader;
224import java.io.FilenameFilter;
225import java.io.IOException;
226import java.io.InputStream;
227import java.io.PrintWriter;
228import java.nio.charset.StandardCharsets;
229import java.security.NoSuchAlgorithmException;
230import java.security.PublicKey;
231import java.security.cert.CertificateEncodingException;
232import java.security.cert.CertificateException;
233import java.text.SimpleDateFormat;
234import java.util.ArrayList;
235import java.util.Arrays;
236import java.util.Collection;
237import java.util.Collections;
238import java.util.Comparator;
239import java.util.Date;
240import java.util.Iterator;
241import java.util.List;
242import java.util.Map;
243import java.util.Objects;
244import java.util.Set;
245import java.util.concurrent.CountDownLatch;
246import java.util.concurrent.TimeUnit;
247import java.util.concurrent.atomic.AtomicBoolean;
248import java.util.concurrent.atomic.AtomicInteger;
249import java.util.concurrent.atomic.AtomicLong;
250
251/**
252 * Keep track of all those .apks everywhere.
253 *
254 * This is very central to the platform's security; please run the unit
255 * tests whenever making modifications here:
256 *
257mmm frameworks/base/tests/AndroidTests
258adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
259adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
260 *
261 * {@hide}
262 */
263public class PackageManagerService extends IPackageManager.Stub {
264    static final String TAG = "PackageManager";
265    static final boolean DEBUG_SETTINGS = false;
266    static final boolean DEBUG_PREFERRED = false;
267    static final boolean DEBUG_UPGRADE = false;
268    private static final boolean DEBUG_BACKUP = true;
269    private static final boolean DEBUG_INSTALL = false;
270    private static final boolean DEBUG_REMOVE = false;
271    private static final boolean DEBUG_BROADCASTS = false;
272    private static final boolean DEBUG_SHOW_INFO = false;
273    private static final boolean DEBUG_PACKAGE_INFO = false;
274    private static final boolean DEBUG_INTENT_MATCHING = false;
275    private static final boolean DEBUG_PACKAGE_SCANNING = false;
276    private static final boolean DEBUG_VERIFY = false;
277    private static final boolean DEBUG_DEXOPT = false;
278    private static final boolean DEBUG_ABI_SELECTION = false;
279
280    static final boolean RUNTIME_PERMISSIONS_ENABLED = true;
281
282    private static final int RADIO_UID = Process.PHONE_UID;
283    private static final int LOG_UID = Process.LOG_UID;
284    private static final int NFC_UID = Process.NFC_UID;
285    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
286    private static final int SHELL_UID = Process.SHELL_UID;
287
288    // Cap the size of permission trees that 3rd party apps can define
289    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
290
291    // Suffix used during package installation when copying/moving
292    // package apks to install directory.
293    private static final String INSTALL_PACKAGE_SUFFIX = "-";
294
295    static final int SCAN_NO_DEX = 1<<1;
296    static final int SCAN_FORCE_DEX = 1<<2;
297    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
298    static final int SCAN_NEW_INSTALL = 1<<4;
299    static final int SCAN_NO_PATHS = 1<<5;
300    static final int SCAN_UPDATE_TIME = 1<<6;
301    static final int SCAN_DEFER_DEX = 1<<7;
302    static final int SCAN_BOOTING = 1<<8;
303    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
304    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
305    static final int SCAN_REQUIRE_KNOWN = 1<<12;
306
307    static final int REMOVE_CHATTY = 1<<16;
308
309    /**
310     * Timeout (in milliseconds) after which the watchdog should declare that
311     * our handler thread is wedged.  The usual default for such things is one
312     * minute but we sometimes do very lengthy I/O operations on this thread,
313     * such as installing multi-gigabyte applications, so ours needs to be longer.
314     */
315    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
316
317    /**
318     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
319     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
320     * settings entry if available, otherwise we use the hardcoded default.  If it's been
321     * more than this long since the last fstrim, we force one during the boot sequence.
322     *
323     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
324     * one gets run at the next available charging+idle time.  This final mandatory
325     * no-fstrim check kicks in only of the other scheduling criteria is never met.
326     */
327    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
328
329    /**
330     * Whether verification is enabled by default.
331     */
332    private static final boolean DEFAULT_VERIFY_ENABLE = true;
333
334    /**
335     * The default maximum time to wait for the verification agent to return in
336     * milliseconds.
337     */
338    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
339
340    /**
341     * The default response for package verification timeout.
342     *
343     * This can be either PackageManager.VERIFICATION_ALLOW or
344     * PackageManager.VERIFICATION_REJECT.
345     */
346    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
347
348    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
349
350    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
351            DEFAULT_CONTAINER_PACKAGE,
352            "com.android.defcontainer.DefaultContainerService");
353
354    private static final String KILL_APP_REASON_GIDS_CHANGED =
355            "permission grant or revoke changed gids";
356
357    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
358            "permissions revoked";
359
360    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
361
362    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
363
364    /** Permission grant: not grant the permission. */
365    private static final int GRANT_DENIED = 1;
366
367    /** Permission grant: grant the permission as an install permission. */
368    private static final int GRANT_INSTALL = 2;
369
370    /** Permission grant: grant the permission as a runtime one. */
371    private static final int GRANT_RUNTIME = 3;
372
373    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
374    private static final int GRANT_UPGRADE = 4;
375
376    final ServiceThread mHandlerThread;
377
378    final PackageHandler mHandler;
379
380    /**
381     * Messages for {@link #mHandler} that need to wait for system ready before
382     * being dispatched.
383     */
384    private ArrayList<Message> mPostSystemReadyMessages;
385
386    final int mSdkVersion = Build.VERSION.SDK_INT;
387
388    final Context mContext;
389    final boolean mFactoryTest;
390    final boolean mOnlyCore;
391    final boolean mLazyDexOpt;
392    final long mDexOptLRUThresholdInMills;
393    final DisplayMetrics mMetrics;
394    final int mDefParseFlags;
395    final String[] mSeparateProcesses;
396    final boolean mIsUpgrade;
397
398    // This is where all application persistent data goes.
399    final File mAppDataDir;
400
401    // This is where all application persistent data goes for secondary users.
402    final File mUserAppDataDir;
403
404    /** The location for ASEC container files on internal storage. */
405    final String mAsecInternalPath;
406
407    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
408    // LOCK HELD.  Can be called with mInstallLock held.
409    final Installer mInstaller;
410
411    /** Directory where installed third-party apps stored */
412    final File mAppInstallDir;
413
414    /**
415     * Directory to which applications installed internally have their
416     * 32 bit native libraries copied.
417     */
418    private File mAppLib32InstallDir;
419
420    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
421    // apps.
422    final File mDrmAppPrivateInstallDir;
423
424    // ----------------------------------------------------------------
425
426    // Lock for state used when installing and doing other long running
427    // operations.  Methods that must be called with this lock held have
428    // the suffix "LI".
429    final Object mInstallLock = new Object();
430
431    // ----------------------------------------------------------------
432
433    // Keys are String (package name), values are Package.  This also serves
434    // as the lock for the global state.  Methods that must be called with
435    // this lock held have the prefix "LP".
436    final ArrayMap<String, PackageParser.Package> mPackages =
437            new ArrayMap<String, PackageParser.Package>();
438
439    // Tracks available target package names -> overlay package paths.
440    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
441        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
442
443    final Settings mSettings;
444    boolean mRestoredSettings;
445
446    // System configuration read by SystemConfig.
447    final int[] mGlobalGids;
448    final SparseArray<ArraySet<String>> mSystemPermissions;
449    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
450
451    // If mac_permissions.xml was found for seinfo labeling.
452    boolean mFoundPolicyFile;
453
454    // If a recursive restorecon of /data/data/<pkg> is needed.
455    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
456
457    public static final class SharedLibraryEntry {
458        public final String path;
459        public final String apk;
460
461        SharedLibraryEntry(String _path, String _apk) {
462            path = _path;
463            apk = _apk;
464        }
465    }
466
467    // Currently known shared libraries.
468    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
469            new ArrayMap<String, SharedLibraryEntry>();
470
471    // All available activities, for your resolving pleasure.
472    final ActivityIntentResolver mActivities =
473            new ActivityIntentResolver();
474
475    // All available receivers, for your resolving pleasure.
476    final ActivityIntentResolver mReceivers =
477            new ActivityIntentResolver();
478
479    // All available services, for your resolving pleasure.
480    final ServiceIntentResolver mServices = new ServiceIntentResolver();
481
482    // All available providers, for your resolving pleasure.
483    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
484
485    // Mapping from provider base names (first directory in content URI codePath)
486    // to the provider information.
487    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
488            new ArrayMap<String, PackageParser.Provider>();
489
490    // Mapping from instrumentation class names to info about them.
491    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
492            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
493
494    // Mapping from permission names to info about them.
495    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
496            new ArrayMap<String, PackageParser.PermissionGroup>();
497
498    // Packages whose data we have transfered into another package, thus
499    // should no longer exist.
500    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
501
502    // Broadcast actions that are only available to the system.
503    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
504
505    /** List of packages waiting for verification. */
506    final SparseArray<PackageVerificationState> mPendingVerification
507            = new SparseArray<PackageVerificationState>();
508
509    /** Set of packages associated with each app op permission. */
510    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
511
512    final PackageInstallerService mInstallerService;
513
514    private final PackageDexOptimizer mPackageDexOptimizer;
515
516    private AtomicInteger mNextMoveId = new AtomicInteger();
517    private final MoveCallbacks mMoveCallbacks;
518
519    // Cache of users who need badging.
520    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
521
522    /** Token for keys in mPendingVerification. */
523    private int mPendingVerificationToken = 0;
524
525    volatile boolean mSystemReady;
526    volatile boolean mSafeMode;
527    volatile boolean mHasSystemUidErrors;
528
529    ApplicationInfo mAndroidApplication;
530    final ActivityInfo mResolveActivity = new ActivityInfo();
531    final ResolveInfo mResolveInfo = new ResolveInfo();
532    ComponentName mResolveComponentName;
533    PackageParser.Package mPlatformPackage;
534    ComponentName mCustomResolverComponentName;
535
536    boolean mResolverReplaced = false;
537
538    private final ComponentName mIntentFilterVerifierComponent;
539    private int mIntentFilterVerificationToken = 0;
540
541    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
542            = new SparseArray<IntentFilterVerificationState>();
543
544    private interface IntentFilterVerifier<T extends IntentFilter> {
545        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
546                                               T filter, String packageName);
547        void startVerifications(int userId);
548        void receiveVerificationResponse(int verificationId);
549    }
550
551    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
552        private Context mContext;
553        private ComponentName mIntentFilterVerifierComponent;
554        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
555
556        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
557            mContext = context;
558            mIntentFilterVerifierComponent = verifierComponent;
559        }
560
561        private String getDefaultScheme() {
562            // TODO: replace SCHEME_HTTP with SCHEME_HTTPS
563            return IntentFilter.SCHEME_HTTP;
564        }
565
566        @Override
567        public void startVerifications(int userId) {
568            // Launch verifications requests
569            int count = mCurrentIntentFilterVerifications.size();
570            for (int n=0; n<count; n++) {
571                int verificationId = mCurrentIntentFilterVerifications.get(n);
572                final IntentFilterVerificationState ivs =
573                        mIntentFilterVerificationStates.get(verificationId);
574
575                String packageName = ivs.getPackageName();
576
577                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
578                final int filterCount = filters.size();
579                ArraySet<String> domainsSet = new ArraySet<>();
580                for (int m=0; m<filterCount; m++) {
581                    PackageParser.ActivityIntentInfo filter = filters.get(m);
582                    domainsSet.addAll(filter.getHostsList());
583                }
584                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
585                synchronized (mPackages) {
586                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
587                            packageName, domainsList) != null) {
588                        scheduleWriteSettingsLocked();
589                    }
590                }
591                sendVerificationRequest(userId, verificationId, ivs);
592            }
593            mCurrentIntentFilterVerifications.clear();
594        }
595
596        private void sendVerificationRequest(int userId, int verificationId,
597                IntentFilterVerificationState ivs) {
598
599            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
600            verificationIntent.putExtra(
601                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
602                    verificationId);
603            verificationIntent.putExtra(
604                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
605                    getDefaultScheme());
606            verificationIntent.putExtra(
607                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
608                    ivs.getHostsString());
609            verificationIntent.putExtra(
610                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
611                    ivs.getPackageName());
612            verificationIntent.setComponent(mIntentFilterVerifierComponent);
613            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
614
615            UserHandle user = new UserHandle(userId);
616            mContext.sendBroadcastAsUser(verificationIntent, user);
617            Slog.d(TAG, "Sending IntenFilter verification broadcast");
618        }
619
620        public void receiveVerificationResponse(int verificationId) {
621            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
622
623            final boolean verified = ivs.isVerified();
624
625            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
626            final int count = filters.size();
627            for (int n=0; n<count; n++) {
628                PackageParser.ActivityIntentInfo filter = filters.get(n);
629                filter.setVerified(verified);
630
631                Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:"
632                        + verified + " and hosts:" + ivs.getHostsString());
633            }
634
635            mIntentFilterVerificationStates.remove(verificationId);
636
637            final String packageName = ivs.getPackageName();
638            IntentFilterVerificationInfo ivi = null;
639
640            synchronized (mPackages) {
641                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
642            }
643            if (ivi == null) {
644                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
645                        + verificationId + " packageName:" + packageName);
646                return;
647            }
648            Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:"
649                    + verificationId);
650
651            synchronized (mPackages) {
652                if (verified) {
653                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
654                } else {
655                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
656                }
657                scheduleWriteSettingsLocked();
658
659                final int userId = ivs.getUserId();
660                if (userId != UserHandle.USER_ALL) {
661                    final int userStatus =
662                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
663
664                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
665                    boolean needUpdate = false;
666
667                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
668                    // already been set by the User thru the Disambiguation dialog
669                    switch (userStatus) {
670                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
671                            if (verified) {
672                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
673                            } else {
674                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
675                            }
676                            needUpdate = true;
677                            break;
678
679                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
680                            if (verified) {
681                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
682                                needUpdate = true;
683                            }
684                            break;
685
686                        default:
687                            // Nothing to do
688                    }
689
690                    if (needUpdate) {
691                        mSettings.updateIntentFilterVerificationStatusLPw(
692                                packageName, updatedStatus, userId);
693                        scheduleWritePackageRestrictionsLocked(userId);
694                    }
695                }
696            }
697        }
698
699        @Override
700        public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
701                    ActivityIntentInfo filter, String packageName) {
702            if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
703                    filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
704                Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme");
705                return false;
706            }
707            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
708            if (ivs == null) {
709                ivs = createDomainVerificationState(verifierId, userId, verificationId,
710                        packageName);
711            }
712            if (!hasValidDomains(filter)) {
713                return false;
714            }
715            ivs.addFilter(filter);
716            return true;
717        }
718
719        private IntentFilterVerificationState createDomainVerificationState(int verifierId,
720                int userId, int verificationId, String packageName) {
721            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
722                    verifierId, userId, packageName);
723            ivs.setPendingState();
724            synchronized (mPackages) {
725                mIntentFilterVerificationStates.append(verificationId, ivs);
726                mCurrentIntentFilterVerifications.add(verificationId);
727            }
728            return ivs;
729        }
730    }
731
732    private static boolean hasValidDomains(ActivityIntentInfo filter) {
733        return hasValidDomains(filter, true);
734    }
735
736    private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) {
737        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
738                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
739        if (!hasHTTPorHTTPS) {
740            if (logging) {
741                Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme");
742            }
743            return false;
744        }
745        return true;
746    }
747
748    private IntentFilterVerifier mIntentFilterVerifier;
749
750    // Set of pending broadcasts for aggregating enable/disable of components.
751    static class PendingPackageBroadcasts {
752        // for each user id, a map of <package name -> components within that package>
753        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
754
755        public PendingPackageBroadcasts() {
756            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
757        }
758
759        public ArrayList<String> get(int userId, String packageName) {
760            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
761            return packages.get(packageName);
762        }
763
764        public void put(int userId, String packageName, ArrayList<String> components) {
765            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
766            packages.put(packageName, components);
767        }
768
769        public void remove(int userId, String packageName) {
770            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
771            if (packages != null) {
772                packages.remove(packageName);
773            }
774        }
775
776        public void remove(int userId) {
777            mUidMap.remove(userId);
778        }
779
780        public int userIdCount() {
781            return mUidMap.size();
782        }
783
784        public int userIdAt(int n) {
785            return mUidMap.keyAt(n);
786        }
787
788        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
789            return mUidMap.get(userId);
790        }
791
792        public int size() {
793            // total number of pending broadcast entries across all userIds
794            int num = 0;
795            for (int i = 0; i< mUidMap.size(); i++) {
796                num += mUidMap.valueAt(i).size();
797            }
798            return num;
799        }
800
801        public void clear() {
802            mUidMap.clear();
803        }
804
805        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
806            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
807            if (map == null) {
808                map = new ArrayMap<String, ArrayList<String>>();
809                mUidMap.put(userId, map);
810            }
811            return map;
812        }
813    }
814    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
815
816    // Service Connection to remote media container service to copy
817    // package uri's from external media onto secure containers
818    // or internal storage.
819    private IMediaContainerService mContainerService = null;
820
821    static final int SEND_PENDING_BROADCAST = 1;
822    static final int MCS_BOUND = 3;
823    static final int END_COPY = 4;
824    static final int INIT_COPY = 5;
825    static final int MCS_UNBIND = 6;
826    static final int START_CLEANING_PACKAGE = 7;
827    static final int FIND_INSTALL_LOC = 8;
828    static final int POST_INSTALL = 9;
829    static final int MCS_RECONNECT = 10;
830    static final int MCS_GIVE_UP = 11;
831    static final int UPDATED_MEDIA_STATUS = 12;
832    static final int WRITE_SETTINGS = 13;
833    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
834    static final int PACKAGE_VERIFIED = 15;
835    static final int CHECK_PENDING_VERIFICATION = 16;
836    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
837    static final int INTENT_FILTER_VERIFIED = 18;
838
839    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
840
841    // Delay time in millisecs
842    static final int BROADCAST_DELAY = 10 * 1000;
843
844    static UserManagerService sUserManager;
845
846    // Stores a list of users whose package restrictions file needs to be updated
847    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
848
849    final private DefaultContainerConnection mDefContainerConn =
850            new DefaultContainerConnection();
851    class DefaultContainerConnection implements ServiceConnection {
852        public void onServiceConnected(ComponentName name, IBinder service) {
853            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
854            IMediaContainerService imcs =
855                IMediaContainerService.Stub.asInterface(service);
856            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
857        }
858
859        public void onServiceDisconnected(ComponentName name) {
860            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
861        }
862    };
863
864    // Recordkeeping of restore-after-install operations that are currently in flight
865    // between the Package Manager and the Backup Manager
866    class PostInstallData {
867        public InstallArgs args;
868        public PackageInstalledInfo res;
869
870        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
871            args = _a;
872            res = _r;
873        }
874    };
875    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
876    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
877
878    // backup/restore of preferred activity state
879    private static final String TAG_PREFERRED_BACKUP = "pa";
880
881    private final String mRequiredVerifierPackage;
882
883    private final PackageUsage mPackageUsage = new PackageUsage();
884
885    private class PackageUsage {
886        private static final int WRITE_INTERVAL
887            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
888
889        private final Object mFileLock = new Object();
890        private final AtomicLong mLastWritten = new AtomicLong(0);
891        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
892
893        private boolean mIsHistoricalPackageUsageAvailable = true;
894
895        boolean isHistoricalPackageUsageAvailable() {
896            return mIsHistoricalPackageUsageAvailable;
897        }
898
899        void write(boolean force) {
900            if (force) {
901                writeInternal();
902                return;
903            }
904            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
905                && !DEBUG_DEXOPT) {
906                return;
907            }
908            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
909                new Thread("PackageUsage_DiskWriter") {
910                    @Override
911                    public void run() {
912                        try {
913                            writeInternal();
914                        } finally {
915                            mBackgroundWriteRunning.set(false);
916                        }
917                    }
918                }.start();
919            }
920        }
921
922        private void writeInternal() {
923            synchronized (mPackages) {
924                synchronized (mFileLock) {
925                    AtomicFile file = getFile();
926                    FileOutputStream f = null;
927                    try {
928                        f = file.startWrite();
929                        BufferedOutputStream out = new BufferedOutputStream(f);
930                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
931                        StringBuilder sb = new StringBuilder();
932                        for (PackageParser.Package pkg : mPackages.values()) {
933                            if (pkg.mLastPackageUsageTimeInMills == 0) {
934                                continue;
935                            }
936                            sb.setLength(0);
937                            sb.append(pkg.packageName);
938                            sb.append(' ');
939                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
940                            sb.append('\n');
941                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
942                        }
943                        out.flush();
944                        file.finishWrite(f);
945                    } catch (IOException e) {
946                        if (f != null) {
947                            file.failWrite(f);
948                        }
949                        Log.e(TAG, "Failed to write package usage times", e);
950                    }
951                }
952            }
953            mLastWritten.set(SystemClock.elapsedRealtime());
954        }
955
956        void readLP() {
957            synchronized (mFileLock) {
958                AtomicFile file = getFile();
959                BufferedInputStream in = null;
960                try {
961                    in = new BufferedInputStream(file.openRead());
962                    StringBuffer sb = new StringBuffer();
963                    while (true) {
964                        String packageName = readToken(in, sb, ' ');
965                        if (packageName == null) {
966                            break;
967                        }
968                        String timeInMillisString = readToken(in, sb, '\n');
969                        if (timeInMillisString == null) {
970                            throw new IOException("Failed to find last usage time for package "
971                                                  + packageName);
972                        }
973                        PackageParser.Package pkg = mPackages.get(packageName);
974                        if (pkg == null) {
975                            continue;
976                        }
977                        long timeInMillis;
978                        try {
979                            timeInMillis = Long.parseLong(timeInMillisString.toString());
980                        } catch (NumberFormatException e) {
981                            throw new IOException("Failed to parse " + timeInMillisString
982                                                  + " as a long.", e);
983                        }
984                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
985                    }
986                } catch (FileNotFoundException expected) {
987                    mIsHistoricalPackageUsageAvailable = false;
988                } catch (IOException e) {
989                    Log.w(TAG, "Failed to read package usage times", e);
990                } finally {
991                    IoUtils.closeQuietly(in);
992                }
993            }
994            mLastWritten.set(SystemClock.elapsedRealtime());
995        }
996
997        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
998                throws IOException {
999            sb.setLength(0);
1000            while (true) {
1001                int ch = in.read();
1002                if (ch == -1) {
1003                    if (sb.length() == 0) {
1004                        return null;
1005                    }
1006                    throw new IOException("Unexpected EOF");
1007                }
1008                if (ch == endOfToken) {
1009                    return sb.toString();
1010                }
1011                sb.append((char)ch);
1012            }
1013        }
1014
1015        private AtomicFile getFile() {
1016            File dataDir = Environment.getDataDirectory();
1017            File systemDir = new File(dataDir, "system");
1018            File fname = new File(systemDir, "package-usage.list");
1019            return new AtomicFile(fname);
1020        }
1021    }
1022
1023    class PackageHandler extends Handler {
1024        private boolean mBound = false;
1025        final ArrayList<HandlerParams> mPendingInstalls =
1026            new ArrayList<HandlerParams>();
1027
1028        private boolean connectToService() {
1029            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1030                    " DefaultContainerService");
1031            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1032            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1033            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1034                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1035                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1036                mBound = true;
1037                return true;
1038            }
1039            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1040            return false;
1041        }
1042
1043        private void disconnectService() {
1044            mContainerService = null;
1045            mBound = false;
1046            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1047            mContext.unbindService(mDefContainerConn);
1048            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1049        }
1050
1051        PackageHandler(Looper looper) {
1052            super(looper);
1053        }
1054
1055        public void handleMessage(Message msg) {
1056            try {
1057                doHandleMessage(msg);
1058            } finally {
1059                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1060            }
1061        }
1062
1063        void doHandleMessage(Message msg) {
1064            switch (msg.what) {
1065                case INIT_COPY: {
1066                    HandlerParams params = (HandlerParams) msg.obj;
1067                    int idx = mPendingInstalls.size();
1068                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1069                    // If a bind was already initiated we dont really
1070                    // need to do anything. The pending install
1071                    // will be processed later on.
1072                    if (!mBound) {
1073                        // If this is the only one pending we might
1074                        // have to bind to the service again.
1075                        if (!connectToService()) {
1076                            Slog.e(TAG, "Failed to bind to media container service");
1077                            params.serviceError();
1078                            return;
1079                        } else {
1080                            // Once we bind to the service, the first
1081                            // pending request will be processed.
1082                            mPendingInstalls.add(idx, params);
1083                        }
1084                    } else {
1085                        mPendingInstalls.add(idx, params);
1086                        // Already bound to the service. Just make
1087                        // sure we trigger off processing the first request.
1088                        if (idx == 0) {
1089                            mHandler.sendEmptyMessage(MCS_BOUND);
1090                        }
1091                    }
1092                    break;
1093                }
1094                case MCS_BOUND: {
1095                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1096                    if (msg.obj != null) {
1097                        mContainerService = (IMediaContainerService) msg.obj;
1098                    }
1099                    if (mContainerService == null) {
1100                        // Something seriously wrong. Bail out
1101                        Slog.e(TAG, "Cannot bind to media container service");
1102                        for (HandlerParams params : mPendingInstalls) {
1103                            // Indicate service bind error
1104                            params.serviceError();
1105                        }
1106                        mPendingInstalls.clear();
1107                    } else if (mPendingInstalls.size() > 0) {
1108                        HandlerParams params = mPendingInstalls.get(0);
1109                        if (params != null) {
1110                            if (params.startCopy()) {
1111                                // We are done...  look for more work or to
1112                                // go idle.
1113                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1114                                        "Checking for more work or unbind...");
1115                                // Delete pending install
1116                                if (mPendingInstalls.size() > 0) {
1117                                    mPendingInstalls.remove(0);
1118                                }
1119                                if (mPendingInstalls.size() == 0) {
1120                                    if (mBound) {
1121                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1122                                                "Posting delayed MCS_UNBIND");
1123                                        removeMessages(MCS_UNBIND);
1124                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1125                                        // Unbind after a little delay, to avoid
1126                                        // continual thrashing.
1127                                        sendMessageDelayed(ubmsg, 10000);
1128                                    }
1129                                } else {
1130                                    // There are more pending requests in queue.
1131                                    // Just post MCS_BOUND message to trigger processing
1132                                    // of next pending install.
1133                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1134                                            "Posting MCS_BOUND for next work");
1135                                    mHandler.sendEmptyMessage(MCS_BOUND);
1136                                }
1137                            }
1138                        }
1139                    } else {
1140                        // Should never happen ideally.
1141                        Slog.w(TAG, "Empty queue");
1142                    }
1143                    break;
1144                }
1145                case MCS_RECONNECT: {
1146                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1147                    if (mPendingInstalls.size() > 0) {
1148                        if (mBound) {
1149                            disconnectService();
1150                        }
1151                        if (!connectToService()) {
1152                            Slog.e(TAG, "Failed to bind to media container service");
1153                            for (HandlerParams params : mPendingInstalls) {
1154                                // Indicate service bind error
1155                                params.serviceError();
1156                            }
1157                            mPendingInstalls.clear();
1158                        }
1159                    }
1160                    break;
1161                }
1162                case MCS_UNBIND: {
1163                    // If there is no actual work left, then time to unbind.
1164                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1165
1166                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1167                        if (mBound) {
1168                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1169
1170                            disconnectService();
1171                        }
1172                    } else if (mPendingInstalls.size() > 0) {
1173                        // There are more pending requests in queue.
1174                        // Just post MCS_BOUND message to trigger processing
1175                        // of next pending install.
1176                        mHandler.sendEmptyMessage(MCS_BOUND);
1177                    }
1178
1179                    break;
1180                }
1181                case MCS_GIVE_UP: {
1182                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1183                    mPendingInstalls.remove(0);
1184                    break;
1185                }
1186                case SEND_PENDING_BROADCAST: {
1187                    String packages[];
1188                    ArrayList<String> components[];
1189                    int size = 0;
1190                    int uids[];
1191                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1192                    synchronized (mPackages) {
1193                        if (mPendingBroadcasts == null) {
1194                            return;
1195                        }
1196                        size = mPendingBroadcasts.size();
1197                        if (size <= 0) {
1198                            // Nothing to be done. Just return
1199                            return;
1200                        }
1201                        packages = new String[size];
1202                        components = new ArrayList[size];
1203                        uids = new int[size];
1204                        int i = 0;  // filling out the above arrays
1205
1206                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1207                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1208                            Iterator<Map.Entry<String, ArrayList<String>>> it
1209                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1210                                            .entrySet().iterator();
1211                            while (it.hasNext() && i < size) {
1212                                Map.Entry<String, ArrayList<String>> ent = it.next();
1213                                packages[i] = ent.getKey();
1214                                components[i] = ent.getValue();
1215                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1216                                uids[i] = (ps != null)
1217                                        ? UserHandle.getUid(packageUserId, ps.appId)
1218                                        : -1;
1219                                i++;
1220                            }
1221                        }
1222                        size = i;
1223                        mPendingBroadcasts.clear();
1224                    }
1225                    // Send broadcasts
1226                    for (int i = 0; i < size; i++) {
1227                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1228                    }
1229                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1230                    break;
1231                }
1232                case START_CLEANING_PACKAGE: {
1233                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1234                    final String packageName = (String)msg.obj;
1235                    final int userId = msg.arg1;
1236                    final boolean andCode = msg.arg2 != 0;
1237                    synchronized (mPackages) {
1238                        if (userId == UserHandle.USER_ALL) {
1239                            int[] users = sUserManager.getUserIds();
1240                            for (int user : users) {
1241                                mSettings.addPackageToCleanLPw(
1242                                        new PackageCleanItem(user, packageName, andCode));
1243                            }
1244                        } else {
1245                            mSettings.addPackageToCleanLPw(
1246                                    new PackageCleanItem(userId, packageName, andCode));
1247                        }
1248                    }
1249                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1250                    startCleaningPackages();
1251                } break;
1252                case POST_INSTALL: {
1253                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1254                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1255                    mRunningInstalls.delete(msg.arg1);
1256                    boolean deleteOld = false;
1257
1258                    if (data != null) {
1259                        InstallArgs args = data.args;
1260                        PackageInstalledInfo res = data.res;
1261
1262                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1263                            res.removedInfo.sendBroadcast(false, true, false);
1264                            Bundle extras = new Bundle(1);
1265                            extras.putInt(Intent.EXTRA_UID, res.uid);
1266
1267                            // Now that we successfully installed the package, grant runtime
1268                            // permissions if requested before broadcasting the install.
1269                            if ((args.installFlags
1270                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1271                                grantRequestedRuntimePermissions(res.pkg,
1272                                        args.user.getIdentifier());
1273                            }
1274
1275                            // Determine the set of users who are adding this
1276                            // package for the first time vs. those who are seeing
1277                            // an update.
1278                            int[] firstUsers;
1279                            int[] updateUsers = new int[0];
1280                            if (res.origUsers == null || res.origUsers.length == 0) {
1281                                firstUsers = res.newUsers;
1282                            } else {
1283                                firstUsers = new int[0];
1284                                for (int i=0; i<res.newUsers.length; i++) {
1285                                    int user = res.newUsers[i];
1286                                    boolean isNew = true;
1287                                    for (int j=0; j<res.origUsers.length; j++) {
1288                                        if (res.origUsers[j] == user) {
1289                                            isNew = false;
1290                                            break;
1291                                        }
1292                                    }
1293                                    if (isNew) {
1294                                        int[] newFirst = new int[firstUsers.length+1];
1295                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1296                                                firstUsers.length);
1297                                        newFirst[firstUsers.length] = user;
1298                                        firstUsers = newFirst;
1299                                    } else {
1300                                        int[] newUpdate = new int[updateUsers.length+1];
1301                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1302                                                updateUsers.length);
1303                                        newUpdate[updateUsers.length] = user;
1304                                        updateUsers = newUpdate;
1305                                    }
1306                                }
1307                            }
1308                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1309                                    res.pkg.applicationInfo.packageName,
1310                                    extras, null, null, firstUsers);
1311                            final boolean update = res.removedInfo.removedPackage != null;
1312                            if (update) {
1313                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1314                            }
1315                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1316                                    res.pkg.applicationInfo.packageName,
1317                                    extras, null, null, updateUsers);
1318                            if (update) {
1319                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1320                                        res.pkg.applicationInfo.packageName,
1321                                        extras, null, null, updateUsers);
1322                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1323                                        null, null,
1324                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1325
1326                                // treat asec-hosted packages like removable media on upgrade
1327                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1328                                    if (DEBUG_INSTALL) {
1329                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1330                                                + " is ASEC-hosted -> AVAILABLE");
1331                                    }
1332                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1333                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1334                                    pkgList.add(res.pkg.applicationInfo.packageName);
1335                                    sendResourcesChangedBroadcast(true, true,
1336                                            pkgList,uidArray, null);
1337                                }
1338                            }
1339                            if (res.removedInfo.args != null) {
1340                                // Remove the replaced package's older resources safely now
1341                                deleteOld = true;
1342                            }
1343
1344                            // Log current value of "unknown sources" setting
1345                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1346                                getUnknownSourcesSettings());
1347                        }
1348                        // Force a gc to clear up things
1349                        Runtime.getRuntime().gc();
1350                        // We delete after a gc for applications  on sdcard.
1351                        if (deleteOld) {
1352                            synchronized (mInstallLock) {
1353                                res.removedInfo.args.doPostDeleteLI(true);
1354                            }
1355                        }
1356                        if (args.observer != null) {
1357                            try {
1358                                Bundle extras = extrasForInstallResult(res);
1359                                args.observer.onPackageInstalled(res.name, res.returnCode,
1360                                        res.returnMsg, extras);
1361                            } catch (RemoteException e) {
1362                                Slog.i(TAG, "Observer no longer exists.");
1363                            }
1364                        }
1365                    } else {
1366                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1367                    }
1368                } break;
1369                case UPDATED_MEDIA_STATUS: {
1370                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1371                    boolean reportStatus = msg.arg1 == 1;
1372                    boolean doGc = msg.arg2 == 1;
1373                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1374                    if (doGc) {
1375                        // Force a gc to clear up stale containers.
1376                        Runtime.getRuntime().gc();
1377                    }
1378                    if (msg.obj != null) {
1379                        @SuppressWarnings("unchecked")
1380                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1381                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1382                        // Unload containers
1383                        unloadAllContainers(args);
1384                    }
1385                    if (reportStatus) {
1386                        try {
1387                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1388                            PackageHelper.getMountService().finishMediaUpdate();
1389                        } catch (RemoteException e) {
1390                            Log.e(TAG, "MountService not running?");
1391                        }
1392                    }
1393                } break;
1394                case WRITE_SETTINGS: {
1395                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1396                    synchronized (mPackages) {
1397                        removeMessages(WRITE_SETTINGS);
1398                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1399                        mSettings.writeLPr();
1400                        mDirtyUsers.clear();
1401                    }
1402                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1403                } break;
1404                case WRITE_PACKAGE_RESTRICTIONS: {
1405                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1406                    synchronized (mPackages) {
1407                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1408                        for (int userId : mDirtyUsers) {
1409                            mSettings.writePackageRestrictionsLPr(userId);
1410                        }
1411                        mDirtyUsers.clear();
1412                    }
1413                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1414                } break;
1415                case CHECK_PENDING_VERIFICATION: {
1416                    final int verificationId = msg.arg1;
1417                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1418
1419                    if ((state != null) && !state.timeoutExtended()) {
1420                        final InstallArgs args = state.getInstallArgs();
1421                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1422
1423                        Slog.i(TAG, "Verification timed out for " + originUri);
1424                        mPendingVerification.remove(verificationId);
1425
1426                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1427
1428                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1429                            Slog.i(TAG, "Continuing with installation of " + originUri);
1430                            state.setVerifierResponse(Binder.getCallingUid(),
1431                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1432                            broadcastPackageVerified(verificationId, originUri,
1433                                    PackageManager.VERIFICATION_ALLOW,
1434                                    state.getInstallArgs().getUser());
1435                            try {
1436                                ret = args.copyApk(mContainerService, true);
1437                            } catch (RemoteException e) {
1438                                Slog.e(TAG, "Could not contact the ContainerService");
1439                            }
1440                        } else {
1441                            broadcastPackageVerified(verificationId, originUri,
1442                                    PackageManager.VERIFICATION_REJECT,
1443                                    state.getInstallArgs().getUser());
1444                        }
1445
1446                        processPendingInstall(args, ret);
1447                        mHandler.sendEmptyMessage(MCS_UNBIND);
1448                    }
1449                    break;
1450                }
1451                case PACKAGE_VERIFIED: {
1452                    final int verificationId = msg.arg1;
1453
1454                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1455                    if (state == null) {
1456                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1457                        break;
1458                    }
1459
1460                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1461
1462                    state.setVerifierResponse(response.callerUid, response.code);
1463
1464                    if (state.isVerificationComplete()) {
1465                        mPendingVerification.remove(verificationId);
1466
1467                        final InstallArgs args = state.getInstallArgs();
1468                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1469
1470                        int ret;
1471                        if (state.isInstallAllowed()) {
1472                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1473                            broadcastPackageVerified(verificationId, originUri,
1474                                    response.code, state.getInstallArgs().getUser());
1475                            try {
1476                                ret = args.copyApk(mContainerService, true);
1477                            } catch (RemoteException e) {
1478                                Slog.e(TAG, "Could not contact the ContainerService");
1479                            }
1480                        } else {
1481                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1482                        }
1483
1484                        processPendingInstall(args, ret);
1485
1486                        mHandler.sendEmptyMessage(MCS_UNBIND);
1487                    }
1488
1489                    break;
1490                }
1491                case START_INTENT_FILTER_VERIFICATIONS: {
1492                    int userId = msg.arg1;
1493                    int verifierUid = msg.arg2;
1494                    PackageParser.Package pkg = (PackageParser.Package)msg.obj;
1495
1496                    verifyIntentFiltersIfNeeded(userId, verifierUid, pkg);
1497                    break;
1498                }
1499                case INTENT_FILTER_VERIFIED: {
1500                    final int verificationId = msg.arg1;
1501
1502                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1503                            verificationId);
1504                    if (state == null) {
1505                        Slog.w(TAG, "Invalid IntentFilter verification token "
1506                                + verificationId + " received");
1507                        break;
1508                    }
1509
1510                    final int userId = state.getUserId();
1511
1512                    Slog.d(TAG, "Processing IntentFilter verification with token:"
1513                            + verificationId + " and userId:" + userId);
1514
1515                    final IntentFilterVerificationResponse response =
1516                            (IntentFilterVerificationResponse) msg.obj;
1517
1518                    state.setVerifierResponse(response.callerUid, response.code);
1519
1520                    Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1521                            + " and userId:" + userId
1522                            + " is settings verifier response with response code:"
1523                            + response.code);
1524
1525                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1526                        Slog.d(TAG, "Domains failing verification: "
1527                                + response.getFailedDomainsString());
1528                    }
1529
1530                    if (state.isVerificationComplete()) {
1531                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1532                    } else {
1533                        Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1534                                + " was not said to be complete");
1535                    }
1536
1537                    break;
1538                }
1539            }
1540        }
1541    }
1542
1543    private StorageEventListener mStorageListener = new StorageEventListener() {
1544        @Override
1545        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1546            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1547                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1548                    // TODO: ensure that private directories exist for all active users
1549                    // TODO: remove user data whose serial number doesn't match
1550                    loadPrivatePackages(vol);
1551                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1552                    unloadPrivatePackages(vol);
1553                }
1554            }
1555
1556            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1557                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1558                    updateExternalMediaStatus(true, false);
1559                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1560                    updateExternalMediaStatus(false, false);
1561                }
1562            }
1563        }
1564
1565        @Override
1566        public void onVolumeForgotten(String fsUuid) {
1567            // TODO: remove all packages hosted on this uuid
1568        }
1569    };
1570
1571    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1572        if (userId >= UserHandle.USER_OWNER) {
1573            grantRequestedRuntimePermissionsForUser(pkg, userId);
1574        } else if (userId == UserHandle.USER_ALL) {
1575            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1576                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1577            }
1578        }
1579    }
1580
1581    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1582        SettingBase sb = (SettingBase) pkg.mExtras;
1583        if (sb == null) {
1584            return;
1585        }
1586
1587        PermissionsState permissionsState = sb.getPermissionsState();
1588
1589        for (String permission : pkg.requestedPermissions) {
1590            BasePermission bp = mSettings.mPermissions.get(permission);
1591            if (bp != null && bp.isRuntime()) {
1592                permissionsState.grantRuntimePermission(bp, userId);
1593            }
1594        }
1595    }
1596
1597    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1598        Bundle extras = null;
1599        switch (res.returnCode) {
1600            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1601                extras = new Bundle();
1602                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1603                        res.origPermission);
1604                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1605                        res.origPackage);
1606                break;
1607            }
1608            case PackageManager.INSTALL_SUCCEEDED: {
1609                extras = new Bundle();
1610                extras.putBoolean(Intent.EXTRA_REPLACING,
1611                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1612                break;
1613            }
1614        }
1615        return extras;
1616    }
1617
1618    void scheduleWriteSettingsLocked() {
1619        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1620            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1621        }
1622    }
1623
1624    void scheduleWritePackageRestrictionsLocked(int userId) {
1625        if (!sUserManager.exists(userId)) return;
1626        mDirtyUsers.add(userId);
1627        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1628            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1629        }
1630    }
1631
1632    public static PackageManagerService main(Context context, Installer installer,
1633            boolean factoryTest, boolean onlyCore) {
1634        PackageManagerService m = new PackageManagerService(context, installer,
1635                factoryTest, onlyCore);
1636        ServiceManager.addService("package", m);
1637        return m;
1638    }
1639
1640    static String[] splitString(String str, char sep) {
1641        int count = 1;
1642        int i = 0;
1643        while ((i=str.indexOf(sep, i)) >= 0) {
1644            count++;
1645            i++;
1646        }
1647
1648        String[] res = new String[count];
1649        i=0;
1650        count = 0;
1651        int lastI=0;
1652        while ((i=str.indexOf(sep, i)) >= 0) {
1653            res[count] = str.substring(lastI, i);
1654            count++;
1655            i++;
1656            lastI = i;
1657        }
1658        res[count] = str.substring(lastI, str.length());
1659        return res;
1660    }
1661
1662    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1663        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1664                Context.DISPLAY_SERVICE);
1665        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1666    }
1667
1668    public PackageManagerService(Context context, Installer installer,
1669            boolean factoryTest, boolean onlyCore) {
1670        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1671                SystemClock.uptimeMillis());
1672
1673        if (mSdkVersion <= 0) {
1674            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1675        }
1676
1677        mContext = context;
1678        mFactoryTest = factoryTest;
1679        mOnlyCore = onlyCore;
1680        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1681        mMetrics = new DisplayMetrics();
1682        mSettings = new Settings(mPackages);
1683        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1684                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1685        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1686                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1687        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1688                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1689        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1690                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1691        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1692                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1693        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1694                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1695
1696        // TODO: add a property to control this?
1697        long dexOptLRUThresholdInMinutes;
1698        if (mLazyDexOpt) {
1699            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1700        } else {
1701            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1702        }
1703        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1704
1705        String separateProcesses = SystemProperties.get("debug.separate_processes");
1706        if (separateProcesses != null && separateProcesses.length() > 0) {
1707            if ("*".equals(separateProcesses)) {
1708                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1709                mSeparateProcesses = null;
1710                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1711            } else {
1712                mDefParseFlags = 0;
1713                mSeparateProcesses = separateProcesses.split(",");
1714                Slog.w(TAG, "Running with debug.separate_processes: "
1715                        + separateProcesses);
1716            }
1717        } else {
1718            mDefParseFlags = 0;
1719            mSeparateProcesses = null;
1720        }
1721
1722        mInstaller = installer;
1723        mPackageDexOptimizer = new PackageDexOptimizer(this);
1724        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1725
1726        getDefaultDisplayMetrics(context, mMetrics);
1727
1728        SystemConfig systemConfig = SystemConfig.getInstance();
1729        mGlobalGids = systemConfig.getGlobalGids();
1730        mSystemPermissions = systemConfig.getSystemPermissions();
1731        mAvailableFeatures = systemConfig.getAvailableFeatures();
1732
1733        synchronized (mInstallLock) {
1734        // writer
1735        synchronized (mPackages) {
1736            mHandlerThread = new ServiceThread(TAG,
1737                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1738            mHandlerThread.start();
1739            mHandler = new PackageHandler(mHandlerThread.getLooper());
1740            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1741
1742            File dataDir = Environment.getDataDirectory();
1743            mAppDataDir = new File(dataDir, "data");
1744            mAppInstallDir = new File(dataDir, "app");
1745            mAppLib32InstallDir = new File(dataDir, "app-lib");
1746            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1747            mUserAppDataDir = new File(dataDir, "user");
1748            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1749
1750            sUserManager = new UserManagerService(context, this,
1751                    mInstallLock, mPackages);
1752
1753            // Propagate permission configuration in to package manager.
1754            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1755                    = systemConfig.getPermissions();
1756            for (int i=0; i<permConfig.size(); i++) {
1757                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1758                BasePermission bp = mSettings.mPermissions.get(perm.name);
1759                if (bp == null) {
1760                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1761                    mSettings.mPermissions.put(perm.name, bp);
1762                }
1763                if (perm.gids != null) {
1764                    bp.setGids(perm.gids, perm.perUser);
1765                }
1766            }
1767
1768            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1769            for (int i=0; i<libConfig.size(); i++) {
1770                mSharedLibraries.put(libConfig.keyAt(i),
1771                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1772            }
1773
1774            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1775
1776            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1777                    mSdkVersion, mOnlyCore);
1778
1779            String customResolverActivity = Resources.getSystem().getString(
1780                    R.string.config_customResolverActivity);
1781            if (TextUtils.isEmpty(customResolverActivity)) {
1782                customResolverActivity = null;
1783            } else {
1784                mCustomResolverComponentName = ComponentName.unflattenFromString(
1785                        customResolverActivity);
1786            }
1787
1788            long startTime = SystemClock.uptimeMillis();
1789
1790            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1791                    startTime);
1792
1793            // Set flag to monitor and not change apk file paths when
1794            // scanning install directories.
1795            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1796
1797            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1798
1799            /**
1800             * Add everything in the in the boot class path to the
1801             * list of process files because dexopt will have been run
1802             * if necessary during zygote startup.
1803             */
1804            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1805            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1806
1807            if (bootClassPath != null) {
1808                String[] bootClassPathElements = splitString(bootClassPath, ':');
1809                for (String element : bootClassPathElements) {
1810                    alreadyDexOpted.add(element);
1811                }
1812            } else {
1813                Slog.w(TAG, "No BOOTCLASSPATH found!");
1814            }
1815
1816            if (systemServerClassPath != null) {
1817                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1818                for (String element : systemServerClassPathElements) {
1819                    alreadyDexOpted.add(element);
1820                }
1821            } else {
1822                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1823            }
1824
1825            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1826            final String[] dexCodeInstructionSets =
1827                    getDexCodeInstructionSets(
1828                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1829
1830            /**
1831             * Ensure all external libraries have had dexopt run on them.
1832             */
1833            if (mSharedLibraries.size() > 0) {
1834                // NOTE: For now, we're compiling these system "shared libraries"
1835                // (and framework jars) into all available architectures. It's possible
1836                // to compile them only when we come across an app that uses them (there's
1837                // already logic for that in scanPackageLI) but that adds some complexity.
1838                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1839                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1840                        final String lib = libEntry.path;
1841                        if (lib == null) {
1842                            continue;
1843                        }
1844
1845                        try {
1846                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1847                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1848                                alreadyDexOpted.add(lib);
1849                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1850                            }
1851                        } catch (FileNotFoundException e) {
1852                            Slog.w(TAG, "Library not found: " + lib);
1853                        } catch (IOException e) {
1854                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1855                                    + e.getMessage());
1856                        }
1857                    }
1858                }
1859            }
1860
1861            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1862
1863            // Gross hack for now: we know this file doesn't contain any
1864            // code, so don't dexopt it to avoid the resulting log spew.
1865            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1866
1867            // Gross hack for now: we know this file is only part of
1868            // the boot class path for art, so don't dexopt it to
1869            // avoid the resulting log spew.
1870            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1871
1872            /**
1873             * And there are a number of commands implemented in Java, which
1874             * we currently need to do the dexopt on so that they can be
1875             * run from a non-root shell.
1876             */
1877            String[] frameworkFiles = frameworkDir.list();
1878            if (frameworkFiles != null) {
1879                // TODO: We could compile these only for the most preferred ABI. We should
1880                // first double check that the dex files for these commands are not referenced
1881                // by other system apps.
1882                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1883                    for (int i=0; i<frameworkFiles.length; i++) {
1884                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1885                        String path = libPath.getPath();
1886                        // Skip the file if we already did it.
1887                        if (alreadyDexOpted.contains(path)) {
1888                            continue;
1889                        }
1890                        // Skip the file if it is not a type we want to dexopt.
1891                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1892                            continue;
1893                        }
1894                        try {
1895                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1896                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1897                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1898                            }
1899                        } catch (FileNotFoundException e) {
1900                            Slog.w(TAG, "Jar not found: " + path);
1901                        } catch (IOException e) {
1902                            Slog.w(TAG, "Exception reading jar: " + path, e);
1903                        }
1904                    }
1905                }
1906            }
1907
1908            // Collect vendor overlay packages.
1909            // (Do this before scanning any apps.)
1910            // For security and version matching reason, only consider
1911            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1912            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1913            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1914                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1915
1916            // Find base frameworks (resource packages without code).
1917            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1918                    | PackageParser.PARSE_IS_SYSTEM_DIR
1919                    | PackageParser.PARSE_IS_PRIVILEGED,
1920                    scanFlags | SCAN_NO_DEX, 0);
1921
1922            // Collected privileged system packages.
1923            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1924            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1925                    | PackageParser.PARSE_IS_SYSTEM_DIR
1926                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1927
1928            // Collect ordinary system packages.
1929            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1930            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1931                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1932
1933            // Collect all vendor packages.
1934            File vendorAppDir = new File("/vendor/app");
1935            try {
1936                vendorAppDir = vendorAppDir.getCanonicalFile();
1937            } catch (IOException e) {
1938                // failed to look up canonical path, continue with original one
1939            }
1940            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1941                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1942
1943            // Collect all OEM packages.
1944            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1945            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1946                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1947
1948            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1949            mInstaller.moveFiles();
1950
1951            // Prune any system packages that no longer exist.
1952            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1953            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1954            if (!mOnlyCore) {
1955                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1956                while (psit.hasNext()) {
1957                    PackageSetting ps = psit.next();
1958
1959                    /*
1960                     * If this is not a system app, it can't be a
1961                     * disable system app.
1962                     */
1963                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1964                        continue;
1965                    }
1966
1967                    /*
1968                     * If the package is scanned, it's not erased.
1969                     */
1970                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1971                    if (scannedPkg != null) {
1972                        /*
1973                         * If the system app is both scanned and in the
1974                         * disabled packages list, then it must have been
1975                         * added via OTA. Remove it from the currently
1976                         * scanned package so the previously user-installed
1977                         * application can be scanned.
1978                         */
1979                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1980                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1981                                    + ps.name + "; removing system app.  Last known codePath="
1982                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1983                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1984                                    + scannedPkg.mVersionCode);
1985                            removePackageLI(ps, true);
1986                            expectingBetter.put(ps.name, ps.codePath);
1987                        }
1988
1989                        continue;
1990                    }
1991
1992                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1993                        psit.remove();
1994                        logCriticalInfo(Log.WARN, "System package " + ps.name
1995                                + " no longer exists; wiping its data");
1996                        removeDataDirsLI(null, ps.name);
1997                    } else {
1998                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1999                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2000                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2001                        }
2002                    }
2003                }
2004            }
2005
2006            //look for any incomplete package installations
2007            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2008            //clean up list
2009            for(int i = 0; i < deletePkgsList.size(); i++) {
2010                //clean up here
2011                cleanupInstallFailedPackage(deletePkgsList.get(i));
2012            }
2013            //delete tmp files
2014            deleteTempPackageFiles();
2015
2016            // Remove any shared userIDs that have no associated packages
2017            mSettings.pruneSharedUsersLPw();
2018
2019            if (!mOnlyCore) {
2020                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2021                        SystemClock.uptimeMillis());
2022                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2023
2024                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2025                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2026
2027                /**
2028                 * Remove disable package settings for any updated system
2029                 * apps that were removed via an OTA. If they're not a
2030                 * previously-updated app, remove them completely.
2031                 * Otherwise, just revoke their system-level permissions.
2032                 */
2033                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2034                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2035                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2036
2037                    String msg;
2038                    if (deletedPkg == null) {
2039                        msg = "Updated system package " + deletedAppName
2040                                + " no longer exists; wiping its data";
2041                        removeDataDirsLI(null, deletedAppName);
2042                    } else {
2043                        msg = "Updated system app + " + deletedAppName
2044                                + " no longer present; removing system privileges for "
2045                                + deletedAppName;
2046
2047                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2048
2049                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2050                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2051                    }
2052                    logCriticalInfo(Log.WARN, msg);
2053                }
2054
2055                /**
2056                 * Make sure all system apps that we expected to appear on
2057                 * the userdata partition actually showed up. If they never
2058                 * appeared, crawl back and revive the system version.
2059                 */
2060                for (int i = 0; i < expectingBetter.size(); i++) {
2061                    final String packageName = expectingBetter.keyAt(i);
2062                    if (!mPackages.containsKey(packageName)) {
2063                        final File scanFile = expectingBetter.valueAt(i);
2064
2065                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2066                                + " but never showed up; reverting to system");
2067
2068                        final int reparseFlags;
2069                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2070                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2071                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2072                                    | PackageParser.PARSE_IS_PRIVILEGED;
2073                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2074                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2075                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2076                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2077                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2078                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2079                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2080                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2081                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2082                        } else {
2083                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2084                            continue;
2085                        }
2086
2087                        mSettings.enableSystemPackageLPw(packageName);
2088
2089                        try {
2090                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2091                        } catch (PackageManagerException e) {
2092                            Slog.e(TAG, "Failed to parse original system package: "
2093                                    + e.getMessage());
2094                        }
2095                    }
2096                }
2097            }
2098
2099            // Now that we know all of the shared libraries, update all clients to have
2100            // the correct library paths.
2101            updateAllSharedLibrariesLPw();
2102
2103            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2104                // NOTE: We ignore potential failures here during a system scan (like
2105                // the rest of the commands above) because there's precious little we
2106                // can do about it. A settings error is reported, though.
2107                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2108                        false /* force dexopt */, false /* defer dexopt */);
2109            }
2110
2111            // Now that we know all the packages we are keeping,
2112            // read and update their last usage times.
2113            mPackageUsage.readLP();
2114
2115            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2116                    SystemClock.uptimeMillis());
2117            Slog.i(TAG, "Time to scan packages: "
2118                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2119                    + " seconds");
2120
2121            // If the platform SDK has changed since the last time we booted,
2122            // we need to re-grant app permission to catch any new ones that
2123            // appear.  This is really a hack, and means that apps can in some
2124            // cases get permissions that the user didn't initially explicitly
2125            // allow...  it would be nice to have some better way to handle
2126            // this situation.
2127            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2128                    != mSdkVersion;
2129            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2130                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2131                    + "; regranting permissions for internal storage");
2132            mSettings.mInternalSdkPlatform = mSdkVersion;
2133
2134            // For now runtime permissions are toggled via a system property.
2135            if (!RUNTIME_PERMISSIONS_ENABLED) {
2136                // Remove the runtime permissions state if the feature
2137                // was disabled by flipping the system property.
2138                mSettings.deleteRuntimePermissionsFiles();
2139            }
2140
2141            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2142                    | (regrantPermissions
2143                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2144                            : 0));
2145
2146            // If this is the first boot, and it is a normal boot, then
2147            // we need to initialize the default preferred apps.
2148            if (!mRestoredSettings && !onlyCore) {
2149                mSettings.readDefaultPreferredAppsLPw(this, 0);
2150            }
2151
2152            // If this is first boot after an OTA, and a normal boot, then
2153            // we need to clear code cache directories.
2154            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2155            if (mIsUpgrade && !onlyCore) {
2156                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2157                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2158                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2159                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2160                }
2161                mSettings.mFingerprint = Build.FINGERPRINT;
2162            }
2163
2164            primeDomainVerificationsLPw(false);
2165
2166            // All the changes are done during package scanning.
2167            mSettings.updateInternalDatabaseVersion();
2168
2169            // can downgrade to reader
2170            mSettings.writeLPr();
2171
2172            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2173                    SystemClock.uptimeMillis());
2174
2175            mRequiredVerifierPackage = getRequiredVerifierLPr();
2176
2177            mInstallerService = new PackageInstallerService(context, this);
2178
2179            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2180            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2181                    mIntentFilterVerifierComponent);
2182
2183        } // synchronized (mPackages)
2184        } // synchronized (mInstallLock)
2185
2186        // Now after opening every single application zip, make sure they
2187        // are all flushed.  Not really needed, but keeps things nice and
2188        // tidy.
2189        Runtime.getRuntime().gc();
2190    }
2191
2192    @Override
2193    public boolean isFirstBoot() {
2194        return !mRestoredSettings;
2195    }
2196
2197    @Override
2198    public boolean isOnlyCoreApps() {
2199        return mOnlyCore;
2200    }
2201
2202    @Override
2203    public boolean isUpgrade() {
2204        return mIsUpgrade;
2205    }
2206
2207    private String getRequiredVerifierLPr() {
2208        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2209        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2210                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2211
2212        String requiredVerifier = null;
2213
2214        final int N = receivers.size();
2215        for (int i = 0; i < N; i++) {
2216            final ResolveInfo info = receivers.get(i);
2217
2218            if (info.activityInfo == null) {
2219                continue;
2220            }
2221
2222            final String packageName = info.activityInfo.packageName;
2223
2224            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2225                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2226                continue;
2227            }
2228
2229            if (requiredVerifier != null) {
2230                throw new RuntimeException("There can be only one required verifier");
2231            }
2232
2233            requiredVerifier = packageName;
2234        }
2235
2236        return requiredVerifier;
2237    }
2238
2239    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2240        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2241        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2242                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2243
2244        ComponentName verifierComponentName = null;
2245
2246        int priority = -1000;
2247        final int N = receivers.size();
2248        for (int i = 0; i < N; i++) {
2249            final ResolveInfo info = receivers.get(i);
2250
2251            if (info.activityInfo == null) {
2252                continue;
2253            }
2254
2255            final String packageName = info.activityInfo.packageName;
2256
2257            final PackageSetting ps = mSettings.mPackages.get(packageName);
2258            if (ps == null) {
2259                continue;
2260            }
2261
2262            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2263                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2264                continue;
2265            }
2266
2267            // Select the IntentFilterVerifier with the highest priority
2268            if (priority < info.priority) {
2269                priority = info.priority;
2270                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2271                Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName +
2272                        " with priority: " + info.priority);
2273            }
2274        }
2275
2276        return verifierComponentName;
2277    }
2278
2279    private void primeDomainVerificationsLPw(boolean logging) {
2280        Slog.d(TAG, "Start priming domain verifications");
2281        boolean updated = false;
2282        ArraySet<String> allHostsSet = new ArraySet<>();
2283        for (PackageParser.Package pkg : mPackages.values()) {
2284            final String packageName = pkg.packageName;
2285            if (!hasDomainURLs(pkg)) {
2286                if (logging) {
2287                    Slog.d(TAG, "No priming domain verifications for " +
2288                            "package with no domain URLs: " + packageName);
2289                }
2290                continue;
2291            }
2292            if (!pkg.isSystemApp()) {
2293                if (logging) {
2294                    Slog.d(TAG, "No priming domain verifications for a non system package : " +
2295                            packageName);
2296                }
2297                continue;
2298            }
2299            for (PackageParser.Activity a : pkg.activities) {
2300                for (ActivityIntentInfo filter : a.intents) {
2301                    if (hasValidDomains(filter, false)) {
2302                        allHostsSet.addAll(filter.getHostsList());
2303                    }
2304                }
2305            }
2306            if (allHostsSet.size() == 0) {
2307                allHostsSet.add("*");
2308            }
2309            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2310            IntentFilterVerificationInfo ivi =
2311                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2312            if (ivi != null) {
2313                // We will always log this
2314                Slog.d(TAG, "Priming domain verifications for package: " + packageName +
2315                        " with hosts:" + ivi.getDomainsString());
2316                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2317                updated = true;
2318            }
2319            else {
2320                if (logging) {
2321                    Slog.d(TAG, "No priming domain verifications for package: " + packageName);
2322                }
2323            }
2324            allHostsSet.clear();
2325        }
2326        if (updated) {
2327            if (logging) {
2328                Slog.d(TAG, "Will need to write primed domain verifications");
2329            }
2330        }
2331        Slog.d(TAG, "End priming domain verifications");
2332    }
2333
2334    @Override
2335    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2336            throws RemoteException {
2337        try {
2338            return super.onTransact(code, data, reply, flags);
2339        } catch (RuntimeException e) {
2340            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2341                Slog.wtf(TAG, "Package Manager Crash", e);
2342            }
2343            throw e;
2344        }
2345    }
2346
2347    void cleanupInstallFailedPackage(PackageSetting ps) {
2348        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2349
2350        removeDataDirsLI(ps.volumeUuid, ps.name);
2351        if (ps.codePath != null) {
2352            if (ps.codePath.isDirectory()) {
2353                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2354            } else {
2355                ps.codePath.delete();
2356            }
2357        }
2358        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2359            if (ps.resourcePath.isDirectory()) {
2360                FileUtils.deleteContents(ps.resourcePath);
2361            }
2362            ps.resourcePath.delete();
2363        }
2364        mSettings.removePackageLPw(ps.name);
2365    }
2366
2367    static int[] appendInts(int[] cur, int[] add) {
2368        if (add == null) return cur;
2369        if (cur == null) return add;
2370        final int N = add.length;
2371        for (int i=0; i<N; i++) {
2372            cur = appendInt(cur, add[i]);
2373        }
2374        return cur;
2375    }
2376
2377    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2378        if (!sUserManager.exists(userId)) return null;
2379        final PackageSetting ps = (PackageSetting) p.mExtras;
2380        if (ps == null) {
2381            return null;
2382        }
2383
2384        final PermissionsState permissionsState = ps.getPermissionsState();
2385
2386        final int[] gids = permissionsState.computeGids(userId);
2387        final Set<String> permissions = permissionsState.getPermissions(userId);
2388        final PackageUserState state = ps.readUserState(userId);
2389
2390        return PackageParser.generatePackageInfo(p, gids, flags,
2391                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2392    }
2393
2394    @Override
2395    public boolean isPackageFrozen(String packageName) {
2396        synchronized (mPackages) {
2397            final PackageSetting ps = mSettings.mPackages.get(packageName);
2398            if (ps != null) {
2399                return ps.frozen;
2400            }
2401        }
2402        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2403        return true;
2404    }
2405
2406    @Override
2407    public boolean isPackageAvailable(String packageName, int userId) {
2408        if (!sUserManager.exists(userId)) return false;
2409        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2410        synchronized (mPackages) {
2411            PackageParser.Package p = mPackages.get(packageName);
2412            if (p != null) {
2413                final PackageSetting ps = (PackageSetting) p.mExtras;
2414                if (ps != null) {
2415                    final PackageUserState state = ps.readUserState(userId);
2416                    if (state != null) {
2417                        return PackageParser.isAvailable(state);
2418                    }
2419                }
2420            }
2421        }
2422        return false;
2423    }
2424
2425    @Override
2426    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2427        if (!sUserManager.exists(userId)) return null;
2428        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2429        // reader
2430        synchronized (mPackages) {
2431            PackageParser.Package p = mPackages.get(packageName);
2432            if (DEBUG_PACKAGE_INFO)
2433                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2434            if (p != null) {
2435                return generatePackageInfo(p, flags, userId);
2436            }
2437            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2438                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2439            }
2440        }
2441        return null;
2442    }
2443
2444    @Override
2445    public String[] currentToCanonicalPackageNames(String[] names) {
2446        String[] out = new String[names.length];
2447        // reader
2448        synchronized (mPackages) {
2449            for (int i=names.length-1; i>=0; i--) {
2450                PackageSetting ps = mSettings.mPackages.get(names[i]);
2451                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2452            }
2453        }
2454        return out;
2455    }
2456
2457    @Override
2458    public String[] canonicalToCurrentPackageNames(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                String cur = mSettings.mRenamedPackages.get(names[i]);
2464                out[i] = cur != null ? cur : names[i];
2465            }
2466        }
2467        return out;
2468    }
2469
2470    @Override
2471    public int getPackageUid(String packageName, int userId) {
2472        if (!sUserManager.exists(userId)) return -1;
2473        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2474
2475        // reader
2476        synchronized (mPackages) {
2477            PackageParser.Package p = mPackages.get(packageName);
2478            if(p != null) {
2479                return UserHandle.getUid(userId, p.applicationInfo.uid);
2480            }
2481            PackageSetting ps = mSettings.mPackages.get(packageName);
2482            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2483                return -1;
2484            }
2485            p = ps.pkg;
2486            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2487        }
2488    }
2489
2490    @Override
2491    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2492        if (!sUserManager.exists(userId)) {
2493            return null;
2494        }
2495
2496        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2497                "getPackageGids");
2498
2499        // reader
2500        synchronized (mPackages) {
2501            PackageParser.Package p = mPackages.get(packageName);
2502            if (DEBUG_PACKAGE_INFO) {
2503                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2504            }
2505            if (p != null) {
2506                PackageSetting ps = (PackageSetting) p.mExtras;
2507                return ps.getPermissionsState().computeGids(userId);
2508            }
2509        }
2510
2511        return null;
2512    }
2513
2514    static PermissionInfo generatePermissionInfo(
2515            BasePermission bp, int flags) {
2516        if (bp.perm != null) {
2517            return PackageParser.generatePermissionInfo(bp.perm, flags);
2518        }
2519        PermissionInfo pi = new PermissionInfo();
2520        pi.name = bp.name;
2521        pi.packageName = bp.sourcePackage;
2522        pi.nonLocalizedLabel = bp.name;
2523        pi.protectionLevel = bp.protectionLevel;
2524        return pi;
2525    }
2526
2527    @Override
2528    public PermissionInfo getPermissionInfo(String name, int flags) {
2529        // reader
2530        synchronized (mPackages) {
2531            final BasePermission p = mSettings.mPermissions.get(name);
2532            if (p != null) {
2533                return generatePermissionInfo(p, flags);
2534            }
2535            return null;
2536        }
2537    }
2538
2539    @Override
2540    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2541        // reader
2542        synchronized (mPackages) {
2543            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2544            for (BasePermission p : mSettings.mPermissions.values()) {
2545                if (group == null) {
2546                    if (p.perm == null || p.perm.info.group == null) {
2547                        out.add(generatePermissionInfo(p, flags));
2548                    }
2549                } else {
2550                    if (p.perm != null && group.equals(p.perm.info.group)) {
2551                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2552                    }
2553                }
2554            }
2555
2556            if (out.size() > 0) {
2557                return out;
2558            }
2559            return mPermissionGroups.containsKey(group) ? out : null;
2560        }
2561    }
2562
2563    @Override
2564    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2565        // reader
2566        synchronized (mPackages) {
2567            return PackageParser.generatePermissionGroupInfo(
2568                    mPermissionGroups.get(name), flags);
2569        }
2570    }
2571
2572    @Override
2573    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2574        // reader
2575        synchronized (mPackages) {
2576            final int N = mPermissionGroups.size();
2577            ArrayList<PermissionGroupInfo> out
2578                    = new ArrayList<PermissionGroupInfo>(N);
2579            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2580                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2581            }
2582            return out;
2583        }
2584    }
2585
2586    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2587            int userId) {
2588        if (!sUserManager.exists(userId)) return null;
2589        PackageSetting ps = mSettings.mPackages.get(packageName);
2590        if (ps != null) {
2591            if (ps.pkg == null) {
2592                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2593                        flags, userId);
2594                if (pInfo != null) {
2595                    return pInfo.applicationInfo;
2596                }
2597                return null;
2598            }
2599            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2600                    ps.readUserState(userId), userId);
2601        }
2602        return null;
2603    }
2604
2605    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2606            int userId) {
2607        if (!sUserManager.exists(userId)) return null;
2608        PackageSetting ps = mSettings.mPackages.get(packageName);
2609        if (ps != null) {
2610            PackageParser.Package pkg = ps.pkg;
2611            if (pkg == null) {
2612                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2613                    return null;
2614                }
2615                // Only data remains, so we aren't worried about code paths
2616                pkg = new PackageParser.Package(packageName);
2617                pkg.applicationInfo.packageName = packageName;
2618                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2619                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2620                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2621                        packageName, userId).getAbsolutePath();
2622                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2623                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2624            }
2625            return generatePackageInfo(pkg, flags, userId);
2626        }
2627        return null;
2628    }
2629
2630    @Override
2631    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2632        if (!sUserManager.exists(userId)) return null;
2633        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2634        // writer
2635        synchronized (mPackages) {
2636            PackageParser.Package p = mPackages.get(packageName);
2637            if (DEBUG_PACKAGE_INFO) Log.v(
2638                    TAG, "getApplicationInfo " + packageName
2639                    + ": " + p);
2640            if (p != null) {
2641                PackageSetting ps = mSettings.mPackages.get(packageName);
2642                if (ps == null) return null;
2643                // Note: isEnabledLP() does not apply here - always return info
2644                return PackageParser.generateApplicationInfo(
2645                        p, flags, ps.readUserState(userId), userId);
2646            }
2647            if ("android".equals(packageName)||"system".equals(packageName)) {
2648                return mAndroidApplication;
2649            }
2650            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2651                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2652            }
2653        }
2654        return null;
2655    }
2656
2657    @Override
2658    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2659            final IPackageDataObserver observer) {
2660        mContext.enforceCallingOrSelfPermission(
2661                android.Manifest.permission.CLEAR_APP_CACHE, null);
2662        // Queue up an async operation since clearing cache may take a little while.
2663        mHandler.post(new Runnable() {
2664            public void run() {
2665                mHandler.removeCallbacks(this);
2666                int retCode = -1;
2667                synchronized (mInstallLock) {
2668                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2669                    if (retCode < 0) {
2670                        Slog.w(TAG, "Couldn't clear application caches");
2671                    }
2672                }
2673                if (observer != null) {
2674                    try {
2675                        observer.onRemoveCompleted(null, (retCode >= 0));
2676                    } catch (RemoteException e) {
2677                        Slog.w(TAG, "RemoveException when invoking call back");
2678                    }
2679                }
2680            }
2681        });
2682    }
2683
2684    @Override
2685    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2686            final IntentSender pi) {
2687        mContext.enforceCallingOrSelfPermission(
2688                android.Manifest.permission.CLEAR_APP_CACHE, null);
2689        // Queue up an async operation since clearing cache may take a little while.
2690        mHandler.post(new Runnable() {
2691            public void run() {
2692                mHandler.removeCallbacks(this);
2693                int retCode = -1;
2694                synchronized (mInstallLock) {
2695                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2696                    if (retCode < 0) {
2697                        Slog.w(TAG, "Couldn't clear application caches");
2698                    }
2699                }
2700                if(pi != null) {
2701                    try {
2702                        // Callback via pending intent
2703                        int code = (retCode >= 0) ? 1 : 0;
2704                        pi.sendIntent(null, code, null,
2705                                null, null);
2706                    } catch (SendIntentException e1) {
2707                        Slog.i(TAG, "Failed to send pending intent");
2708                    }
2709                }
2710            }
2711        });
2712    }
2713
2714    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2715        synchronized (mInstallLock) {
2716            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2717                throw new IOException("Failed to free enough space");
2718            }
2719        }
2720    }
2721
2722    @Override
2723    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2724        if (!sUserManager.exists(userId)) return null;
2725        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2726        synchronized (mPackages) {
2727            PackageParser.Activity a = mActivities.mActivities.get(component);
2728
2729            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2730            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2731                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2732                if (ps == null) return null;
2733                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2734                        userId);
2735            }
2736            if (mResolveComponentName.equals(component)) {
2737                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2738                        new PackageUserState(), userId);
2739            }
2740        }
2741        return null;
2742    }
2743
2744    @Override
2745    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2746            String resolvedType) {
2747        synchronized (mPackages) {
2748            PackageParser.Activity a = mActivities.mActivities.get(component);
2749            if (a == null) {
2750                return false;
2751            }
2752            for (int i=0; i<a.intents.size(); i++) {
2753                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2754                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2755                    return true;
2756                }
2757            }
2758            return false;
2759        }
2760    }
2761
2762    @Override
2763    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2764        if (!sUserManager.exists(userId)) return null;
2765        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2766        synchronized (mPackages) {
2767            PackageParser.Activity a = mReceivers.mActivities.get(component);
2768            if (DEBUG_PACKAGE_INFO) Log.v(
2769                TAG, "getReceiverInfo " + component + ": " + a);
2770            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2771                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2772                if (ps == null) return null;
2773                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2774                        userId);
2775            }
2776        }
2777        return null;
2778    }
2779
2780    @Override
2781    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2782        if (!sUserManager.exists(userId)) return null;
2783        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2784        synchronized (mPackages) {
2785            PackageParser.Service s = mServices.mServices.get(component);
2786            if (DEBUG_PACKAGE_INFO) Log.v(
2787                TAG, "getServiceInfo " + component + ": " + s);
2788            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2789                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2790                if (ps == null) return null;
2791                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2792                        userId);
2793            }
2794        }
2795        return null;
2796    }
2797
2798    @Override
2799    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2800        if (!sUserManager.exists(userId)) return null;
2801        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2802        synchronized (mPackages) {
2803            PackageParser.Provider p = mProviders.mProviders.get(component);
2804            if (DEBUG_PACKAGE_INFO) Log.v(
2805                TAG, "getProviderInfo " + component + ": " + p);
2806            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2807                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2808                if (ps == null) return null;
2809                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2810                        userId);
2811            }
2812        }
2813        return null;
2814    }
2815
2816    @Override
2817    public String[] getSystemSharedLibraryNames() {
2818        Set<String> libSet;
2819        synchronized (mPackages) {
2820            libSet = mSharedLibraries.keySet();
2821            int size = libSet.size();
2822            if (size > 0) {
2823                String[] libs = new String[size];
2824                libSet.toArray(libs);
2825                return libs;
2826            }
2827        }
2828        return null;
2829    }
2830
2831    /**
2832     * @hide
2833     */
2834    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2835        synchronized (mPackages) {
2836            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2837            if (lib != null && lib.apk != null) {
2838                return mPackages.get(lib.apk);
2839            }
2840        }
2841        return null;
2842    }
2843
2844    @Override
2845    public FeatureInfo[] getSystemAvailableFeatures() {
2846        Collection<FeatureInfo> featSet;
2847        synchronized (mPackages) {
2848            featSet = mAvailableFeatures.values();
2849            int size = featSet.size();
2850            if (size > 0) {
2851                FeatureInfo[] features = new FeatureInfo[size+1];
2852                featSet.toArray(features);
2853                FeatureInfo fi = new FeatureInfo();
2854                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2855                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2856                features[size] = fi;
2857                return features;
2858            }
2859        }
2860        return null;
2861    }
2862
2863    @Override
2864    public boolean hasSystemFeature(String name) {
2865        synchronized (mPackages) {
2866            return mAvailableFeatures.containsKey(name);
2867        }
2868    }
2869
2870    private void checkValidCaller(int uid, int userId) {
2871        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2872            return;
2873
2874        throw new SecurityException("Caller uid=" + uid
2875                + " is not privileged to communicate with user=" + userId);
2876    }
2877
2878    @Override
2879    public int checkPermission(String permName, String pkgName, int userId) {
2880        if (!sUserManager.exists(userId)) {
2881            return PackageManager.PERMISSION_DENIED;
2882        }
2883
2884        synchronized (mPackages) {
2885            final PackageParser.Package p = mPackages.get(pkgName);
2886            if (p != null && p.mExtras != null) {
2887                final PackageSetting ps = (PackageSetting) p.mExtras;
2888                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2889                    return PackageManager.PERMISSION_GRANTED;
2890                }
2891            }
2892        }
2893
2894        return PackageManager.PERMISSION_DENIED;
2895    }
2896
2897    @Override
2898    public int checkUidPermission(String permName, int uid) {
2899        final int userId = UserHandle.getUserId(uid);
2900
2901        if (!sUserManager.exists(userId)) {
2902            return PackageManager.PERMISSION_DENIED;
2903        }
2904
2905        synchronized (mPackages) {
2906            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2907            if (obj != null) {
2908                final SettingBase ps = (SettingBase) obj;
2909                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2910                    return PackageManager.PERMISSION_GRANTED;
2911                }
2912            } else {
2913                ArraySet<String> perms = mSystemPermissions.get(uid);
2914                if (perms != null && perms.contains(permName)) {
2915                    return PackageManager.PERMISSION_GRANTED;
2916                }
2917            }
2918        }
2919
2920        return PackageManager.PERMISSION_DENIED;
2921    }
2922
2923    /**
2924     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2925     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2926     * @param checkShell TODO(yamasani):
2927     * @param message the message to log on security exception
2928     */
2929    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2930            boolean checkShell, String message) {
2931        if (userId < 0) {
2932            throw new IllegalArgumentException("Invalid userId " + userId);
2933        }
2934        if (checkShell) {
2935            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2936        }
2937        if (userId == UserHandle.getUserId(callingUid)) return;
2938        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2939            if (requireFullPermission) {
2940                mContext.enforceCallingOrSelfPermission(
2941                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2942            } else {
2943                try {
2944                    mContext.enforceCallingOrSelfPermission(
2945                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2946                } catch (SecurityException se) {
2947                    mContext.enforceCallingOrSelfPermission(
2948                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2949                }
2950            }
2951        }
2952    }
2953
2954    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2955        if (callingUid == Process.SHELL_UID) {
2956            if (userHandle >= 0
2957                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2958                throw new SecurityException("Shell does not have permission to access user "
2959                        + userHandle);
2960            } else if (userHandle < 0) {
2961                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2962                        + Debug.getCallers(3));
2963            }
2964        }
2965    }
2966
2967    private BasePermission findPermissionTreeLP(String permName) {
2968        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2969            if (permName.startsWith(bp.name) &&
2970                    permName.length() > bp.name.length() &&
2971                    permName.charAt(bp.name.length()) == '.') {
2972                return bp;
2973            }
2974        }
2975        return null;
2976    }
2977
2978    private BasePermission checkPermissionTreeLP(String permName) {
2979        if (permName != null) {
2980            BasePermission bp = findPermissionTreeLP(permName);
2981            if (bp != null) {
2982                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2983                    return bp;
2984                }
2985                throw new SecurityException("Calling uid "
2986                        + Binder.getCallingUid()
2987                        + " is not allowed to add to permission tree "
2988                        + bp.name + " owned by uid " + bp.uid);
2989            }
2990        }
2991        throw new SecurityException("No permission tree found for " + permName);
2992    }
2993
2994    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2995        if (s1 == null) {
2996            return s2 == null;
2997        }
2998        if (s2 == null) {
2999            return false;
3000        }
3001        if (s1.getClass() != s2.getClass()) {
3002            return false;
3003        }
3004        return s1.equals(s2);
3005    }
3006
3007    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3008        if (pi1.icon != pi2.icon) return false;
3009        if (pi1.logo != pi2.logo) return false;
3010        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3011        if (!compareStrings(pi1.name, pi2.name)) return false;
3012        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3013        // We'll take care of setting this one.
3014        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3015        // These are not currently stored in settings.
3016        //if (!compareStrings(pi1.group, pi2.group)) return false;
3017        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3018        //if (pi1.labelRes != pi2.labelRes) return false;
3019        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3020        return true;
3021    }
3022
3023    int permissionInfoFootprint(PermissionInfo info) {
3024        int size = info.name.length();
3025        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3026        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3027        return size;
3028    }
3029
3030    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3031        int size = 0;
3032        for (BasePermission perm : mSettings.mPermissions.values()) {
3033            if (perm.uid == tree.uid) {
3034                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3035            }
3036        }
3037        return size;
3038    }
3039
3040    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3041        // We calculate the max size of permissions defined by this uid and throw
3042        // if that plus the size of 'info' would exceed our stated maximum.
3043        if (tree.uid != Process.SYSTEM_UID) {
3044            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3045            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3046                throw new SecurityException("Permission tree size cap exceeded");
3047            }
3048        }
3049    }
3050
3051    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3052        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3053            throw new SecurityException("Label must be specified in permission");
3054        }
3055        BasePermission tree = checkPermissionTreeLP(info.name);
3056        BasePermission bp = mSettings.mPermissions.get(info.name);
3057        boolean added = bp == null;
3058        boolean changed = true;
3059        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3060        if (added) {
3061            enforcePermissionCapLocked(info, tree);
3062            bp = new BasePermission(info.name, tree.sourcePackage,
3063                    BasePermission.TYPE_DYNAMIC);
3064        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3065            throw new SecurityException(
3066                    "Not allowed to modify non-dynamic permission "
3067                    + info.name);
3068        } else {
3069            if (bp.protectionLevel == fixedLevel
3070                    && bp.perm.owner.equals(tree.perm.owner)
3071                    && bp.uid == tree.uid
3072                    && comparePermissionInfos(bp.perm.info, info)) {
3073                changed = false;
3074            }
3075        }
3076        bp.protectionLevel = fixedLevel;
3077        info = new PermissionInfo(info);
3078        info.protectionLevel = fixedLevel;
3079        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3080        bp.perm.info.packageName = tree.perm.info.packageName;
3081        bp.uid = tree.uid;
3082        if (added) {
3083            mSettings.mPermissions.put(info.name, bp);
3084        }
3085        if (changed) {
3086            if (!async) {
3087                mSettings.writeLPr();
3088            } else {
3089                scheduleWriteSettingsLocked();
3090            }
3091        }
3092        return added;
3093    }
3094
3095    @Override
3096    public boolean addPermission(PermissionInfo info) {
3097        synchronized (mPackages) {
3098            return addPermissionLocked(info, false);
3099        }
3100    }
3101
3102    @Override
3103    public boolean addPermissionAsync(PermissionInfo info) {
3104        synchronized (mPackages) {
3105            return addPermissionLocked(info, true);
3106        }
3107    }
3108
3109    @Override
3110    public void removePermission(String name) {
3111        synchronized (mPackages) {
3112            checkPermissionTreeLP(name);
3113            BasePermission bp = mSettings.mPermissions.get(name);
3114            if (bp != null) {
3115                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3116                    throw new SecurityException(
3117                            "Not allowed to modify non-dynamic permission "
3118                            + name);
3119                }
3120                mSettings.mPermissions.remove(name);
3121                mSettings.writeLPr();
3122            }
3123        }
3124    }
3125
3126    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3127            BasePermission bp) {
3128        int index = pkg.requestedPermissions.indexOf(bp.name);
3129        if (index == -1) {
3130            throw new SecurityException("Package " + pkg.packageName
3131                    + " has not requested permission " + bp.name);
3132        }
3133        if (!bp.isRuntime()) {
3134            throw new SecurityException("Permission " + bp.name
3135                    + " is not a changeable permission type");
3136        }
3137    }
3138
3139    @Override
3140    public boolean grantPermission(String packageName, String name, int userId) {
3141        if (!RUNTIME_PERMISSIONS_ENABLED) {
3142            return false;
3143        }
3144
3145        if (!sUserManager.exists(userId)) {
3146            return false;
3147        }
3148
3149        mContext.enforceCallingOrSelfPermission(
3150                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3151                "grantPermission");
3152
3153        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3154                "grantPermission");
3155
3156        boolean gidsChanged = false;
3157        final SettingBase sb;
3158
3159        synchronized (mPackages) {
3160            final PackageParser.Package pkg = mPackages.get(packageName);
3161            if (pkg == null) {
3162                throw new IllegalArgumentException("Unknown package: " + packageName);
3163            }
3164
3165            final BasePermission bp = mSettings.mPermissions.get(name);
3166            if (bp == null) {
3167                throw new IllegalArgumentException("Unknown permission: " + name);
3168            }
3169
3170            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3171
3172            sb = (SettingBase) pkg.mExtras;
3173            if (sb == null) {
3174                throw new IllegalArgumentException("Unknown package: " + packageName);
3175            }
3176
3177            final PermissionsState permissionsState = sb.getPermissionsState();
3178
3179            final int result = permissionsState.grantRuntimePermission(bp, userId);
3180            switch (result) {
3181                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3182                    return false;
3183                }
3184
3185                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3186                    gidsChanged = true;
3187                } break;
3188            }
3189
3190            // Not critical if that is lost - app has to request again.
3191            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3192        }
3193
3194        if (gidsChanged) {
3195            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3196        }
3197
3198        return true;
3199    }
3200
3201    @Override
3202    public boolean revokePermission(String packageName, String name, int userId) {
3203        if (!RUNTIME_PERMISSIONS_ENABLED) {
3204            return false;
3205        }
3206
3207        if (!sUserManager.exists(userId)) {
3208            return false;
3209        }
3210
3211        mContext.enforceCallingOrSelfPermission(
3212                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3213                "revokePermission");
3214
3215        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3216                "revokePermission");
3217
3218        final SettingBase sb;
3219
3220        synchronized (mPackages) {
3221            final PackageParser.Package pkg = mPackages.get(packageName);
3222            if (pkg == null) {
3223                throw new IllegalArgumentException("Unknown package: " + packageName);
3224            }
3225
3226            final BasePermission bp = mSettings.mPermissions.get(name);
3227            if (bp == null) {
3228                throw new IllegalArgumentException("Unknown permission: " + name);
3229            }
3230
3231            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3232
3233            sb = (SettingBase) pkg.mExtras;
3234            if (sb == null) {
3235                throw new IllegalArgumentException("Unknown package: " + packageName);
3236            }
3237
3238            final PermissionsState permissionsState = sb.getPermissionsState();
3239
3240            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3241                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3242                return false;
3243            }
3244
3245            // Critical, after this call all should never have the permission.
3246            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3247        }
3248
3249        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3250
3251        return true;
3252    }
3253
3254    @Override
3255    public boolean isProtectedBroadcast(String actionName) {
3256        synchronized (mPackages) {
3257            return mProtectedBroadcasts.contains(actionName);
3258        }
3259    }
3260
3261    @Override
3262    public int checkSignatures(String pkg1, String pkg2) {
3263        synchronized (mPackages) {
3264            final PackageParser.Package p1 = mPackages.get(pkg1);
3265            final PackageParser.Package p2 = mPackages.get(pkg2);
3266            if (p1 == null || p1.mExtras == null
3267                    || p2 == null || p2.mExtras == null) {
3268                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3269            }
3270            return compareSignatures(p1.mSignatures, p2.mSignatures);
3271        }
3272    }
3273
3274    @Override
3275    public int checkUidSignatures(int uid1, int uid2) {
3276        // Map to base uids.
3277        uid1 = UserHandle.getAppId(uid1);
3278        uid2 = UserHandle.getAppId(uid2);
3279        // reader
3280        synchronized (mPackages) {
3281            Signature[] s1;
3282            Signature[] s2;
3283            Object obj = mSettings.getUserIdLPr(uid1);
3284            if (obj != null) {
3285                if (obj instanceof SharedUserSetting) {
3286                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3287                } else if (obj instanceof PackageSetting) {
3288                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3289                } else {
3290                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3291                }
3292            } else {
3293                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3294            }
3295            obj = mSettings.getUserIdLPr(uid2);
3296            if (obj != null) {
3297                if (obj instanceof SharedUserSetting) {
3298                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3299                } else if (obj instanceof PackageSetting) {
3300                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3301                } else {
3302                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3303                }
3304            } else {
3305                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3306            }
3307            return compareSignatures(s1, s2);
3308        }
3309    }
3310
3311    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3312        final long identity = Binder.clearCallingIdentity();
3313        try {
3314            if (sb instanceof SharedUserSetting) {
3315                SharedUserSetting sus = (SharedUserSetting) sb;
3316                final int packageCount = sus.packages.size();
3317                for (int i = 0; i < packageCount; i++) {
3318                    PackageSetting susPs = sus.packages.valueAt(i);
3319                    if (userId == UserHandle.USER_ALL) {
3320                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3321                    } else {
3322                        final int uid = UserHandle.getUid(userId, susPs.appId);
3323                        killUid(uid, reason);
3324                    }
3325                }
3326            } else if (sb instanceof PackageSetting) {
3327                PackageSetting ps = (PackageSetting) sb;
3328                if (userId == UserHandle.USER_ALL) {
3329                    killApplication(ps.pkg.packageName, ps.appId, reason);
3330                } else {
3331                    final int uid = UserHandle.getUid(userId, ps.appId);
3332                    killUid(uid, reason);
3333                }
3334            }
3335        } finally {
3336            Binder.restoreCallingIdentity(identity);
3337        }
3338    }
3339
3340    private static void killUid(int uid, String reason) {
3341        IActivityManager am = ActivityManagerNative.getDefault();
3342        if (am != null) {
3343            try {
3344                am.killUid(uid, reason);
3345            } catch (RemoteException e) {
3346                /* ignore - same process */
3347            }
3348        }
3349    }
3350
3351    /**
3352     * Compares two sets of signatures. Returns:
3353     * <br />
3354     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3355     * <br />
3356     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3357     * <br />
3358     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3359     * <br />
3360     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3361     * <br />
3362     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3363     */
3364    static int compareSignatures(Signature[] s1, Signature[] s2) {
3365        if (s1 == null) {
3366            return s2 == null
3367                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3368                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3369        }
3370
3371        if (s2 == null) {
3372            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3373        }
3374
3375        if (s1.length != s2.length) {
3376            return PackageManager.SIGNATURE_NO_MATCH;
3377        }
3378
3379        // Since both signature sets are of size 1, we can compare without HashSets.
3380        if (s1.length == 1) {
3381            return s1[0].equals(s2[0]) ?
3382                    PackageManager.SIGNATURE_MATCH :
3383                    PackageManager.SIGNATURE_NO_MATCH;
3384        }
3385
3386        ArraySet<Signature> set1 = new ArraySet<Signature>();
3387        for (Signature sig : s1) {
3388            set1.add(sig);
3389        }
3390        ArraySet<Signature> set2 = new ArraySet<Signature>();
3391        for (Signature sig : s2) {
3392            set2.add(sig);
3393        }
3394        // Make sure s2 contains all signatures in s1.
3395        if (set1.equals(set2)) {
3396            return PackageManager.SIGNATURE_MATCH;
3397        }
3398        return PackageManager.SIGNATURE_NO_MATCH;
3399    }
3400
3401    /**
3402     * If the database version for this type of package (internal storage or
3403     * external storage) is less than the version where package signatures
3404     * were updated, return true.
3405     */
3406    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3407        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3408                DatabaseVersion.SIGNATURE_END_ENTITY))
3409                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3410                        DatabaseVersion.SIGNATURE_END_ENTITY));
3411    }
3412
3413    /**
3414     * Used for backward compatibility to make sure any packages with
3415     * certificate chains get upgraded to the new style. {@code existingSigs}
3416     * will be in the old format (since they were stored on disk from before the
3417     * system upgrade) and {@code scannedSigs} will be in the newer format.
3418     */
3419    private int compareSignaturesCompat(PackageSignatures existingSigs,
3420            PackageParser.Package scannedPkg) {
3421        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3422            return PackageManager.SIGNATURE_NO_MATCH;
3423        }
3424
3425        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3426        for (Signature sig : existingSigs.mSignatures) {
3427            existingSet.add(sig);
3428        }
3429        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3430        for (Signature sig : scannedPkg.mSignatures) {
3431            try {
3432                Signature[] chainSignatures = sig.getChainSignatures();
3433                for (Signature chainSig : chainSignatures) {
3434                    scannedCompatSet.add(chainSig);
3435                }
3436            } catch (CertificateEncodingException e) {
3437                scannedCompatSet.add(sig);
3438            }
3439        }
3440        /*
3441         * Make sure the expanded scanned set contains all signatures in the
3442         * existing one.
3443         */
3444        if (scannedCompatSet.equals(existingSet)) {
3445            // Migrate the old signatures to the new scheme.
3446            existingSigs.assignSignatures(scannedPkg.mSignatures);
3447            // The new KeySets will be re-added later in the scanning process.
3448            synchronized (mPackages) {
3449                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3450            }
3451            return PackageManager.SIGNATURE_MATCH;
3452        }
3453        return PackageManager.SIGNATURE_NO_MATCH;
3454    }
3455
3456    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3457        if (isExternal(scannedPkg)) {
3458            return mSettings.isExternalDatabaseVersionOlderThan(
3459                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3460        } else {
3461            return mSettings.isInternalDatabaseVersionOlderThan(
3462                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3463        }
3464    }
3465
3466    private int compareSignaturesRecover(PackageSignatures existingSigs,
3467            PackageParser.Package scannedPkg) {
3468        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3469            return PackageManager.SIGNATURE_NO_MATCH;
3470        }
3471
3472        String msg = null;
3473        try {
3474            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3475                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3476                        + scannedPkg.packageName);
3477                return PackageManager.SIGNATURE_MATCH;
3478            }
3479        } catch (CertificateException e) {
3480            msg = e.getMessage();
3481        }
3482
3483        logCriticalInfo(Log.INFO,
3484                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3485        return PackageManager.SIGNATURE_NO_MATCH;
3486    }
3487
3488    @Override
3489    public String[] getPackagesForUid(int uid) {
3490        uid = UserHandle.getAppId(uid);
3491        // reader
3492        synchronized (mPackages) {
3493            Object obj = mSettings.getUserIdLPr(uid);
3494            if (obj instanceof SharedUserSetting) {
3495                final SharedUserSetting sus = (SharedUserSetting) obj;
3496                final int N = sus.packages.size();
3497                final String[] res = new String[N];
3498                final Iterator<PackageSetting> it = sus.packages.iterator();
3499                int i = 0;
3500                while (it.hasNext()) {
3501                    res[i++] = it.next().name;
3502                }
3503                return res;
3504            } else if (obj instanceof PackageSetting) {
3505                final PackageSetting ps = (PackageSetting) obj;
3506                return new String[] { ps.name };
3507            }
3508        }
3509        return null;
3510    }
3511
3512    @Override
3513    public String getNameForUid(int uid) {
3514        // reader
3515        synchronized (mPackages) {
3516            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3517            if (obj instanceof SharedUserSetting) {
3518                final SharedUserSetting sus = (SharedUserSetting) obj;
3519                return sus.name + ":" + sus.userId;
3520            } else if (obj instanceof PackageSetting) {
3521                final PackageSetting ps = (PackageSetting) obj;
3522                return ps.name;
3523            }
3524        }
3525        return null;
3526    }
3527
3528    @Override
3529    public int getUidForSharedUser(String sharedUserName) {
3530        if(sharedUserName == null) {
3531            return -1;
3532        }
3533        // reader
3534        synchronized (mPackages) {
3535            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3536            if (suid == null) {
3537                return -1;
3538            }
3539            return suid.userId;
3540        }
3541    }
3542
3543    @Override
3544    public int getFlagsForUid(int uid) {
3545        synchronized (mPackages) {
3546            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3547            if (obj instanceof SharedUserSetting) {
3548                final SharedUserSetting sus = (SharedUserSetting) obj;
3549                return sus.pkgFlags;
3550            } else if (obj instanceof PackageSetting) {
3551                final PackageSetting ps = (PackageSetting) obj;
3552                return ps.pkgFlags;
3553            }
3554        }
3555        return 0;
3556    }
3557
3558    @Override
3559    public int getPrivateFlagsForUid(int uid) {
3560        synchronized (mPackages) {
3561            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3562            if (obj instanceof SharedUserSetting) {
3563                final SharedUserSetting sus = (SharedUserSetting) obj;
3564                return sus.pkgPrivateFlags;
3565            } else if (obj instanceof PackageSetting) {
3566                final PackageSetting ps = (PackageSetting) obj;
3567                return ps.pkgPrivateFlags;
3568            }
3569        }
3570        return 0;
3571    }
3572
3573    @Override
3574    public boolean isUidPrivileged(int uid) {
3575        uid = UserHandle.getAppId(uid);
3576        // reader
3577        synchronized (mPackages) {
3578            Object obj = mSettings.getUserIdLPr(uid);
3579            if (obj instanceof SharedUserSetting) {
3580                final SharedUserSetting sus = (SharedUserSetting) obj;
3581                final Iterator<PackageSetting> it = sus.packages.iterator();
3582                while (it.hasNext()) {
3583                    if (it.next().isPrivileged()) {
3584                        return true;
3585                    }
3586                }
3587            } else if (obj instanceof PackageSetting) {
3588                final PackageSetting ps = (PackageSetting) obj;
3589                return ps.isPrivileged();
3590            }
3591        }
3592        return false;
3593    }
3594
3595    @Override
3596    public String[] getAppOpPermissionPackages(String permissionName) {
3597        synchronized (mPackages) {
3598            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3599            if (pkgs == null) {
3600                return null;
3601            }
3602            return pkgs.toArray(new String[pkgs.size()]);
3603        }
3604    }
3605
3606    @Override
3607    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3608            int flags, int userId) {
3609        if (!sUserManager.exists(userId)) return null;
3610        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3611        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3612        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3613    }
3614
3615    @Override
3616    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3617            IntentFilter filter, int match, ComponentName activity) {
3618        final int userId = UserHandle.getCallingUserId();
3619        if (DEBUG_PREFERRED) {
3620            Log.v(TAG, "setLastChosenActivity intent=" + intent
3621                + " resolvedType=" + resolvedType
3622                + " flags=" + flags
3623                + " filter=" + filter
3624                + " match=" + match
3625                + " activity=" + activity);
3626            filter.dump(new PrintStreamPrinter(System.out), "    ");
3627        }
3628        intent.setComponent(null);
3629        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3630        // Find any earlier preferred or last chosen entries and nuke them
3631        findPreferredActivity(intent, resolvedType,
3632                flags, query, 0, false, true, false, userId);
3633        // Add the new activity as the last chosen for this filter
3634        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3635                "Setting last chosen");
3636    }
3637
3638    @Override
3639    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3640        final int userId = UserHandle.getCallingUserId();
3641        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3642        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3643        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3644                false, false, false, userId);
3645    }
3646
3647    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3648            int flags, List<ResolveInfo> query, int userId) {
3649        if (query != null) {
3650            final int N = query.size();
3651            if (N == 1) {
3652                return query.get(0);
3653            } else if (N > 1) {
3654                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3655                // If there is more than one activity with the same priority,
3656                // then let the user decide between them.
3657                ResolveInfo r0 = query.get(0);
3658                ResolveInfo r1 = query.get(1);
3659                if (DEBUG_INTENT_MATCHING || debug) {
3660                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3661                            + r1.activityInfo.name + "=" + r1.priority);
3662                }
3663                // If the first activity has a higher priority, or a different
3664                // default, then it is always desireable to pick it.
3665                if (r0.priority != r1.priority
3666                        || r0.preferredOrder != r1.preferredOrder
3667                        || r0.isDefault != r1.isDefault) {
3668                    return query.get(0);
3669                }
3670                // If we have saved a preference for a preferred activity for
3671                // this Intent, use that.
3672                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3673                        flags, query, r0.priority, true, false, debug, userId);
3674                if (ri != null) {
3675                    return ri;
3676                }
3677                if (userId != 0) {
3678                    ri = new ResolveInfo(mResolveInfo);
3679                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3680                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3681                            ri.activityInfo.applicationInfo);
3682                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3683                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3684                    return ri;
3685                }
3686                return mResolveInfo;
3687            }
3688        }
3689        return null;
3690    }
3691
3692    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3693            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3694        final int N = query.size();
3695        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3696                .get(userId);
3697        // Get the list of persistent preferred activities that handle the intent
3698        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3699        List<PersistentPreferredActivity> pprefs = ppir != null
3700                ? ppir.queryIntent(intent, resolvedType,
3701                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3702                : null;
3703        if (pprefs != null && pprefs.size() > 0) {
3704            final int M = pprefs.size();
3705            for (int i=0; i<M; i++) {
3706                final PersistentPreferredActivity ppa = pprefs.get(i);
3707                if (DEBUG_PREFERRED || debug) {
3708                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3709                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3710                            + "\n  component=" + ppa.mComponent);
3711                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3712                }
3713                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3714                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3715                if (DEBUG_PREFERRED || debug) {
3716                    Slog.v(TAG, "Found persistent preferred activity:");
3717                    if (ai != null) {
3718                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3719                    } else {
3720                        Slog.v(TAG, "  null");
3721                    }
3722                }
3723                if (ai == null) {
3724                    // This previously registered persistent preferred activity
3725                    // component is no longer known. Ignore it and do NOT remove it.
3726                    continue;
3727                }
3728                for (int j=0; j<N; j++) {
3729                    final ResolveInfo ri = query.get(j);
3730                    if (!ri.activityInfo.applicationInfo.packageName
3731                            .equals(ai.applicationInfo.packageName)) {
3732                        continue;
3733                    }
3734                    if (!ri.activityInfo.name.equals(ai.name)) {
3735                        continue;
3736                    }
3737                    //  Found a persistent preference that can handle the intent.
3738                    if (DEBUG_PREFERRED || debug) {
3739                        Slog.v(TAG, "Returning persistent preferred activity: " +
3740                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3741                    }
3742                    return ri;
3743                }
3744            }
3745        }
3746        return null;
3747    }
3748
3749    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3750            List<ResolveInfo> query, int priority, boolean always,
3751            boolean removeMatches, boolean debug, int userId) {
3752        if (!sUserManager.exists(userId)) return null;
3753        // writer
3754        synchronized (mPackages) {
3755            if (intent.getSelector() != null) {
3756                intent = intent.getSelector();
3757            }
3758            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3759
3760            // Try to find a matching persistent preferred activity.
3761            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3762                    debug, userId);
3763
3764            // If a persistent preferred activity matched, use it.
3765            if (pri != null) {
3766                return pri;
3767            }
3768
3769            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3770            // Get the list of preferred activities that handle the intent
3771            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3772            List<PreferredActivity> prefs = pir != null
3773                    ? pir.queryIntent(intent, resolvedType,
3774                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3775                    : null;
3776            if (prefs != null && prefs.size() > 0) {
3777                boolean changed = false;
3778                try {
3779                    // First figure out how good the original match set is.
3780                    // We will only allow preferred activities that came
3781                    // from the same match quality.
3782                    int match = 0;
3783
3784                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3785
3786                    final int N = query.size();
3787                    for (int j=0; j<N; j++) {
3788                        final ResolveInfo ri = query.get(j);
3789                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3790                                + ": 0x" + Integer.toHexString(match));
3791                        if (ri.match > match) {
3792                            match = ri.match;
3793                        }
3794                    }
3795
3796                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3797                            + Integer.toHexString(match));
3798
3799                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3800                    final int M = prefs.size();
3801                    for (int i=0; i<M; i++) {
3802                        final PreferredActivity pa = prefs.get(i);
3803                        if (DEBUG_PREFERRED || debug) {
3804                            Slog.v(TAG, "Checking PreferredActivity ds="
3805                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3806                                    + "\n  component=" + pa.mPref.mComponent);
3807                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3808                        }
3809                        if (pa.mPref.mMatch != match) {
3810                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3811                                    + Integer.toHexString(pa.mPref.mMatch));
3812                            continue;
3813                        }
3814                        // If it's not an "always" type preferred activity and that's what we're
3815                        // looking for, skip it.
3816                        if (always && !pa.mPref.mAlways) {
3817                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3818                            continue;
3819                        }
3820                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3821                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3822                        if (DEBUG_PREFERRED || debug) {
3823                            Slog.v(TAG, "Found preferred activity:");
3824                            if (ai != null) {
3825                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3826                            } else {
3827                                Slog.v(TAG, "  null");
3828                            }
3829                        }
3830                        if (ai == null) {
3831                            // This previously registered preferred activity
3832                            // component is no longer known.  Most likely an update
3833                            // to the app was installed and in the new version this
3834                            // component no longer exists.  Clean it up by removing
3835                            // it from the preferred activities list, and skip it.
3836                            Slog.w(TAG, "Removing dangling preferred activity: "
3837                                    + pa.mPref.mComponent);
3838                            pir.removeFilter(pa);
3839                            changed = true;
3840                            continue;
3841                        }
3842                        for (int j=0; j<N; j++) {
3843                            final ResolveInfo ri = query.get(j);
3844                            if (!ri.activityInfo.applicationInfo.packageName
3845                                    .equals(ai.applicationInfo.packageName)) {
3846                                continue;
3847                            }
3848                            if (!ri.activityInfo.name.equals(ai.name)) {
3849                                continue;
3850                            }
3851
3852                            if (removeMatches) {
3853                                pir.removeFilter(pa);
3854                                changed = true;
3855                                if (DEBUG_PREFERRED) {
3856                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3857                                }
3858                                break;
3859                            }
3860
3861                            // Okay we found a previously set preferred or last chosen app.
3862                            // If the result set is different from when this
3863                            // was created, we need to clear it and re-ask the
3864                            // user their preference, if we're looking for an "always" type entry.
3865                            if (always && !pa.mPref.sameSet(query)) {
3866                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3867                                        + intent + " type " + resolvedType);
3868                                if (DEBUG_PREFERRED) {
3869                                    Slog.v(TAG, "Removing preferred activity since set changed "
3870                                            + pa.mPref.mComponent);
3871                                }
3872                                pir.removeFilter(pa);
3873                                // Re-add the filter as a "last chosen" entry (!always)
3874                                PreferredActivity lastChosen = new PreferredActivity(
3875                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3876                                pir.addFilter(lastChosen);
3877                                changed = true;
3878                                return null;
3879                            }
3880
3881                            // Yay! Either the set matched or we're looking for the last chosen
3882                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3883                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3884                            return ri;
3885                        }
3886                    }
3887                } finally {
3888                    if (changed) {
3889                        if (DEBUG_PREFERRED) {
3890                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3891                        }
3892                        scheduleWritePackageRestrictionsLocked(userId);
3893                    }
3894                }
3895            }
3896        }
3897        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3898        return null;
3899    }
3900
3901    /*
3902     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3903     */
3904    @Override
3905    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3906            int targetUserId) {
3907        mContext.enforceCallingOrSelfPermission(
3908                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3909        List<CrossProfileIntentFilter> matches =
3910                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3911        if (matches != null) {
3912            int size = matches.size();
3913            for (int i = 0; i < size; i++) {
3914                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3915            }
3916        }
3917        return false;
3918    }
3919
3920    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3921            String resolvedType, int userId) {
3922        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3923        if (resolver != null) {
3924            return resolver.queryIntent(intent, resolvedType, false, userId);
3925        }
3926        return null;
3927    }
3928
3929    @Override
3930    public List<ResolveInfo> queryIntentActivities(Intent intent,
3931            String resolvedType, int flags, int userId) {
3932        if (!sUserManager.exists(userId)) return Collections.emptyList();
3933        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3934        ComponentName comp = intent.getComponent();
3935        if (comp == null) {
3936            if (intent.getSelector() != null) {
3937                intent = intent.getSelector();
3938                comp = intent.getComponent();
3939            }
3940        }
3941
3942        if (comp != null) {
3943            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3944            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3945            if (ai != null) {
3946                final ResolveInfo ri = new ResolveInfo();
3947                ri.activityInfo = ai;
3948                list.add(ri);
3949            }
3950            return list;
3951        }
3952
3953        // reader
3954        synchronized (mPackages) {
3955            final String pkgName = intent.getPackage();
3956            if (pkgName == null) {
3957                List<CrossProfileIntentFilter> matchingFilters =
3958                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3959                // Check for results that need to skip the current profile.
3960                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3961                        resolvedType, flags, userId);
3962                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
3963                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3964                    result.add(resolveInfo);
3965                    return filterIfNotPrimaryUser(result, userId);
3966                }
3967
3968                // Check for results in the current profile.
3969                List<ResolveInfo> result = mActivities.queryIntent(
3970                        intent, resolvedType, flags, userId);
3971
3972                // Check for cross profile results.
3973                resolveInfo = queryCrossProfileIntents(
3974                        matchingFilters, intent, resolvedType, flags, userId);
3975                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
3976                    result.add(resolveInfo);
3977                    Collections.sort(result, mResolvePrioritySorter);
3978                }
3979                result = filterIfNotPrimaryUser(result, userId);
3980                if (result.size() > 1 && hasWebURI(intent)) {
3981                    return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result);
3982                }
3983                return result;
3984            }
3985            final PackageParser.Package pkg = mPackages.get(pkgName);
3986            if (pkg != null) {
3987                return filterIfNotPrimaryUser(
3988                        mActivities.queryIntentForPackage(
3989                                intent, resolvedType, flags, pkg.activities, userId),
3990                        userId);
3991            }
3992            return new ArrayList<ResolveInfo>();
3993        }
3994    }
3995
3996    private boolean isUserEnabled(int userId) {
3997        long callingId = Binder.clearCallingIdentity();
3998        try {
3999            UserInfo userInfo = sUserManager.getUserInfo(userId);
4000            return userInfo != null && userInfo.isEnabled();
4001        } finally {
4002            Binder.restoreCallingIdentity(callingId);
4003        }
4004    }
4005
4006    /**
4007     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4008     *
4009     * @return filtered list
4010     */
4011    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4012        if (userId == UserHandle.USER_OWNER) {
4013            return resolveInfos;
4014        }
4015        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4016            ResolveInfo info = resolveInfos.get(i);
4017            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4018                resolveInfos.remove(i);
4019            }
4020        }
4021        return resolveInfos;
4022    }
4023
4024    private static boolean hasWebURI(Intent intent) {
4025        if (intent.getData() == null) {
4026            return false;
4027        }
4028        final String scheme = intent.getScheme();
4029        if (TextUtils.isEmpty(scheme)) {
4030            return false;
4031        }
4032        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4033    }
4034
4035    private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr(
4036            int flags, List<ResolveInfo> candidates) {
4037        if (DEBUG_PREFERRED) {
4038            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4039                    candidates.size());
4040        }
4041
4042        final int userId = UserHandle.getCallingUserId();
4043        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4044        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4045        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4046        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4047
4048        synchronized (mPackages) {
4049            final int count = candidates.size();
4050            // First, try to use the domain prefered App
4051            for (int n=0; n<count; n++) {
4052                ResolveInfo info = candidates.get(n);
4053                String packageName = info.activityInfo.packageName;
4054                PackageSetting ps = mSettings.mPackages.get(packageName);
4055                if (ps != null) {
4056                    // Add to the special match all list (Browser use case)
4057                    if (info.handleAllWebDataURI) {
4058                        matchAllList.add(info);
4059                        continue;
4060                    }
4061                    // Try to get the status from User settings first
4062                    int status = getDomainVerificationStatusLPr(ps, userId);
4063                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4064                        result.add(info);
4065                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4066                        neverList.add(info);
4067                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4068                        undefinedList.add(info);
4069                    }
4070                }
4071            }
4072            // If there is nothing selected, add all candidates and remove the ones that the User
4073            // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and
4074            // also remove any Browser Apps ones.
4075            // If there is still none after this pass, add all undefined one and Browser Apps and
4076            // let the User decide with the Disambiguation dialog if there are several ones.
4077            if (result.size() == 0) {
4078                result.addAll(candidates);
4079            }
4080            result.removeAll(neverList);
4081            result.removeAll(matchAllList);
4082            if (result.size() == 0) {
4083                result.addAll(undefinedList);
4084                if ((flags & MATCH_ALL) != 0) {
4085                    result.addAll(matchAllList);
4086                } else {
4087                    // Try to add the Default Browser if we can
4088                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4089                            UserHandle.myUserId());
4090                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4091                        boolean defaultBrowserFound = false;
4092                        final int browserCount = matchAllList.size();
4093                        for (int n=0; n<browserCount; n++) {
4094                            ResolveInfo browser = matchAllList.get(n);
4095                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4096                                result.add(browser);
4097                                defaultBrowserFound = true;
4098                                break;
4099                            }
4100                        }
4101                        if (!defaultBrowserFound) {
4102                            result.addAll(matchAllList);
4103                        }
4104                    } else {
4105                        result.addAll(matchAllList);
4106                    }
4107                }
4108            }
4109        }
4110        if (DEBUG_PREFERRED) {
4111            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4112                    result.size());
4113        }
4114        return result;
4115    }
4116
4117    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4118        int status = ps.getDomainVerificationStatusForUser(userId);
4119        // if none available, get the master status
4120        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4121            if (ps.getIntentFilterVerificationInfo() != null) {
4122                status = ps.getIntentFilterVerificationInfo().getStatus();
4123            }
4124        }
4125        return status;
4126    }
4127
4128    private ResolveInfo querySkipCurrentProfileIntents(
4129            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4130            int flags, int sourceUserId) {
4131        if (matchingFilters != null) {
4132            int size = matchingFilters.size();
4133            for (int i = 0; i < size; i ++) {
4134                CrossProfileIntentFilter filter = matchingFilters.get(i);
4135                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4136                    // Checking if there are activities in the target user that can handle the
4137                    // intent.
4138                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4139                            flags, sourceUserId);
4140                    if (resolveInfo != null) {
4141                        return resolveInfo;
4142                    }
4143                }
4144            }
4145        }
4146        return null;
4147    }
4148
4149    // Return matching ResolveInfo if any for skip current profile intent filters.
4150    private ResolveInfo queryCrossProfileIntents(
4151            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4152            int flags, int sourceUserId) {
4153        if (matchingFilters != null) {
4154            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4155            // match the same intent. For performance reasons, it is better not to
4156            // run queryIntent twice for the same userId
4157            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4158            int size = matchingFilters.size();
4159            for (int i = 0; i < size; i++) {
4160                CrossProfileIntentFilter filter = matchingFilters.get(i);
4161                int targetUserId = filter.getTargetUserId();
4162                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4163                        && !alreadyTriedUserIds.get(targetUserId)) {
4164                    // Checking if there are activities in the target user that can handle the
4165                    // intent.
4166                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4167                            flags, sourceUserId);
4168                    if (resolveInfo != null) return resolveInfo;
4169                    alreadyTriedUserIds.put(targetUserId, true);
4170                }
4171            }
4172        }
4173        return null;
4174    }
4175
4176    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4177            String resolvedType, int flags, int sourceUserId) {
4178        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4179                resolvedType, flags, filter.getTargetUserId());
4180        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4181            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4182        }
4183        return null;
4184    }
4185
4186    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4187            int sourceUserId, int targetUserId) {
4188        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4189        String className;
4190        if (targetUserId == UserHandle.USER_OWNER) {
4191            className = FORWARD_INTENT_TO_USER_OWNER;
4192        } else {
4193            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4194        }
4195        ComponentName forwardingActivityComponentName = new ComponentName(
4196                mAndroidApplication.packageName, className);
4197        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4198                sourceUserId);
4199        if (targetUserId == UserHandle.USER_OWNER) {
4200            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4201            forwardingResolveInfo.noResourceId = true;
4202        }
4203        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4204        forwardingResolveInfo.priority = 0;
4205        forwardingResolveInfo.preferredOrder = 0;
4206        forwardingResolveInfo.match = 0;
4207        forwardingResolveInfo.isDefault = true;
4208        forwardingResolveInfo.filter = filter;
4209        forwardingResolveInfo.targetUserId = targetUserId;
4210        return forwardingResolveInfo;
4211    }
4212
4213    @Override
4214    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4215            Intent[] specifics, String[] specificTypes, Intent intent,
4216            String resolvedType, int flags, int userId) {
4217        if (!sUserManager.exists(userId)) return Collections.emptyList();
4218        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4219                false, "query intent activity options");
4220        final String resultsAction = intent.getAction();
4221
4222        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4223                | PackageManager.GET_RESOLVED_FILTER, userId);
4224
4225        if (DEBUG_INTENT_MATCHING) {
4226            Log.v(TAG, "Query " + intent + ": " + results);
4227        }
4228
4229        int specificsPos = 0;
4230        int N;
4231
4232        // todo: note that the algorithm used here is O(N^2).  This
4233        // isn't a problem in our current environment, but if we start running
4234        // into situations where we have more than 5 or 10 matches then this
4235        // should probably be changed to something smarter...
4236
4237        // First we go through and resolve each of the specific items
4238        // that were supplied, taking care of removing any corresponding
4239        // duplicate items in the generic resolve list.
4240        if (specifics != null) {
4241            for (int i=0; i<specifics.length; i++) {
4242                final Intent sintent = specifics[i];
4243                if (sintent == null) {
4244                    continue;
4245                }
4246
4247                if (DEBUG_INTENT_MATCHING) {
4248                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4249                }
4250
4251                String action = sintent.getAction();
4252                if (resultsAction != null && resultsAction.equals(action)) {
4253                    // If this action was explicitly requested, then don't
4254                    // remove things that have it.
4255                    action = null;
4256                }
4257
4258                ResolveInfo ri = null;
4259                ActivityInfo ai = null;
4260
4261                ComponentName comp = sintent.getComponent();
4262                if (comp == null) {
4263                    ri = resolveIntent(
4264                        sintent,
4265                        specificTypes != null ? specificTypes[i] : null,
4266                            flags, userId);
4267                    if (ri == null) {
4268                        continue;
4269                    }
4270                    if (ri == mResolveInfo) {
4271                        // ACK!  Must do something better with this.
4272                    }
4273                    ai = ri.activityInfo;
4274                    comp = new ComponentName(ai.applicationInfo.packageName,
4275                            ai.name);
4276                } else {
4277                    ai = getActivityInfo(comp, flags, userId);
4278                    if (ai == null) {
4279                        continue;
4280                    }
4281                }
4282
4283                // Look for any generic query activities that are duplicates
4284                // of this specific one, and remove them from the results.
4285                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4286                N = results.size();
4287                int j;
4288                for (j=specificsPos; j<N; j++) {
4289                    ResolveInfo sri = results.get(j);
4290                    if ((sri.activityInfo.name.equals(comp.getClassName())
4291                            && sri.activityInfo.applicationInfo.packageName.equals(
4292                                    comp.getPackageName()))
4293                        || (action != null && sri.filter.matchAction(action))) {
4294                        results.remove(j);
4295                        if (DEBUG_INTENT_MATCHING) Log.v(
4296                            TAG, "Removing duplicate item from " + j
4297                            + " due to specific " + specificsPos);
4298                        if (ri == null) {
4299                            ri = sri;
4300                        }
4301                        j--;
4302                        N--;
4303                    }
4304                }
4305
4306                // Add this specific item to its proper place.
4307                if (ri == null) {
4308                    ri = new ResolveInfo();
4309                    ri.activityInfo = ai;
4310                }
4311                results.add(specificsPos, ri);
4312                ri.specificIndex = i;
4313                specificsPos++;
4314            }
4315        }
4316
4317        // Now we go through the remaining generic results and remove any
4318        // duplicate actions that are found here.
4319        N = results.size();
4320        for (int i=specificsPos; i<N-1; i++) {
4321            final ResolveInfo rii = results.get(i);
4322            if (rii.filter == null) {
4323                continue;
4324            }
4325
4326            // Iterate over all of the actions of this result's intent
4327            // filter...  typically this should be just one.
4328            final Iterator<String> it = rii.filter.actionsIterator();
4329            if (it == null) {
4330                continue;
4331            }
4332            while (it.hasNext()) {
4333                final String action = it.next();
4334                if (resultsAction != null && resultsAction.equals(action)) {
4335                    // If this action was explicitly requested, then don't
4336                    // remove things that have it.
4337                    continue;
4338                }
4339                for (int j=i+1; j<N; j++) {
4340                    final ResolveInfo rij = results.get(j);
4341                    if (rij.filter != null && rij.filter.hasAction(action)) {
4342                        results.remove(j);
4343                        if (DEBUG_INTENT_MATCHING) Log.v(
4344                            TAG, "Removing duplicate item from " + j
4345                            + " due to action " + action + " at " + i);
4346                        j--;
4347                        N--;
4348                    }
4349                }
4350            }
4351
4352            // If the caller didn't request filter information, drop it now
4353            // so we don't have to marshall/unmarshall it.
4354            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4355                rii.filter = null;
4356            }
4357        }
4358
4359        // Filter out the caller activity if so requested.
4360        if (caller != null) {
4361            N = results.size();
4362            for (int i=0; i<N; i++) {
4363                ActivityInfo ainfo = results.get(i).activityInfo;
4364                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4365                        && caller.getClassName().equals(ainfo.name)) {
4366                    results.remove(i);
4367                    break;
4368                }
4369            }
4370        }
4371
4372        // If the caller didn't request filter information,
4373        // drop them now so we don't have to
4374        // marshall/unmarshall it.
4375        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4376            N = results.size();
4377            for (int i=0; i<N; i++) {
4378                results.get(i).filter = null;
4379            }
4380        }
4381
4382        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4383        return results;
4384    }
4385
4386    @Override
4387    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4388            int userId) {
4389        if (!sUserManager.exists(userId)) return Collections.emptyList();
4390        ComponentName comp = intent.getComponent();
4391        if (comp == null) {
4392            if (intent.getSelector() != null) {
4393                intent = intent.getSelector();
4394                comp = intent.getComponent();
4395            }
4396        }
4397        if (comp != null) {
4398            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4399            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4400            if (ai != null) {
4401                ResolveInfo ri = new ResolveInfo();
4402                ri.activityInfo = ai;
4403                list.add(ri);
4404            }
4405            return list;
4406        }
4407
4408        // reader
4409        synchronized (mPackages) {
4410            String pkgName = intent.getPackage();
4411            if (pkgName == null) {
4412                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4413            }
4414            final PackageParser.Package pkg = mPackages.get(pkgName);
4415            if (pkg != null) {
4416                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4417                        userId);
4418            }
4419            return null;
4420        }
4421    }
4422
4423    @Override
4424    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4425        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4426        if (!sUserManager.exists(userId)) return null;
4427        if (query != null) {
4428            if (query.size() >= 1) {
4429                // If there is more than one service with the same priority,
4430                // just arbitrarily pick the first one.
4431                return query.get(0);
4432            }
4433        }
4434        return null;
4435    }
4436
4437    @Override
4438    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4439            int userId) {
4440        if (!sUserManager.exists(userId)) return Collections.emptyList();
4441        ComponentName comp = intent.getComponent();
4442        if (comp == null) {
4443            if (intent.getSelector() != null) {
4444                intent = intent.getSelector();
4445                comp = intent.getComponent();
4446            }
4447        }
4448        if (comp != null) {
4449            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4450            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4451            if (si != null) {
4452                final ResolveInfo ri = new ResolveInfo();
4453                ri.serviceInfo = si;
4454                list.add(ri);
4455            }
4456            return list;
4457        }
4458
4459        // reader
4460        synchronized (mPackages) {
4461            String pkgName = intent.getPackage();
4462            if (pkgName == null) {
4463                return mServices.queryIntent(intent, resolvedType, flags, userId);
4464            }
4465            final PackageParser.Package pkg = mPackages.get(pkgName);
4466            if (pkg != null) {
4467                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4468                        userId);
4469            }
4470            return null;
4471        }
4472    }
4473
4474    @Override
4475    public List<ResolveInfo> queryIntentContentProviders(
4476            Intent intent, String resolvedType, int flags, int userId) {
4477        if (!sUserManager.exists(userId)) return Collections.emptyList();
4478        ComponentName comp = intent.getComponent();
4479        if (comp == null) {
4480            if (intent.getSelector() != null) {
4481                intent = intent.getSelector();
4482                comp = intent.getComponent();
4483            }
4484        }
4485        if (comp != null) {
4486            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4487            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4488            if (pi != null) {
4489                final ResolveInfo ri = new ResolveInfo();
4490                ri.providerInfo = pi;
4491                list.add(ri);
4492            }
4493            return list;
4494        }
4495
4496        // reader
4497        synchronized (mPackages) {
4498            String pkgName = intent.getPackage();
4499            if (pkgName == null) {
4500                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4501            }
4502            final PackageParser.Package pkg = mPackages.get(pkgName);
4503            if (pkg != null) {
4504                return mProviders.queryIntentForPackage(
4505                        intent, resolvedType, flags, pkg.providers, userId);
4506            }
4507            return null;
4508        }
4509    }
4510
4511    @Override
4512    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4513        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4514
4515        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4516
4517        // writer
4518        synchronized (mPackages) {
4519            ArrayList<PackageInfo> list;
4520            if (listUninstalled) {
4521                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4522                for (PackageSetting ps : mSettings.mPackages.values()) {
4523                    PackageInfo pi;
4524                    if (ps.pkg != null) {
4525                        pi = generatePackageInfo(ps.pkg, flags, userId);
4526                    } else {
4527                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4528                    }
4529                    if (pi != null) {
4530                        list.add(pi);
4531                    }
4532                }
4533            } else {
4534                list = new ArrayList<PackageInfo>(mPackages.size());
4535                for (PackageParser.Package p : mPackages.values()) {
4536                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4537                    if (pi != null) {
4538                        list.add(pi);
4539                    }
4540                }
4541            }
4542
4543            return new ParceledListSlice<PackageInfo>(list);
4544        }
4545    }
4546
4547    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4548            String[] permissions, boolean[] tmp, int flags, int userId) {
4549        int numMatch = 0;
4550        final PermissionsState permissionsState = ps.getPermissionsState();
4551        for (int i=0; i<permissions.length; i++) {
4552            final String permission = permissions[i];
4553            if (permissionsState.hasPermission(permission, userId)) {
4554                tmp[i] = true;
4555                numMatch++;
4556            } else {
4557                tmp[i] = false;
4558            }
4559        }
4560        if (numMatch == 0) {
4561            return;
4562        }
4563        PackageInfo pi;
4564        if (ps.pkg != null) {
4565            pi = generatePackageInfo(ps.pkg, flags, userId);
4566        } else {
4567            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4568        }
4569        // The above might return null in cases of uninstalled apps or install-state
4570        // skew across users/profiles.
4571        if (pi != null) {
4572            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4573                if (numMatch == permissions.length) {
4574                    pi.requestedPermissions = permissions;
4575                } else {
4576                    pi.requestedPermissions = new String[numMatch];
4577                    numMatch = 0;
4578                    for (int i=0; i<permissions.length; i++) {
4579                        if (tmp[i]) {
4580                            pi.requestedPermissions[numMatch] = permissions[i];
4581                            numMatch++;
4582                        }
4583                    }
4584                }
4585            }
4586            list.add(pi);
4587        }
4588    }
4589
4590    @Override
4591    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4592            String[] permissions, int flags, int userId) {
4593        if (!sUserManager.exists(userId)) return null;
4594        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4595
4596        // writer
4597        synchronized (mPackages) {
4598            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4599            boolean[] tmpBools = new boolean[permissions.length];
4600            if (listUninstalled) {
4601                for (PackageSetting ps : mSettings.mPackages.values()) {
4602                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4603                }
4604            } else {
4605                for (PackageParser.Package pkg : mPackages.values()) {
4606                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4607                    if (ps != null) {
4608                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4609                                userId);
4610                    }
4611                }
4612            }
4613
4614            return new ParceledListSlice<PackageInfo>(list);
4615        }
4616    }
4617
4618    @Override
4619    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4620        if (!sUserManager.exists(userId)) return null;
4621        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4622
4623        // writer
4624        synchronized (mPackages) {
4625            ArrayList<ApplicationInfo> list;
4626            if (listUninstalled) {
4627                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4628                for (PackageSetting ps : mSettings.mPackages.values()) {
4629                    ApplicationInfo ai;
4630                    if (ps.pkg != null) {
4631                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4632                                ps.readUserState(userId), userId);
4633                    } else {
4634                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4635                    }
4636                    if (ai != null) {
4637                        list.add(ai);
4638                    }
4639                }
4640            } else {
4641                list = new ArrayList<ApplicationInfo>(mPackages.size());
4642                for (PackageParser.Package p : mPackages.values()) {
4643                    if (p.mExtras != null) {
4644                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4645                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4646                        if (ai != null) {
4647                            list.add(ai);
4648                        }
4649                    }
4650                }
4651            }
4652
4653            return new ParceledListSlice<ApplicationInfo>(list);
4654        }
4655    }
4656
4657    public List<ApplicationInfo> getPersistentApplications(int flags) {
4658        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4659
4660        // reader
4661        synchronized (mPackages) {
4662            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4663            final int userId = UserHandle.getCallingUserId();
4664            while (i.hasNext()) {
4665                final PackageParser.Package p = i.next();
4666                if (p.applicationInfo != null
4667                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4668                        && (!mSafeMode || isSystemApp(p))) {
4669                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4670                    if (ps != null) {
4671                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4672                                ps.readUserState(userId), userId);
4673                        if (ai != null) {
4674                            finalList.add(ai);
4675                        }
4676                    }
4677                }
4678            }
4679        }
4680
4681        return finalList;
4682    }
4683
4684    @Override
4685    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4686        if (!sUserManager.exists(userId)) return null;
4687        // reader
4688        synchronized (mPackages) {
4689            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4690            PackageSetting ps = provider != null
4691                    ? mSettings.mPackages.get(provider.owner.packageName)
4692                    : null;
4693            return ps != null
4694                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4695                    && (!mSafeMode || (provider.info.applicationInfo.flags
4696                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4697                    ? PackageParser.generateProviderInfo(provider, flags,
4698                            ps.readUserState(userId), userId)
4699                    : null;
4700        }
4701    }
4702
4703    /**
4704     * @deprecated
4705     */
4706    @Deprecated
4707    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4708        // reader
4709        synchronized (mPackages) {
4710            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4711                    .entrySet().iterator();
4712            final int userId = UserHandle.getCallingUserId();
4713            while (i.hasNext()) {
4714                Map.Entry<String, PackageParser.Provider> entry = i.next();
4715                PackageParser.Provider p = entry.getValue();
4716                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4717
4718                if (ps != null && p.syncable
4719                        && (!mSafeMode || (p.info.applicationInfo.flags
4720                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4721                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4722                            ps.readUserState(userId), userId);
4723                    if (info != null) {
4724                        outNames.add(entry.getKey());
4725                        outInfo.add(info);
4726                    }
4727                }
4728            }
4729        }
4730    }
4731
4732    @Override
4733    public List<ProviderInfo> queryContentProviders(String processName,
4734            int uid, int flags) {
4735        ArrayList<ProviderInfo> finalList = null;
4736        // reader
4737        synchronized (mPackages) {
4738            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4739            final int userId = processName != null ?
4740                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4741            while (i.hasNext()) {
4742                final PackageParser.Provider p = i.next();
4743                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4744                if (ps != null && p.info.authority != null
4745                        && (processName == null
4746                                || (p.info.processName.equals(processName)
4747                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4748                        && mSettings.isEnabledLPr(p.info, flags, userId)
4749                        && (!mSafeMode
4750                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4751                    if (finalList == null) {
4752                        finalList = new ArrayList<ProviderInfo>(3);
4753                    }
4754                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4755                            ps.readUserState(userId), userId);
4756                    if (info != null) {
4757                        finalList.add(info);
4758                    }
4759                }
4760            }
4761        }
4762
4763        if (finalList != null) {
4764            Collections.sort(finalList, mProviderInitOrderSorter);
4765        }
4766
4767        return finalList;
4768    }
4769
4770    @Override
4771    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4772            int flags) {
4773        // reader
4774        synchronized (mPackages) {
4775            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4776            return PackageParser.generateInstrumentationInfo(i, flags);
4777        }
4778    }
4779
4780    @Override
4781    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4782            int flags) {
4783        ArrayList<InstrumentationInfo> finalList =
4784            new ArrayList<InstrumentationInfo>();
4785
4786        // reader
4787        synchronized (mPackages) {
4788            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4789            while (i.hasNext()) {
4790                final PackageParser.Instrumentation p = i.next();
4791                if (targetPackage == null
4792                        || targetPackage.equals(p.info.targetPackage)) {
4793                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4794                            flags);
4795                    if (ii != null) {
4796                        finalList.add(ii);
4797                    }
4798                }
4799            }
4800        }
4801
4802        return finalList;
4803    }
4804
4805    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4806        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4807        if (overlays == null) {
4808            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4809            return;
4810        }
4811        for (PackageParser.Package opkg : overlays.values()) {
4812            // Not much to do if idmap fails: we already logged the error
4813            // and we certainly don't want to abort installation of pkg simply
4814            // because an overlay didn't fit properly. For these reasons,
4815            // ignore the return value of createIdmapForPackagePairLI.
4816            createIdmapForPackagePairLI(pkg, opkg);
4817        }
4818    }
4819
4820    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4821            PackageParser.Package opkg) {
4822        if (!opkg.mTrustedOverlay) {
4823            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4824                    opkg.baseCodePath + ": overlay not trusted");
4825            return false;
4826        }
4827        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4828        if (overlaySet == null) {
4829            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4830                    opkg.baseCodePath + " but target package has no known overlays");
4831            return false;
4832        }
4833        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4834        // TODO: generate idmap for split APKs
4835        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4836            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4837                    + opkg.baseCodePath);
4838            return false;
4839        }
4840        PackageParser.Package[] overlayArray =
4841            overlaySet.values().toArray(new PackageParser.Package[0]);
4842        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4843            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4844                return p1.mOverlayPriority - p2.mOverlayPriority;
4845            }
4846        };
4847        Arrays.sort(overlayArray, cmp);
4848
4849        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4850        int i = 0;
4851        for (PackageParser.Package p : overlayArray) {
4852            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4853        }
4854        return true;
4855    }
4856
4857    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4858        final File[] files = dir.listFiles();
4859        if (ArrayUtils.isEmpty(files)) {
4860            Log.d(TAG, "No files in app dir " + dir);
4861            return;
4862        }
4863
4864        if (DEBUG_PACKAGE_SCANNING) {
4865            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4866                    + " flags=0x" + Integer.toHexString(parseFlags));
4867        }
4868
4869        for (File file : files) {
4870            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4871                    && !PackageInstallerService.isStageName(file.getName());
4872            if (!isPackage) {
4873                // Ignore entries which are not packages
4874                continue;
4875            }
4876            try {
4877                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4878                        scanFlags, currentTime, null);
4879            } catch (PackageManagerException e) {
4880                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4881
4882                // Delete invalid userdata apps
4883                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4884                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4885                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4886                    if (file.isDirectory()) {
4887                        mInstaller.rmPackageDir(file.getAbsolutePath());
4888                    } else {
4889                        file.delete();
4890                    }
4891                }
4892            }
4893        }
4894    }
4895
4896    private static File getSettingsProblemFile() {
4897        File dataDir = Environment.getDataDirectory();
4898        File systemDir = new File(dataDir, "system");
4899        File fname = new File(systemDir, "uiderrors.txt");
4900        return fname;
4901    }
4902
4903    static void reportSettingsProblem(int priority, String msg) {
4904        logCriticalInfo(priority, msg);
4905    }
4906
4907    static void logCriticalInfo(int priority, String msg) {
4908        Slog.println(priority, TAG, msg);
4909        EventLogTags.writePmCriticalInfo(msg);
4910        try {
4911            File fname = getSettingsProblemFile();
4912            FileOutputStream out = new FileOutputStream(fname, true);
4913            PrintWriter pw = new FastPrintWriter(out);
4914            SimpleDateFormat formatter = new SimpleDateFormat();
4915            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4916            pw.println(dateString + ": " + msg);
4917            pw.close();
4918            FileUtils.setPermissions(
4919                    fname.toString(),
4920                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4921                    -1, -1);
4922        } catch (java.io.IOException e) {
4923        }
4924    }
4925
4926    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4927            PackageParser.Package pkg, File srcFile, int parseFlags)
4928            throws PackageManagerException {
4929        if (ps != null
4930                && ps.codePath.equals(srcFile)
4931                && ps.timeStamp == srcFile.lastModified()
4932                && !isCompatSignatureUpdateNeeded(pkg)
4933                && !isRecoverSignatureUpdateNeeded(pkg)) {
4934            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4935            if (ps.signatures.mSignatures != null
4936                    && ps.signatures.mSignatures.length != 0
4937                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4938                // Optimization: reuse the existing cached certificates
4939                // if the package appears to be unchanged.
4940                pkg.mSignatures = ps.signatures.mSignatures;
4941                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4942                synchronized (mPackages) {
4943                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4944                }
4945                return;
4946            }
4947
4948            Slog.w(TAG, "PackageSetting for " + ps.name
4949                    + " is missing signatures.  Collecting certs again to recover them.");
4950        } else {
4951            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4952        }
4953
4954        try {
4955            pp.collectCertificates(pkg, parseFlags);
4956            pp.collectManifestDigest(pkg);
4957        } catch (PackageParserException e) {
4958            throw PackageManagerException.from(e);
4959        }
4960    }
4961
4962    /*
4963     *  Scan a package and return the newly parsed package.
4964     *  Returns null in case of errors and the error code is stored in mLastScanError
4965     */
4966    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4967            long currentTime, UserHandle user) throws PackageManagerException {
4968        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4969        parseFlags |= mDefParseFlags;
4970        PackageParser pp = new PackageParser();
4971        pp.setSeparateProcesses(mSeparateProcesses);
4972        pp.setOnlyCoreApps(mOnlyCore);
4973        pp.setDisplayMetrics(mMetrics);
4974
4975        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4976            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4977        }
4978
4979        final PackageParser.Package pkg;
4980        try {
4981            pkg = pp.parsePackage(scanFile, parseFlags);
4982        } catch (PackageParserException e) {
4983            throw PackageManagerException.from(e);
4984        }
4985
4986        PackageSetting ps = null;
4987        PackageSetting updatedPkg;
4988        // reader
4989        synchronized (mPackages) {
4990            // Look to see if we already know about this package.
4991            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4992            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4993                // This package has been renamed to its original name.  Let's
4994                // use that.
4995                ps = mSettings.peekPackageLPr(oldName);
4996            }
4997            // If there was no original package, see one for the real package name.
4998            if (ps == null) {
4999                ps = mSettings.peekPackageLPr(pkg.packageName);
5000            }
5001            // Check to see if this package could be hiding/updating a system
5002            // package.  Must look for it either under the original or real
5003            // package name depending on our state.
5004            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5005            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5006        }
5007        boolean updatedPkgBetter = false;
5008        // First check if this is a system package that may involve an update
5009        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5010            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5011            // it needs to drop FLAG_PRIVILEGED.
5012            if (locationIsPrivileged(scanFile)) {
5013                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5014            } else {
5015                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5016            }
5017
5018            if (ps != null && !ps.codePath.equals(scanFile)) {
5019                // The path has changed from what was last scanned...  check the
5020                // version of the new path against what we have stored to determine
5021                // what to do.
5022                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5023                if (pkg.mVersionCode <= ps.versionCode) {
5024                    // The system package has been updated and the code path does not match
5025                    // Ignore entry. Skip it.
5026                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5027                            + " ignored: updated version " + ps.versionCode
5028                            + " better than this " + pkg.mVersionCode);
5029                    if (!updatedPkg.codePath.equals(scanFile)) {
5030                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5031                                + ps.name + " changing from " + updatedPkg.codePathString
5032                                + " to " + scanFile);
5033                        updatedPkg.codePath = scanFile;
5034                        updatedPkg.codePathString = scanFile.toString();
5035                        updatedPkg.resourcePath = scanFile;
5036                        updatedPkg.resourcePathString = scanFile.toString();
5037                    }
5038                    updatedPkg.pkg = pkg;
5039                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5040                } else {
5041                    // The current app on the system partition is better than
5042                    // what we have updated to on the data partition; switch
5043                    // back to the system partition version.
5044                    // At this point, its safely assumed that package installation for
5045                    // apps in system partition will go through. If not there won't be a working
5046                    // version of the app
5047                    // writer
5048                    synchronized (mPackages) {
5049                        // Just remove the loaded entries from package lists.
5050                        mPackages.remove(ps.name);
5051                    }
5052
5053                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5054                            + " reverting from " + ps.codePathString
5055                            + ": new version " + pkg.mVersionCode
5056                            + " better than installed " + ps.versionCode);
5057
5058                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5059                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5060                    synchronized (mInstallLock) {
5061                        args.cleanUpResourcesLI();
5062                    }
5063                    synchronized (mPackages) {
5064                        mSettings.enableSystemPackageLPw(ps.name);
5065                    }
5066                    updatedPkgBetter = true;
5067                }
5068            }
5069        }
5070
5071        if (updatedPkg != null) {
5072            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5073            // initially
5074            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5075
5076            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5077            // flag set initially
5078            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5079                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5080            }
5081        }
5082
5083        // Verify certificates against what was last scanned
5084        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5085
5086        /*
5087         * A new system app appeared, but we already had a non-system one of the
5088         * same name installed earlier.
5089         */
5090        boolean shouldHideSystemApp = false;
5091        if (updatedPkg == null && ps != null
5092                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5093            /*
5094             * Check to make sure the signatures match first. If they don't,
5095             * wipe the installed application and its data.
5096             */
5097            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5098                    != PackageManager.SIGNATURE_MATCH) {
5099                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5100                        + " signatures don't match existing userdata copy; removing");
5101                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5102                ps = null;
5103            } else {
5104                /*
5105                 * If the newly-added system app is an older version than the
5106                 * already installed version, hide it. It will be scanned later
5107                 * and re-added like an update.
5108                 */
5109                if (pkg.mVersionCode <= ps.versionCode) {
5110                    shouldHideSystemApp = true;
5111                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5112                            + " but new version " + pkg.mVersionCode + " better than installed "
5113                            + ps.versionCode + "; hiding system");
5114                } else {
5115                    /*
5116                     * The newly found system app is a newer version that the
5117                     * one previously installed. Simply remove the
5118                     * already-installed application and replace it with our own
5119                     * while keeping the application data.
5120                     */
5121                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5122                            + " reverting from " + ps.codePathString + ": new version "
5123                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5124                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5125                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5126                    synchronized (mInstallLock) {
5127                        args.cleanUpResourcesLI();
5128                    }
5129                }
5130            }
5131        }
5132
5133        // The apk is forward locked (not public) if its code and resources
5134        // are kept in different files. (except for app in either system or
5135        // vendor path).
5136        // TODO grab this value from PackageSettings
5137        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5138            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5139                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5140            }
5141        }
5142
5143        // TODO: extend to support forward-locked splits
5144        String resourcePath = null;
5145        String baseResourcePath = null;
5146        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5147            if (ps != null && ps.resourcePathString != null) {
5148                resourcePath = ps.resourcePathString;
5149                baseResourcePath = ps.resourcePathString;
5150            } else {
5151                // Should not happen at all. Just log an error.
5152                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5153            }
5154        } else {
5155            resourcePath = pkg.codePath;
5156            baseResourcePath = pkg.baseCodePath;
5157        }
5158
5159        // Set application objects path explicitly.
5160        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5161        pkg.applicationInfo.setCodePath(pkg.codePath);
5162        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5163        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5164        pkg.applicationInfo.setResourcePath(resourcePath);
5165        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5166        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5167
5168        // Note that we invoke the following method only if we are about to unpack an application
5169        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5170                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5171
5172        /*
5173         * If the system app should be overridden by a previously installed
5174         * data, hide the system app now and let the /data/app scan pick it up
5175         * again.
5176         */
5177        if (shouldHideSystemApp) {
5178            synchronized (mPackages) {
5179                /*
5180                 * We have to grant systems permissions before we hide, because
5181                 * grantPermissions will assume the package update is trying to
5182                 * expand its permissions.
5183                 */
5184                grantPermissionsLPw(pkg, true, pkg.packageName);
5185                mSettings.disableSystemPackageLPw(pkg.packageName);
5186            }
5187        }
5188
5189        return scannedPkg;
5190    }
5191
5192    private static String fixProcessName(String defProcessName,
5193            String processName, int uid) {
5194        if (processName == null) {
5195            return defProcessName;
5196        }
5197        return processName;
5198    }
5199
5200    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5201            throws PackageManagerException {
5202        if (pkgSetting.signatures.mSignatures != null) {
5203            // Already existing package. Make sure signatures match
5204            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5205                    == PackageManager.SIGNATURE_MATCH;
5206            if (!match) {
5207                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5208                        == PackageManager.SIGNATURE_MATCH;
5209            }
5210            if (!match) {
5211                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5212                        == PackageManager.SIGNATURE_MATCH;
5213            }
5214            if (!match) {
5215                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5216                        + pkg.packageName + " signatures do not match the "
5217                        + "previously installed version; ignoring!");
5218            }
5219        }
5220
5221        // Check for shared user signatures
5222        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5223            // Already existing package. Make sure signatures match
5224            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5225                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5226            if (!match) {
5227                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5228                        == PackageManager.SIGNATURE_MATCH;
5229            }
5230            if (!match) {
5231                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5232                        == PackageManager.SIGNATURE_MATCH;
5233            }
5234            if (!match) {
5235                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5236                        "Package " + pkg.packageName
5237                        + " has no signatures that match those in shared user "
5238                        + pkgSetting.sharedUser.name + "; ignoring!");
5239            }
5240        }
5241    }
5242
5243    /**
5244     * Enforces that only the system UID or root's UID can call a method exposed
5245     * via Binder.
5246     *
5247     * @param message used as message if SecurityException is thrown
5248     * @throws SecurityException if the caller is not system or root
5249     */
5250    private static final void enforceSystemOrRoot(String message) {
5251        final int uid = Binder.getCallingUid();
5252        if (uid != Process.SYSTEM_UID && uid != 0) {
5253            throw new SecurityException(message);
5254        }
5255    }
5256
5257    @Override
5258    public void performBootDexOpt() {
5259        enforceSystemOrRoot("Only the system can request dexopt be performed");
5260
5261        // Before everything else, see whether we need to fstrim.
5262        try {
5263            IMountService ms = PackageHelper.getMountService();
5264            if (ms != null) {
5265                final boolean isUpgrade = isUpgrade();
5266                boolean doTrim = isUpgrade;
5267                if (doTrim) {
5268                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5269                } else {
5270                    final long interval = android.provider.Settings.Global.getLong(
5271                            mContext.getContentResolver(),
5272                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5273                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5274                    if (interval > 0) {
5275                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5276                        if (timeSinceLast > interval) {
5277                            doTrim = true;
5278                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5279                                    + "; running immediately");
5280                        }
5281                    }
5282                }
5283                if (doTrim) {
5284                    if (!isFirstBoot()) {
5285                        try {
5286                            ActivityManagerNative.getDefault().showBootMessage(
5287                                    mContext.getResources().getString(
5288                                            R.string.android_upgrading_fstrim), true);
5289                        } catch (RemoteException e) {
5290                        }
5291                    }
5292                    ms.runMaintenance();
5293                }
5294            } else {
5295                Slog.e(TAG, "Mount service unavailable!");
5296            }
5297        } catch (RemoteException e) {
5298            // Can't happen; MountService is local
5299        }
5300
5301        final ArraySet<PackageParser.Package> pkgs;
5302        synchronized (mPackages) {
5303            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5304        }
5305
5306        if (pkgs != null) {
5307            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5308            // in case the device runs out of space.
5309            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5310            // Give priority to core apps.
5311            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5312                PackageParser.Package pkg = it.next();
5313                if (pkg.coreApp) {
5314                    if (DEBUG_DEXOPT) {
5315                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5316                    }
5317                    sortedPkgs.add(pkg);
5318                    it.remove();
5319                }
5320            }
5321            // Give priority to system apps that listen for pre boot complete.
5322            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5323            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5324            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5325                PackageParser.Package pkg = it.next();
5326                if (pkgNames.contains(pkg.packageName)) {
5327                    if (DEBUG_DEXOPT) {
5328                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5329                    }
5330                    sortedPkgs.add(pkg);
5331                    it.remove();
5332                }
5333            }
5334            // Give priority to system apps.
5335            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5336                PackageParser.Package pkg = it.next();
5337                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5338                    if (DEBUG_DEXOPT) {
5339                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5340                    }
5341                    sortedPkgs.add(pkg);
5342                    it.remove();
5343                }
5344            }
5345            // Give priority to updated system apps.
5346            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5347                PackageParser.Package pkg = it.next();
5348                if (pkg.isUpdatedSystemApp()) {
5349                    if (DEBUG_DEXOPT) {
5350                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5351                    }
5352                    sortedPkgs.add(pkg);
5353                    it.remove();
5354                }
5355            }
5356            // Give priority to apps that listen for boot complete.
5357            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5358            pkgNames = getPackageNamesForIntent(intent);
5359            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5360                PackageParser.Package pkg = it.next();
5361                if (pkgNames.contains(pkg.packageName)) {
5362                    if (DEBUG_DEXOPT) {
5363                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5364                    }
5365                    sortedPkgs.add(pkg);
5366                    it.remove();
5367                }
5368            }
5369            // Filter out packages that aren't recently used.
5370            filterRecentlyUsedApps(pkgs);
5371            // Add all remaining apps.
5372            for (PackageParser.Package pkg : pkgs) {
5373                if (DEBUG_DEXOPT) {
5374                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5375                }
5376                sortedPkgs.add(pkg);
5377            }
5378
5379            // If we want to be lazy, filter everything that wasn't recently used.
5380            if (mLazyDexOpt) {
5381                filterRecentlyUsedApps(sortedPkgs);
5382            }
5383
5384            int i = 0;
5385            int total = sortedPkgs.size();
5386            File dataDir = Environment.getDataDirectory();
5387            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5388            if (lowThreshold == 0) {
5389                throw new IllegalStateException("Invalid low memory threshold");
5390            }
5391            for (PackageParser.Package pkg : sortedPkgs) {
5392                long usableSpace = dataDir.getUsableSpace();
5393                if (usableSpace < lowThreshold) {
5394                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5395                    break;
5396                }
5397                performBootDexOpt(pkg, ++i, total);
5398            }
5399        }
5400    }
5401
5402    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5403        // Filter out packages that aren't recently used.
5404        //
5405        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5406        // should do a full dexopt.
5407        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5408            int total = pkgs.size();
5409            int skipped = 0;
5410            long now = System.currentTimeMillis();
5411            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5412                PackageParser.Package pkg = i.next();
5413                long then = pkg.mLastPackageUsageTimeInMills;
5414                if (then + mDexOptLRUThresholdInMills < now) {
5415                    if (DEBUG_DEXOPT) {
5416                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5417                              ((then == 0) ? "never" : new Date(then)));
5418                    }
5419                    i.remove();
5420                    skipped++;
5421                }
5422            }
5423            if (DEBUG_DEXOPT) {
5424                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5425            }
5426        }
5427    }
5428
5429    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5430        List<ResolveInfo> ris = null;
5431        try {
5432            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5433                    intent, null, 0, UserHandle.USER_OWNER);
5434        } catch (RemoteException e) {
5435        }
5436        ArraySet<String> pkgNames = new ArraySet<String>();
5437        if (ris != null) {
5438            for (ResolveInfo ri : ris) {
5439                pkgNames.add(ri.activityInfo.packageName);
5440            }
5441        }
5442        return pkgNames;
5443    }
5444
5445    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5446        if (DEBUG_DEXOPT) {
5447            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5448        }
5449        if (!isFirstBoot()) {
5450            try {
5451                ActivityManagerNative.getDefault().showBootMessage(
5452                        mContext.getResources().getString(R.string.android_upgrading_apk,
5453                                curr, total), true);
5454            } catch (RemoteException e) {
5455            }
5456        }
5457        PackageParser.Package p = pkg;
5458        synchronized (mInstallLock) {
5459            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5460                    false /* force dex */, false /* defer */, true /* include dependencies */);
5461        }
5462    }
5463
5464    @Override
5465    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5466        return performDexOpt(packageName, instructionSet, false);
5467    }
5468
5469    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5470        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5471        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5472        if (!dexopt && !updateUsage) {
5473            // We aren't going to dexopt or update usage, so bail early.
5474            return false;
5475        }
5476        PackageParser.Package p;
5477        final String targetInstructionSet;
5478        synchronized (mPackages) {
5479            p = mPackages.get(packageName);
5480            if (p == null) {
5481                return false;
5482            }
5483            if (updateUsage) {
5484                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5485            }
5486            mPackageUsage.write(false);
5487            if (!dexopt) {
5488                // We aren't going to dexopt, so bail early.
5489                return false;
5490            }
5491
5492            targetInstructionSet = instructionSet != null ? instructionSet :
5493                    getPrimaryInstructionSet(p.applicationInfo);
5494            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5495                return false;
5496            }
5497        }
5498
5499        synchronized (mInstallLock) {
5500            final String[] instructionSets = new String[] { targetInstructionSet };
5501            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5502                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5503            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5504        }
5505    }
5506
5507    public ArraySet<String> getPackagesThatNeedDexOpt() {
5508        ArraySet<String> pkgs = null;
5509        synchronized (mPackages) {
5510            for (PackageParser.Package p : mPackages.values()) {
5511                if (DEBUG_DEXOPT) {
5512                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5513                }
5514                if (!p.mDexOptPerformed.isEmpty()) {
5515                    continue;
5516                }
5517                if (pkgs == null) {
5518                    pkgs = new ArraySet<String>();
5519                }
5520                pkgs.add(p.packageName);
5521            }
5522        }
5523        return pkgs;
5524    }
5525
5526    public void shutdown() {
5527        mPackageUsage.write(true);
5528    }
5529
5530    @Override
5531    public void forceDexOpt(String packageName) {
5532        enforceSystemOrRoot("forceDexOpt");
5533
5534        PackageParser.Package pkg;
5535        synchronized (mPackages) {
5536            pkg = mPackages.get(packageName);
5537            if (pkg == null) {
5538                throw new IllegalArgumentException("Missing package: " + packageName);
5539            }
5540        }
5541
5542        synchronized (mInstallLock) {
5543            final String[] instructionSets = new String[] {
5544                    getPrimaryInstructionSet(pkg.applicationInfo) };
5545            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5546                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5547            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5548                throw new IllegalStateException("Failed to dexopt: " + res);
5549            }
5550        }
5551    }
5552
5553    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5554        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5555            Slog.w(TAG, "Unable to update from " + oldPkg.name
5556                    + " to " + newPkg.packageName
5557                    + ": old package not in system partition");
5558            return false;
5559        } else if (mPackages.get(oldPkg.name) != null) {
5560            Slog.w(TAG, "Unable to update from " + oldPkg.name
5561                    + " to " + newPkg.packageName
5562                    + ": old package still exists");
5563            return false;
5564        }
5565        return true;
5566    }
5567
5568    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5569        int[] users = sUserManager.getUserIds();
5570        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5571        if (res < 0) {
5572            return res;
5573        }
5574        for (int user : users) {
5575            if (user != 0) {
5576                res = mInstaller.createUserData(volumeUuid, packageName,
5577                        UserHandle.getUid(user, uid), user, seinfo);
5578                if (res < 0) {
5579                    return res;
5580                }
5581            }
5582        }
5583        return res;
5584    }
5585
5586    private int removeDataDirsLI(String volumeUuid, String packageName) {
5587        int[] users = sUserManager.getUserIds();
5588        int res = 0;
5589        for (int user : users) {
5590            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5591            if (resInner < 0) {
5592                res = resInner;
5593            }
5594        }
5595
5596        return res;
5597    }
5598
5599    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5600        int[] users = sUserManager.getUserIds();
5601        int res = 0;
5602        for (int user : users) {
5603            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5604            if (resInner < 0) {
5605                res = resInner;
5606            }
5607        }
5608        return res;
5609    }
5610
5611    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5612            PackageParser.Package changingLib) {
5613        if (file.path != null) {
5614            usesLibraryFiles.add(file.path);
5615            return;
5616        }
5617        PackageParser.Package p = mPackages.get(file.apk);
5618        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5619            // If we are doing this while in the middle of updating a library apk,
5620            // then we need to make sure to use that new apk for determining the
5621            // dependencies here.  (We haven't yet finished committing the new apk
5622            // to the package manager state.)
5623            if (p == null || p.packageName.equals(changingLib.packageName)) {
5624                p = changingLib;
5625            }
5626        }
5627        if (p != null) {
5628            usesLibraryFiles.addAll(p.getAllCodePaths());
5629        }
5630    }
5631
5632    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5633            PackageParser.Package changingLib) throws PackageManagerException {
5634        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5635            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5636            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5637            for (int i=0; i<N; i++) {
5638                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5639                if (file == null) {
5640                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5641                            "Package " + pkg.packageName + " requires unavailable shared library "
5642                            + pkg.usesLibraries.get(i) + "; failing!");
5643                }
5644                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5645            }
5646            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5647            for (int i=0; i<N; i++) {
5648                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5649                if (file == null) {
5650                    Slog.w(TAG, "Package " + pkg.packageName
5651                            + " desires unavailable shared library "
5652                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5653                } else {
5654                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5655                }
5656            }
5657            N = usesLibraryFiles.size();
5658            if (N > 0) {
5659                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5660            } else {
5661                pkg.usesLibraryFiles = null;
5662            }
5663        }
5664    }
5665
5666    private static boolean hasString(List<String> list, List<String> which) {
5667        if (list == null) {
5668            return false;
5669        }
5670        for (int i=list.size()-1; i>=0; i--) {
5671            for (int j=which.size()-1; j>=0; j--) {
5672                if (which.get(j).equals(list.get(i))) {
5673                    return true;
5674                }
5675            }
5676        }
5677        return false;
5678    }
5679
5680    private void updateAllSharedLibrariesLPw() {
5681        for (PackageParser.Package pkg : mPackages.values()) {
5682            try {
5683                updateSharedLibrariesLPw(pkg, null);
5684            } catch (PackageManagerException e) {
5685                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5686            }
5687        }
5688    }
5689
5690    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5691            PackageParser.Package changingPkg) {
5692        ArrayList<PackageParser.Package> res = null;
5693        for (PackageParser.Package pkg : mPackages.values()) {
5694            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5695                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5696                if (res == null) {
5697                    res = new ArrayList<PackageParser.Package>();
5698                }
5699                res.add(pkg);
5700                try {
5701                    updateSharedLibrariesLPw(pkg, changingPkg);
5702                } catch (PackageManagerException e) {
5703                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5704                }
5705            }
5706        }
5707        return res;
5708    }
5709
5710    /**
5711     * Derive the value of the {@code cpuAbiOverride} based on the provided
5712     * value and an optional stored value from the package settings.
5713     */
5714    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5715        String cpuAbiOverride = null;
5716
5717        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5718            cpuAbiOverride = null;
5719        } else if (abiOverride != null) {
5720            cpuAbiOverride = abiOverride;
5721        } else if (settings != null) {
5722            cpuAbiOverride = settings.cpuAbiOverrideString;
5723        }
5724
5725        return cpuAbiOverride;
5726    }
5727
5728    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5729            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5730        boolean success = false;
5731        try {
5732            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5733                    currentTime, user);
5734            success = true;
5735            return res;
5736        } finally {
5737            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5738                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
5739            }
5740        }
5741    }
5742
5743    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5744            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5745        final File scanFile = new File(pkg.codePath);
5746        if (pkg.applicationInfo.getCodePath() == null ||
5747                pkg.applicationInfo.getResourcePath() == null) {
5748            // Bail out. The resource and code paths haven't been set.
5749            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5750                    "Code and resource paths haven't been set correctly");
5751        }
5752
5753        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5754            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5755        } else {
5756            // Only allow system apps to be flagged as core apps.
5757            pkg.coreApp = false;
5758        }
5759
5760        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5761            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5762        }
5763
5764        if (mCustomResolverComponentName != null &&
5765                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5766            setUpCustomResolverActivity(pkg);
5767        }
5768
5769        if (pkg.packageName.equals("android")) {
5770            synchronized (mPackages) {
5771                if (mAndroidApplication != null) {
5772                    Slog.w(TAG, "*************************************************");
5773                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5774                    Slog.w(TAG, " file=" + scanFile);
5775                    Slog.w(TAG, "*************************************************");
5776                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5777                            "Core android package being redefined.  Skipping.");
5778                }
5779
5780                // Set up information for our fall-back user intent resolution activity.
5781                mPlatformPackage = pkg;
5782                pkg.mVersionCode = mSdkVersion;
5783                mAndroidApplication = pkg.applicationInfo;
5784
5785                if (!mResolverReplaced) {
5786                    mResolveActivity.applicationInfo = mAndroidApplication;
5787                    mResolveActivity.name = ResolverActivity.class.getName();
5788                    mResolveActivity.packageName = mAndroidApplication.packageName;
5789                    mResolveActivity.processName = "system:ui";
5790                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5791                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5792                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5793                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5794                    mResolveActivity.exported = true;
5795                    mResolveActivity.enabled = true;
5796                    mResolveInfo.activityInfo = mResolveActivity;
5797                    mResolveInfo.priority = 0;
5798                    mResolveInfo.preferredOrder = 0;
5799                    mResolveInfo.match = 0;
5800                    mResolveComponentName = new ComponentName(
5801                            mAndroidApplication.packageName, mResolveActivity.name);
5802                }
5803            }
5804        }
5805
5806        if (DEBUG_PACKAGE_SCANNING) {
5807            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5808                Log.d(TAG, "Scanning package " + pkg.packageName);
5809        }
5810
5811        if (mPackages.containsKey(pkg.packageName)
5812                || mSharedLibraries.containsKey(pkg.packageName)) {
5813            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5814                    "Application package " + pkg.packageName
5815                    + " already installed.  Skipping duplicate.");
5816        }
5817
5818        // If we're only installing presumed-existing packages, require that the
5819        // scanned APK is both already known and at the path previously established
5820        // for it.  Previously unknown packages we pick up normally, but if we have an
5821        // a priori expectation about this package's install presence, enforce it.
5822        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
5823            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
5824            if (known != null) {
5825                if (DEBUG_PACKAGE_SCANNING) {
5826                    Log.d(TAG, "Examining " + pkg.codePath
5827                            + " and requiring known paths " + known.codePathString
5828                            + " & " + known.resourcePathString);
5829                }
5830                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
5831                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
5832                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
5833                            "Application package " + pkg.packageName
5834                            + " found at " + pkg.applicationInfo.getCodePath()
5835                            + " but expected at " + known.codePathString + "; ignoring.");
5836                }
5837            }
5838        }
5839
5840        // Initialize package source and resource directories
5841        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5842        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5843
5844        SharedUserSetting suid = null;
5845        PackageSetting pkgSetting = null;
5846
5847        if (!isSystemApp(pkg)) {
5848            // Only system apps can use these features.
5849            pkg.mOriginalPackages = null;
5850            pkg.mRealPackage = null;
5851            pkg.mAdoptPermissions = null;
5852        }
5853
5854        // writer
5855        synchronized (mPackages) {
5856            if (pkg.mSharedUserId != null) {
5857                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5858                if (suid == null) {
5859                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5860                            "Creating application package " + pkg.packageName
5861                            + " for shared user failed");
5862                }
5863                if (DEBUG_PACKAGE_SCANNING) {
5864                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5865                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5866                                + "): packages=" + suid.packages);
5867                }
5868            }
5869
5870            // Check if we are renaming from an original package name.
5871            PackageSetting origPackage = null;
5872            String realName = null;
5873            if (pkg.mOriginalPackages != null) {
5874                // This package may need to be renamed to a previously
5875                // installed name.  Let's check on that...
5876                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5877                if (pkg.mOriginalPackages.contains(renamed)) {
5878                    // This package had originally been installed as the
5879                    // original name, and we have already taken care of
5880                    // transitioning to the new one.  Just update the new
5881                    // one to continue using the old name.
5882                    realName = pkg.mRealPackage;
5883                    if (!pkg.packageName.equals(renamed)) {
5884                        // Callers into this function may have already taken
5885                        // care of renaming the package; only do it here if
5886                        // it is not already done.
5887                        pkg.setPackageName(renamed);
5888                    }
5889
5890                } else {
5891                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5892                        if ((origPackage = mSettings.peekPackageLPr(
5893                                pkg.mOriginalPackages.get(i))) != null) {
5894                            // We do have the package already installed under its
5895                            // original name...  should we use it?
5896                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5897                                // New package is not compatible with original.
5898                                origPackage = null;
5899                                continue;
5900                            } else if (origPackage.sharedUser != null) {
5901                                // Make sure uid is compatible between packages.
5902                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5903                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5904                                            + " to " + pkg.packageName + ": old uid "
5905                                            + origPackage.sharedUser.name
5906                                            + " differs from " + pkg.mSharedUserId);
5907                                    origPackage = null;
5908                                    continue;
5909                                }
5910                            } else {
5911                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5912                                        + pkg.packageName + " to old name " + origPackage.name);
5913                            }
5914                            break;
5915                        }
5916                    }
5917                }
5918            }
5919
5920            if (mTransferedPackages.contains(pkg.packageName)) {
5921                Slog.w(TAG, "Package " + pkg.packageName
5922                        + " was transferred to another, but its .apk remains");
5923            }
5924
5925            // Just create the setting, don't add it yet. For already existing packages
5926            // the PkgSetting exists already and doesn't have to be created.
5927            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5928                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5929                    pkg.applicationInfo.primaryCpuAbi,
5930                    pkg.applicationInfo.secondaryCpuAbi,
5931                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
5932                    user, false);
5933            if (pkgSetting == null) {
5934                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5935                        "Creating application package " + pkg.packageName + " failed");
5936            }
5937
5938            if (pkgSetting.origPackage != null) {
5939                // If we are first transitioning from an original package,
5940                // fix up the new package's name now.  We need to do this after
5941                // looking up the package under its new name, so getPackageLP
5942                // can take care of fiddling things correctly.
5943                pkg.setPackageName(origPackage.name);
5944
5945                // File a report about this.
5946                String msg = "New package " + pkgSetting.realName
5947                        + " renamed to replace old package " + pkgSetting.name;
5948                reportSettingsProblem(Log.WARN, msg);
5949
5950                // Make a note of it.
5951                mTransferedPackages.add(origPackage.name);
5952
5953                // No longer need to retain this.
5954                pkgSetting.origPackage = null;
5955            }
5956
5957            if (realName != null) {
5958                // Make a note of it.
5959                mTransferedPackages.add(pkg.packageName);
5960            }
5961
5962            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5963                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5964            }
5965
5966            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5967                // Check all shared libraries and map to their actual file path.
5968                // We only do this here for apps not on a system dir, because those
5969                // are the only ones that can fail an install due to this.  We
5970                // will take care of the system apps by updating all of their
5971                // library paths after the scan is done.
5972                updateSharedLibrariesLPw(pkg, null);
5973            }
5974
5975            if (mFoundPolicyFile) {
5976                SELinuxMMAC.assignSeinfoValue(pkg);
5977            }
5978
5979            pkg.applicationInfo.uid = pkgSetting.appId;
5980            pkg.mExtras = pkgSetting;
5981            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5982                try {
5983                    verifySignaturesLP(pkgSetting, pkg);
5984                    // We just determined the app is signed correctly, so bring
5985                    // over the latest parsed certs.
5986                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5987                } catch (PackageManagerException e) {
5988                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5989                        throw e;
5990                    }
5991                    // The signature has changed, but this package is in the system
5992                    // image...  let's recover!
5993                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5994                    // However...  if this package is part of a shared user, but it
5995                    // doesn't match the signature of the shared user, let's fail.
5996                    // What this means is that you can't change the signatures
5997                    // associated with an overall shared user, which doesn't seem all
5998                    // that unreasonable.
5999                    if (pkgSetting.sharedUser != null) {
6000                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6001                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6002                            throw new PackageManagerException(
6003                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6004                                            "Signature mismatch for shared user : "
6005                                            + pkgSetting.sharedUser);
6006                        }
6007                    }
6008                    // File a report about this.
6009                    String msg = "System package " + pkg.packageName
6010                        + " signature changed; retaining data.";
6011                    reportSettingsProblem(Log.WARN, msg);
6012                }
6013            } else {
6014                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
6015                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6016                            + pkg.packageName + " upgrade keys do not match the "
6017                            + "previously installed version");
6018                } else {
6019                    // We just determined the app is signed correctly, so bring
6020                    // over the latest parsed certs.
6021                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6022                }
6023            }
6024            // Verify that this new package doesn't have any content providers
6025            // that conflict with existing packages.  Only do this if the
6026            // package isn't already installed, since we don't want to break
6027            // things that are installed.
6028            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6029                final int N = pkg.providers.size();
6030                int i;
6031                for (i=0; i<N; i++) {
6032                    PackageParser.Provider p = pkg.providers.get(i);
6033                    if (p.info.authority != null) {
6034                        String names[] = p.info.authority.split(";");
6035                        for (int j = 0; j < names.length; j++) {
6036                            if (mProvidersByAuthority.containsKey(names[j])) {
6037                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6038                                final String otherPackageName =
6039                                        ((other != null && other.getComponentName() != null) ?
6040                                                other.getComponentName().getPackageName() : "?");
6041                                throw new PackageManagerException(
6042                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6043                                                "Can't install because provider name " + names[j]
6044                                                + " (in package " + pkg.applicationInfo.packageName
6045                                                + ") is already used by " + otherPackageName);
6046                            }
6047                        }
6048                    }
6049                }
6050            }
6051
6052            if (pkg.mAdoptPermissions != null) {
6053                // This package wants to adopt ownership of permissions from
6054                // another package.
6055                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6056                    final String origName = pkg.mAdoptPermissions.get(i);
6057                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6058                    if (orig != null) {
6059                        if (verifyPackageUpdateLPr(orig, pkg)) {
6060                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6061                                    + pkg.packageName);
6062                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6063                        }
6064                    }
6065                }
6066            }
6067        }
6068
6069        final String pkgName = pkg.packageName;
6070
6071        final long scanFileTime = scanFile.lastModified();
6072        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6073        pkg.applicationInfo.processName = fixProcessName(
6074                pkg.applicationInfo.packageName,
6075                pkg.applicationInfo.processName,
6076                pkg.applicationInfo.uid);
6077
6078        File dataPath;
6079        if (mPlatformPackage == pkg) {
6080            // The system package is special.
6081            dataPath = new File(Environment.getDataDirectory(), "system");
6082
6083            pkg.applicationInfo.dataDir = dataPath.getPath();
6084
6085        } else {
6086            // This is a normal package, need to make its data directory.
6087            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6088                    UserHandle.USER_OWNER);
6089
6090            boolean uidError = false;
6091            if (dataPath.exists()) {
6092                int currentUid = 0;
6093                try {
6094                    StructStat stat = Os.stat(dataPath.getPath());
6095                    currentUid = stat.st_uid;
6096                } catch (ErrnoException e) {
6097                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6098                }
6099
6100                // If we have mismatched owners for the data path, we have a problem.
6101                if (currentUid != pkg.applicationInfo.uid) {
6102                    boolean recovered = false;
6103                    if (currentUid == 0) {
6104                        // The directory somehow became owned by root.  Wow.
6105                        // This is probably because the system was stopped while
6106                        // installd was in the middle of messing with its libs
6107                        // directory.  Ask installd to fix that.
6108                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6109                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6110                        if (ret >= 0) {
6111                            recovered = true;
6112                            String msg = "Package " + pkg.packageName
6113                                    + " unexpectedly changed to uid 0; recovered to " +
6114                                    + pkg.applicationInfo.uid;
6115                            reportSettingsProblem(Log.WARN, msg);
6116                        }
6117                    }
6118                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6119                            || (scanFlags&SCAN_BOOTING) != 0)) {
6120                        // If this is a system app, we can at least delete its
6121                        // current data so the application will still work.
6122                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6123                        if (ret >= 0) {
6124                            // TODO: Kill the processes first
6125                            // Old data gone!
6126                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6127                                    ? "System package " : "Third party package ";
6128                            String msg = prefix + pkg.packageName
6129                                    + " has changed from uid: "
6130                                    + currentUid + " to "
6131                                    + pkg.applicationInfo.uid + "; old data erased";
6132                            reportSettingsProblem(Log.WARN, msg);
6133                            recovered = true;
6134
6135                            // And now re-install the app.
6136                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6137                                    pkg.applicationInfo.seinfo);
6138                            if (ret == -1) {
6139                                // Ack should not happen!
6140                                msg = prefix + pkg.packageName
6141                                        + " could not have data directory re-created after delete.";
6142                                reportSettingsProblem(Log.WARN, msg);
6143                                throw new PackageManagerException(
6144                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6145                            }
6146                        }
6147                        if (!recovered) {
6148                            mHasSystemUidErrors = true;
6149                        }
6150                    } else if (!recovered) {
6151                        // If we allow this install to proceed, we will be broken.
6152                        // Abort, abort!
6153                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6154                                "scanPackageLI");
6155                    }
6156                    if (!recovered) {
6157                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6158                            + pkg.applicationInfo.uid + "/fs_"
6159                            + currentUid;
6160                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6161                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6162                        String msg = "Package " + pkg.packageName
6163                                + " has mismatched uid: "
6164                                + currentUid + " on disk, "
6165                                + pkg.applicationInfo.uid + " in settings";
6166                        // writer
6167                        synchronized (mPackages) {
6168                            mSettings.mReadMessages.append(msg);
6169                            mSettings.mReadMessages.append('\n');
6170                            uidError = true;
6171                            if (!pkgSetting.uidError) {
6172                                reportSettingsProblem(Log.ERROR, msg);
6173                            }
6174                        }
6175                    }
6176                }
6177                pkg.applicationInfo.dataDir = dataPath.getPath();
6178                if (mShouldRestoreconData) {
6179                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6180                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6181                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6182                }
6183            } else {
6184                if (DEBUG_PACKAGE_SCANNING) {
6185                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6186                        Log.v(TAG, "Want this data dir: " + dataPath);
6187                }
6188                //invoke installer to do the actual installation
6189                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6190                        pkg.applicationInfo.seinfo);
6191                if (ret < 0) {
6192                    // Error from installer
6193                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6194                            "Unable to create data dirs [errorCode=" + ret + "]");
6195                }
6196
6197                if (dataPath.exists()) {
6198                    pkg.applicationInfo.dataDir = dataPath.getPath();
6199                } else {
6200                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6201                    pkg.applicationInfo.dataDir = null;
6202                }
6203            }
6204
6205            pkgSetting.uidError = uidError;
6206        }
6207
6208        final String path = scanFile.getPath();
6209        final String codePath = pkg.applicationInfo.getCodePath();
6210        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6211        if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6212            setBundledAppAbisAndRoots(pkg, pkgSetting);
6213
6214            // If we haven't found any native libraries for the app, check if it has
6215            // renderscript code. We'll need to force the app to 32 bit if it has
6216            // renderscript bitcode.
6217            if (pkg.applicationInfo.primaryCpuAbi == null
6218                    && pkg.applicationInfo.secondaryCpuAbi == null
6219                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
6220                NativeLibraryHelper.Handle handle = null;
6221                try {
6222                    handle = NativeLibraryHelper.Handle.create(scanFile);
6223                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6224                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6225                    }
6226                } catch (IOException ioe) {
6227                    Slog.w(TAG, "Error scanning system app : " + ioe);
6228                } finally {
6229                    IoUtils.closeQuietly(handle);
6230                }
6231            }
6232
6233            setNativeLibraryPaths(pkg);
6234        } else {
6235            // TODO: We can probably be smarter about this stuff. For installed apps,
6236            // we can calculate this information at install time once and for all. For
6237            // system apps, we can probably assume that this information doesn't change
6238            // after the first boot scan. As things stand, we do lots of unnecessary work.
6239
6240            // Give ourselves some initial paths; we'll come back for another
6241            // pass once we've determined ABI below.
6242            setNativeLibraryPaths(pkg);
6243
6244            final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg);
6245            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6246            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6247
6248            NativeLibraryHelper.Handle handle = null;
6249            try {
6250                handle = NativeLibraryHelper.Handle.create(scanFile);
6251                // TODO(multiArch): This can be null for apps that didn't go through the
6252                // usual installation process. We can calculate it again, like we
6253                // do during install time.
6254                //
6255                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6256                // unnecessary.
6257                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6258
6259                // Null out the abis so that they can be recalculated.
6260                pkg.applicationInfo.primaryCpuAbi = null;
6261                pkg.applicationInfo.secondaryCpuAbi = null;
6262                if (isMultiArch(pkg.applicationInfo)) {
6263                    // Warn if we've set an abiOverride for multi-lib packages..
6264                    // By definition, we need to copy both 32 and 64 bit libraries for
6265                    // such packages.
6266                    if (pkg.cpuAbiOverride != null
6267                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
6268                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
6269                    }
6270
6271                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
6272                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
6273                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
6274                        if (isAsec) {
6275                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
6276                        } else {
6277                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6278                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
6279                                    useIsaSpecificSubdirs);
6280                        }
6281                    }
6282
6283                    maybeThrowExceptionForMultiArchCopy(
6284                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
6285
6286                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
6287                        if (isAsec) {
6288                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
6289                        } else {
6290                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6291                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
6292                                    useIsaSpecificSubdirs);
6293                        }
6294                    }
6295
6296                    maybeThrowExceptionForMultiArchCopy(
6297                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
6298
6299                    if (abi64 >= 0) {
6300                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
6301                    }
6302
6303                    if (abi32 >= 0) {
6304                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
6305                        if (abi64 >= 0) {
6306                            pkg.applicationInfo.secondaryCpuAbi = abi;
6307                        } else {
6308                            pkg.applicationInfo.primaryCpuAbi = abi;
6309                        }
6310                    }
6311                } else {
6312                    String[] abiList = (cpuAbiOverride != null) ?
6313                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
6314
6315                    // Enable gross and lame hacks for apps that are built with old
6316                    // SDK tools. We must scan their APKs for renderscript bitcode and
6317                    // not launch them if it's present. Don't bother checking on devices
6318                    // that don't have 64 bit support.
6319                    boolean needsRenderScriptOverride = false;
6320                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
6321                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6322                        abiList = Build.SUPPORTED_32_BIT_ABIS;
6323                        needsRenderScriptOverride = true;
6324                    }
6325
6326                    final int copyRet;
6327                    if (isAsec) {
6328                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6329                    } else {
6330                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6331                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
6332                    }
6333
6334                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
6335                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6336                                "Error unpackaging native libs for app, errorCode=" + copyRet);
6337                    }
6338
6339                    if (copyRet >= 0) {
6340                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
6341                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
6342                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
6343                    } else if (needsRenderScriptOverride) {
6344                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
6345                    }
6346                }
6347            } catch (IOException ioe) {
6348                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
6349            } finally {
6350                IoUtils.closeQuietly(handle);
6351            }
6352
6353            // Now that we've calculated the ABIs and determined if it's an internal app,
6354            // we will go ahead and populate the nativeLibraryPath.
6355            setNativeLibraryPaths(pkg);
6356
6357            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6358            final int[] userIds = sUserManager.getUserIds();
6359            synchronized (mInstallLock) {
6360                // Create a native library symlink only if we have native libraries
6361                // and if the native libraries are 32 bit libraries. We do not provide
6362                // this symlink for 64 bit libraries.
6363                if (pkg.applicationInfo.primaryCpuAbi != null &&
6364                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6365                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6366                    for (int userId : userIds) {
6367                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6368                                nativeLibPath, userId) < 0) {
6369                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6370                                    "Failed linking native library dir (user=" + userId + ")");
6371                        }
6372                    }
6373                }
6374            }
6375        }
6376
6377        // This is a special case for the "system" package, where the ABI is
6378        // dictated by the zygote configuration (and init.rc). We should keep track
6379        // of this ABI so that we can deal with "normal" applications that run under
6380        // the same UID correctly.
6381        if (mPlatformPackage == pkg) {
6382            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6383                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6384        }
6385
6386        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6387        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6388        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6389        // Copy the derived override back to the parsed package, so that we can
6390        // update the package settings accordingly.
6391        pkg.cpuAbiOverride = cpuAbiOverride;
6392
6393        if (DEBUG_ABI_SELECTION) {
6394            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6395                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6396                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6397        }
6398
6399        // Push the derived path down into PackageSettings so we know what to
6400        // clean up at uninstall time.
6401        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6402
6403        if (DEBUG_ABI_SELECTION) {
6404            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6405                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6406                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6407        }
6408
6409        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6410            // We don't do this here during boot because we can do it all
6411            // at once after scanning all existing packages.
6412            //
6413            // We also do this *before* we perform dexopt on this package, so that
6414            // we can avoid redundant dexopts, and also to make sure we've got the
6415            // code and package path correct.
6416            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6417                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6418        }
6419
6420        if ((scanFlags & SCAN_NO_DEX) == 0) {
6421            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6422                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6423            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6424                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6425            }
6426        }
6427        if (mFactoryTest && pkg.requestedPermissions.contains(
6428                android.Manifest.permission.FACTORY_TEST)) {
6429            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6430        }
6431
6432        ArrayList<PackageParser.Package> clientLibPkgs = null;
6433
6434        // writer
6435        synchronized (mPackages) {
6436            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6437                // Only system apps can add new shared libraries.
6438                if (pkg.libraryNames != null) {
6439                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6440                        String name = pkg.libraryNames.get(i);
6441                        boolean allowed = false;
6442                        if (pkg.isUpdatedSystemApp()) {
6443                            // New library entries can only be added through the
6444                            // system image.  This is important to get rid of a lot
6445                            // of nasty edge cases: for example if we allowed a non-
6446                            // system update of the app to add a library, then uninstalling
6447                            // the update would make the library go away, and assumptions
6448                            // we made such as through app install filtering would now
6449                            // have allowed apps on the device which aren't compatible
6450                            // with it.  Better to just have the restriction here, be
6451                            // conservative, and create many fewer cases that can negatively
6452                            // impact the user experience.
6453                            final PackageSetting sysPs = mSettings
6454                                    .getDisabledSystemPkgLPr(pkg.packageName);
6455                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6456                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6457                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6458                                        allowed = true;
6459                                        allowed = true;
6460                                        break;
6461                                    }
6462                                }
6463                            }
6464                        } else {
6465                            allowed = true;
6466                        }
6467                        if (allowed) {
6468                            if (!mSharedLibraries.containsKey(name)) {
6469                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6470                            } else if (!name.equals(pkg.packageName)) {
6471                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6472                                        + name + " already exists; skipping");
6473                            }
6474                        } else {
6475                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6476                                    + name + " that is not declared on system image; skipping");
6477                        }
6478                    }
6479                    if ((scanFlags&SCAN_BOOTING) == 0) {
6480                        // If we are not booting, we need to update any applications
6481                        // that are clients of our shared library.  If we are booting,
6482                        // this will all be done once the scan is complete.
6483                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6484                    }
6485                }
6486            }
6487        }
6488
6489        // We also need to dexopt any apps that are dependent on this library.  Note that
6490        // if these fail, we should abort the install since installing the library will
6491        // result in some apps being broken.
6492        if (clientLibPkgs != null) {
6493            if ((scanFlags & SCAN_NO_DEX) == 0) {
6494                for (int i = 0; i < clientLibPkgs.size(); i++) {
6495                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6496                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6497                            null /* instruction sets */, forceDex,
6498                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6499                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6500                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6501                                "scanPackageLI failed to dexopt clientLibPkgs");
6502                    }
6503                }
6504            }
6505        }
6506
6507        // Also need to kill any apps that are dependent on the library.
6508        if (clientLibPkgs != null) {
6509            for (int i=0; i<clientLibPkgs.size(); i++) {
6510                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6511                killApplication(clientPkg.applicationInfo.packageName,
6512                        clientPkg.applicationInfo.uid, "update lib");
6513            }
6514        }
6515
6516        // writer
6517        synchronized (mPackages) {
6518            // We don't expect installation to fail beyond this point
6519
6520            // Add the new setting to mSettings
6521            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6522            // Add the new setting to mPackages
6523            mPackages.put(pkg.applicationInfo.packageName, pkg);
6524            // Make sure we don't accidentally delete its data.
6525            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6526            while (iter.hasNext()) {
6527                PackageCleanItem item = iter.next();
6528                if (pkgName.equals(item.packageName)) {
6529                    iter.remove();
6530                }
6531            }
6532
6533            // Take care of first install / last update times.
6534            if (currentTime != 0) {
6535                if (pkgSetting.firstInstallTime == 0) {
6536                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6537                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6538                    pkgSetting.lastUpdateTime = currentTime;
6539                }
6540            } else if (pkgSetting.firstInstallTime == 0) {
6541                // We need *something*.  Take time time stamp of the file.
6542                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6543            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6544                if (scanFileTime != pkgSetting.timeStamp) {
6545                    // A package on the system image has changed; consider this
6546                    // to be an update.
6547                    pkgSetting.lastUpdateTime = scanFileTime;
6548                }
6549            }
6550
6551            // Add the package's KeySets to the global KeySetManagerService
6552            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6553            try {
6554                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6555                if (pkg.mKeySetMapping != null) {
6556                    ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping);
6557                    if (pkg.mUpgradeKeySets != null) {
6558                        ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets);
6559                    }
6560                }
6561            } catch (NullPointerException e) {
6562                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6563            } catch (IllegalArgumentException e) {
6564                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6565            }
6566
6567            int N = pkg.providers.size();
6568            StringBuilder r = null;
6569            int i;
6570            for (i=0; i<N; i++) {
6571                PackageParser.Provider p = pkg.providers.get(i);
6572                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6573                        p.info.processName, pkg.applicationInfo.uid);
6574                mProviders.addProvider(p);
6575                p.syncable = p.info.isSyncable;
6576                if (p.info.authority != null) {
6577                    String names[] = p.info.authority.split(";");
6578                    p.info.authority = null;
6579                    for (int j = 0; j < names.length; j++) {
6580                        if (j == 1 && p.syncable) {
6581                            // We only want the first authority for a provider to possibly be
6582                            // syncable, so if we already added this provider using a different
6583                            // authority clear the syncable flag. We copy the provider before
6584                            // changing it because the mProviders object contains a reference
6585                            // to a provider that we don't want to change.
6586                            // Only do this for the second authority since the resulting provider
6587                            // object can be the same for all future authorities for this provider.
6588                            p = new PackageParser.Provider(p);
6589                            p.syncable = false;
6590                        }
6591                        if (!mProvidersByAuthority.containsKey(names[j])) {
6592                            mProvidersByAuthority.put(names[j], p);
6593                            if (p.info.authority == null) {
6594                                p.info.authority = names[j];
6595                            } else {
6596                                p.info.authority = p.info.authority + ";" + names[j];
6597                            }
6598                            if (DEBUG_PACKAGE_SCANNING) {
6599                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6600                                    Log.d(TAG, "Registered content provider: " + names[j]
6601                                            + ", className = " + p.info.name + ", isSyncable = "
6602                                            + p.info.isSyncable);
6603                            }
6604                        } else {
6605                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6606                            Slog.w(TAG, "Skipping provider name " + names[j] +
6607                                    " (in package " + pkg.applicationInfo.packageName +
6608                                    "): name already used by "
6609                                    + ((other != null && other.getComponentName() != null)
6610                                            ? other.getComponentName().getPackageName() : "?"));
6611                        }
6612                    }
6613                }
6614                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6615                    if (r == null) {
6616                        r = new StringBuilder(256);
6617                    } else {
6618                        r.append(' ');
6619                    }
6620                    r.append(p.info.name);
6621                }
6622            }
6623            if (r != null) {
6624                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6625            }
6626
6627            N = pkg.services.size();
6628            r = null;
6629            for (i=0; i<N; i++) {
6630                PackageParser.Service s = pkg.services.get(i);
6631                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6632                        s.info.processName, pkg.applicationInfo.uid);
6633                mServices.addService(s);
6634                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6635                    if (r == null) {
6636                        r = new StringBuilder(256);
6637                    } else {
6638                        r.append(' ');
6639                    }
6640                    r.append(s.info.name);
6641                }
6642            }
6643            if (r != null) {
6644                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6645            }
6646
6647            N = pkg.receivers.size();
6648            r = null;
6649            for (i=0; i<N; i++) {
6650                PackageParser.Activity a = pkg.receivers.get(i);
6651                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6652                        a.info.processName, pkg.applicationInfo.uid);
6653                mReceivers.addActivity(a, "receiver");
6654                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6655                    if (r == null) {
6656                        r = new StringBuilder(256);
6657                    } else {
6658                        r.append(' ');
6659                    }
6660                    r.append(a.info.name);
6661                }
6662            }
6663            if (r != null) {
6664                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6665            }
6666
6667            N = pkg.activities.size();
6668            r = null;
6669            for (i=0; i<N; i++) {
6670                PackageParser.Activity a = pkg.activities.get(i);
6671                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6672                        a.info.processName, pkg.applicationInfo.uid);
6673                mActivities.addActivity(a, "activity");
6674                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6675                    if (r == null) {
6676                        r = new StringBuilder(256);
6677                    } else {
6678                        r.append(' ');
6679                    }
6680                    r.append(a.info.name);
6681                }
6682            }
6683            if (r != null) {
6684                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6685            }
6686
6687            N = pkg.permissionGroups.size();
6688            r = null;
6689            for (i=0; i<N; i++) {
6690                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6691                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6692                if (cur == null) {
6693                    mPermissionGroups.put(pg.info.name, pg);
6694                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6695                        if (r == null) {
6696                            r = new StringBuilder(256);
6697                        } else {
6698                            r.append(' ');
6699                        }
6700                        r.append(pg.info.name);
6701                    }
6702                } else {
6703                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6704                            + pg.info.packageName + " ignored: original from "
6705                            + cur.info.packageName);
6706                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6707                        if (r == null) {
6708                            r = new StringBuilder(256);
6709                        } else {
6710                            r.append(' ');
6711                        }
6712                        r.append("DUP:");
6713                        r.append(pg.info.name);
6714                    }
6715                }
6716            }
6717            if (r != null) {
6718                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6719            }
6720
6721            N = pkg.permissions.size();
6722            r = null;
6723            for (i=0; i<N; i++) {
6724                PackageParser.Permission p = pkg.permissions.get(i);
6725
6726                // Now that permission groups have a special meaning, we ignore permission
6727                // groups for legacy apps to prevent unexpected behavior. In particular,
6728                // permissions for one app being granted to someone just becuase they happen
6729                // to be in a group defined by another app (before this had no implications).
6730                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6731                    p.group = mPermissionGroups.get(p.info.group);
6732                    // Warn for a permission in an unknown group.
6733                    if (p.info.group != null && p.group == null) {
6734                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6735                                + p.info.packageName + " in an unknown group " + p.info.group);
6736                    }
6737                }
6738
6739                ArrayMap<String, BasePermission> permissionMap =
6740                        p.tree ? mSettings.mPermissionTrees
6741                                : mSettings.mPermissions;
6742                BasePermission bp = permissionMap.get(p.info.name);
6743
6744                // Allow system apps to redefine non-system permissions
6745                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6746                    final boolean currentOwnerIsSystem = (bp.perm != null
6747                            && isSystemApp(bp.perm.owner));
6748                    if (isSystemApp(p.owner)) {
6749                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6750                            // It's a built-in permission and no owner, take ownership now
6751                            bp.packageSetting = pkgSetting;
6752                            bp.perm = p;
6753                            bp.uid = pkg.applicationInfo.uid;
6754                            bp.sourcePackage = p.info.packageName;
6755                        } else if (!currentOwnerIsSystem) {
6756                            String msg = "New decl " + p.owner + " of permission  "
6757                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6758                            reportSettingsProblem(Log.WARN, msg);
6759                            bp = null;
6760                        }
6761                    }
6762                }
6763
6764                if (bp == null) {
6765                    bp = new BasePermission(p.info.name, p.info.packageName,
6766                            BasePermission.TYPE_NORMAL);
6767                    permissionMap.put(p.info.name, bp);
6768                }
6769
6770                if (bp.perm == null) {
6771                    if (bp.sourcePackage == null
6772                            || bp.sourcePackage.equals(p.info.packageName)) {
6773                        BasePermission tree = findPermissionTreeLP(p.info.name);
6774                        if (tree == null
6775                                || tree.sourcePackage.equals(p.info.packageName)) {
6776                            bp.packageSetting = pkgSetting;
6777                            bp.perm = p;
6778                            bp.uid = pkg.applicationInfo.uid;
6779                            bp.sourcePackage = p.info.packageName;
6780                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6781                                if (r == null) {
6782                                    r = new StringBuilder(256);
6783                                } else {
6784                                    r.append(' ');
6785                                }
6786                                r.append(p.info.name);
6787                            }
6788                        } else {
6789                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6790                                    + p.info.packageName + " ignored: base tree "
6791                                    + tree.name + " is from package "
6792                                    + tree.sourcePackage);
6793                        }
6794                    } else {
6795                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6796                                + p.info.packageName + " ignored: original from "
6797                                + bp.sourcePackage);
6798                    }
6799                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6800                    if (r == null) {
6801                        r = new StringBuilder(256);
6802                    } else {
6803                        r.append(' ');
6804                    }
6805                    r.append("DUP:");
6806                    r.append(p.info.name);
6807                }
6808                if (bp.perm == p) {
6809                    bp.protectionLevel = p.info.protectionLevel;
6810                }
6811            }
6812
6813            if (r != null) {
6814                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6815            }
6816
6817            N = pkg.instrumentation.size();
6818            r = null;
6819            for (i=0; i<N; i++) {
6820                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6821                a.info.packageName = pkg.applicationInfo.packageName;
6822                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6823                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6824                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6825                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6826                a.info.dataDir = pkg.applicationInfo.dataDir;
6827
6828                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6829                // need other information about the application, like the ABI and what not ?
6830                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6831                mInstrumentation.put(a.getComponentName(), a);
6832                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6833                    if (r == null) {
6834                        r = new StringBuilder(256);
6835                    } else {
6836                        r.append(' ');
6837                    }
6838                    r.append(a.info.name);
6839                }
6840            }
6841            if (r != null) {
6842                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6843            }
6844
6845            if (pkg.protectedBroadcasts != null) {
6846                N = pkg.protectedBroadcasts.size();
6847                for (i=0; i<N; i++) {
6848                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6849                }
6850            }
6851
6852            pkgSetting.setTimeStamp(scanFileTime);
6853
6854            // Create idmap files for pairs of (packages, overlay packages).
6855            // Note: "android", ie framework-res.apk, is handled by native layers.
6856            if (pkg.mOverlayTarget != null) {
6857                // This is an overlay package.
6858                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6859                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6860                        mOverlays.put(pkg.mOverlayTarget,
6861                                new ArrayMap<String, PackageParser.Package>());
6862                    }
6863                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6864                    map.put(pkg.packageName, pkg);
6865                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6866                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6867                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6868                                "scanPackageLI failed to createIdmap");
6869                    }
6870                }
6871            } else if (mOverlays.containsKey(pkg.packageName) &&
6872                    !pkg.packageName.equals("android")) {
6873                // This is a regular package, with one or more known overlay packages.
6874                createIdmapsForPackageLI(pkg);
6875            }
6876        }
6877
6878        return pkg;
6879    }
6880
6881    /**
6882     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6883     * i.e, so that all packages can be run inside a single process if required.
6884     *
6885     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6886     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6887     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6888     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6889     * updating a package that belongs to a shared user.
6890     *
6891     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6892     * adds unnecessary complexity.
6893     */
6894    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6895            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6896        String requiredInstructionSet = null;
6897        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6898            requiredInstructionSet = VMRuntime.getInstructionSet(
6899                     scannedPackage.applicationInfo.primaryCpuAbi);
6900        }
6901
6902        PackageSetting requirer = null;
6903        for (PackageSetting ps : packagesForUser) {
6904            // If packagesForUser contains scannedPackage, we skip it. This will happen
6905            // when scannedPackage is an update of an existing package. Without this check,
6906            // we will never be able to change the ABI of any package belonging to a shared
6907            // user, even if it's compatible with other packages.
6908            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6909                if (ps.primaryCpuAbiString == null) {
6910                    continue;
6911                }
6912
6913                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6914                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6915                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6916                    // this but there's not much we can do.
6917                    String errorMessage = "Instruction set mismatch, "
6918                            + ((requirer == null) ? "[caller]" : requirer)
6919                            + " requires " + requiredInstructionSet + " whereas " + ps
6920                            + " requires " + instructionSet;
6921                    Slog.w(TAG, errorMessage);
6922                }
6923
6924                if (requiredInstructionSet == null) {
6925                    requiredInstructionSet = instructionSet;
6926                    requirer = ps;
6927                }
6928            }
6929        }
6930
6931        if (requiredInstructionSet != null) {
6932            String adjustedAbi;
6933            if (requirer != null) {
6934                // requirer != null implies that either scannedPackage was null or that scannedPackage
6935                // did not require an ABI, in which case we have to adjust scannedPackage to match
6936                // the ABI of the set (which is the same as requirer's ABI)
6937                adjustedAbi = requirer.primaryCpuAbiString;
6938                if (scannedPackage != null) {
6939                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6940                }
6941            } else {
6942                // requirer == null implies that we're updating all ABIs in the set to
6943                // match scannedPackage.
6944                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6945            }
6946
6947            for (PackageSetting ps : packagesForUser) {
6948                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6949                    if (ps.primaryCpuAbiString != null) {
6950                        continue;
6951                    }
6952
6953                    ps.primaryCpuAbiString = adjustedAbi;
6954                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6955                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6956                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6957
6958                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
6959                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
6960                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6961                            ps.primaryCpuAbiString = null;
6962                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6963                            return;
6964                        } else {
6965                            mInstaller.rmdex(ps.codePathString,
6966                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
6967                        }
6968                    }
6969                }
6970            }
6971        }
6972    }
6973
6974    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6975        synchronized (mPackages) {
6976            mResolverReplaced = true;
6977            // Set up information for custom user intent resolution activity.
6978            mResolveActivity.applicationInfo = pkg.applicationInfo;
6979            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6980            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6981            mResolveActivity.processName = pkg.applicationInfo.packageName;
6982            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6983            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6984                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6985            mResolveActivity.theme = 0;
6986            mResolveActivity.exported = true;
6987            mResolveActivity.enabled = true;
6988            mResolveInfo.activityInfo = mResolveActivity;
6989            mResolveInfo.priority = 0;
6990            mResolveInfo.preferredOrder = 0;
6991            mResolveInfo.match = 0;
6992            mResolveComponentName = mCustomResolverComponentName;
6993            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6994                    mResolveComponentName);
6995        }
6996    }
6997
6998    private static String calculateBundledApkRoot(final String codePathString) {
6999        final File codePath = new File(codePathString);
7000        final File codeRoot;
7001        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7002            codeRoot = Environment.getRootDirectory();
7003        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7004            codeRoot = Environment.getOemDirectory();
7005        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7006            codeRoot = Environment.getVendorDirectory();
7007        } else {
7008            // Unrecognized code path; take its top real segment as the apk root:
7009            // e.g. /something/app/blah.apk => /something
7010            try {
7011                File f = codePath.getCanonicalFile();
7012                File parent = f.getParentFile();    // non-null because codePath is a file
7013                File tmp;
7014                while ((tmp = parent.getParentFile()) != null) {
7015                    f = parent;
7016                    parent = tmp;
7017                }
7018                codeRoot = f;
7019                Slog.w(TAG, "Unrecognized code path "
7020                        + codePath + " - using " + codeRoot);
7021            } catch (IOException e) {
7022                // Can't canonicalize the code path -- shenanigans?
7023                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7024                return Environment.getRootDirectory().getPath();
7025            }
7026        }
7027        return codeRoot.getPath();
7028    }
7029
7030    /**
7031     * Derive and set the location of native libraries for the given package,
7032     * which varies depending on where and how the package was installed.
7033     */
7034    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7035        final ApplicationInfo info = pkg.applicationInfo;
7036        final String codePath = pkg.codePath;
7037        final File codeFile = new File(codePath);
7038        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7039        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7040
7041        info.nativeLibraryRootDir = null;
7042        info.nativeLibraryRootRequiresIsa = false;
7043        info.nativeLibraryDir = null;
7044        info.secondaryNativeLibraryDir = null;
7045
7046        if (isApkFile(codeFile)) {
7047            // Monolithic install
7048            if (bundledApp) {
7049                // If "/system/lib64/apkname" exists, assume that is the per-package
7050                // native library directory to use; otherwise use "/system/lib/apkname".
7051                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7052                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7053                        getPrimaryInstructionSet(info));
7054
7055                // This is a bundled system app so choose the path based on the ABI.
7056                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7057                // is just the default path.
7058                final String apkName = deriveCodePathName(codePath);
7059                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7060                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7061                        apkName).getAbsolutePath();
7062
7063                if (info.secondaryCpuAbi != null) {
7064                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7065                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7066                            secondaryLibDir, apkName).getAbsolutePath();
7067                }
7068            } else if (asecApp) {
7069                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7070                        .getAbsolutePath();
7071            } else {
7072                final String apkName = deriveCodePathName(codePath);
7073                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7074                        .getAbsolutePath();
7075            }
7076
7077            info.nativeLibraryRootRequiresIsa = false;
7078            info.nativeLibraryDir = info.nativeLibraryRootDir;
7079        } else {
7080            // Cluster install
7081            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7082            info.nativeLibraryRootRequiresIsa = true;
7083
7084            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7085                    getPrimaryInstructionSet(info)).getAbsolutePath();
7086
7087            if (info.secondaryCpuAbi != null) {
7088                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7089                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7090            }
7091        }
7092    }
7093
7094    /**
7095     * Calculate the abis and roots for a bundled app. These can uniquely
7096     * be determined from the contents of the system partition, i.e whether
7097     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7098     * of this information, and instead assume that the system was built
7099     * sensibly.
7100     */
7101    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7102                                           PackageSetting pkgSetting) {
7103        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7104
7105        // If "/system/lib64/apkname" exists, assume that is the per-package
7106        // native library directory to use; otherwise use "/system/lib/apkname".
7107        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7108        setBundledAppAbi(pkg, apkRoot, apkName);
7109        // pkgSetting might be null during rescan following uninstall of updates
7110        // to a bundled app, so accommodate that possibility.  The settings in
7111        // that case will be established later from the parsed package.
7112        //
7113        // If the settings aren't null, sync them up with what we've just derived.
7114        // note that apkRoot isn't stored in the package settings.
7115        if (pkgSetting != null) {
7116            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7117            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7118        }
7119    }
7120
7121    /**
7122     * Deduces the ABI of a bundled app and sets the relevant fields on the
7123     * parsed pkg object.
7124     *
7125     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7126     *        under which system libraries are installed.
7127     * @param apkName the name of the installed package.
7128     */
7129    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7130        final File codeFile = new File(pkg.codePath);
7131
7132        final boolean has64BitLibs;
7133        final boolean has32BitLibs;
7134        if (isApkFile(codeFile)) {
7135            // Monolithic install
7136            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7137            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7138        } else {
7139            // Cluster install
7140            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7141            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7142                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7143                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7144                has64BitLibs = (new File(rootDir, isa)).exists();
7145            } else {
7146                has64BitLibs = false;
7147            }
7148            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7149                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7150                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7151                has32BitLibs = (new File(rootDir, isa)).exists();
7152            } else {
7153                has32BitLibs = false;
7154            }
7155        }
7156
7157        if (has64BitLibs && !has32BitLibs) {
7158            // The package has 64 bit libs, but not 32 bit libs. Its primary
7159            // ABI should be 64 bit. We can safely assume here that the bundled
7160            // native libraries correspond to the most preferred ABI in the list.
7161
7162            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7163            pkg.applicationInfo.secondaryCpuAbi = null;
7164        } else if (has32BitLibs && !has64BitLibs) {
7165            // The package has 32 bit libs but not 64 bit libs. Its primary
7166            // ABI should be 32 bit.
7167
7168            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7169            pkg.applicationInfo.secondaryCpuAbi = null;
7170        } else if (has32BitLibs && has64BitLibs) {
7171            // The application has both 64 and 32 bit bundled libraries. We check
7172            // here that the app declares multiArch support, and warn if it doesn't.
7173            //
7174            // We will be lenient here and record both ABIs. The primary will be the
7175            // ABI that's higher on the list, i.e, a device that's configured to prefer
7176            // 64 bit apps will see a 64 bit primary ABI,
7177
7178            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7179                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7180            }
7181
7182            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7183                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7184                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7185            } else {
7186                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7187                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7188            }
7189        } else {
7190            pkg.applicationInfo.primaryCpuAbi = null;
7191            pkg.applicationInfo.secondaryCpuAbi = null;
7192        }
7193    }
7194
7195    private void killApplication(String pkgName, int appId, String reason) {
7196        // Request the ActivityManager to kill the process(only for existing packages)
7197        // so that we do not end up in a confused state while the user is still using the older
7198        // version of the application while the new one gets installed.
7199        IActivityManager am = ActivityManagerNative.getDefault();
7200        if (am != null) {
7201            try {
7202                am.killApplicationWithAppId(pkgName, appId, reason);
7203            } catch (RemoteException e) {
7204            }
7205        }
7206    }
7207
7208    void removePackageLI(PackageSetting ps, boolean chatty) {
7209        if (DEBUG_INSTALL) {
7210            if (chatty)
7211                Log.d(TAG, "Removing package " + ps.name);
7212        }
7213
7214        // writer
7215        synchronized (mPackages) {
7216            mPackages.remove(ps.name);
7217            final PackageParser.Package pkg = ps.pkg;
7218            if (pkg != null) {
7219                cleanPackageDataStructuresLILPw(pkg, chatty);
7220            }
7221        }
7222    }
7223
7224    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7225        if (DEBUG_INSTALL) {
7226            if (chatty)
7227                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7228        }
7229
7230        // writer
7231        synchronized (mPackages) {
7232            mPackages.remove(pkg.applicationInfo.packageName);
7233            cleanPackageDataStructuresLILPw(pkg, chatty);
7234        }
7235    }
7236
7237    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7238        int N = pkg.providers.size();
7239        StringBuilder r = null;
7240        int i;
7241        for (i=0; i<N; i++) {
7242            PackageParser.Provider p = pkg.providers.get(i);
7243            mProviders.removeProvider(p);
7244            if (p.info.authority == null) {
7245
7246                /* There was another ContentProvider with this authority when
7247                 * this app was installed so this authority is null,
7248                 * Ignore it as we don't have to unregister the provider.
7249                 */
7250                continue;
7251            }
7252            String names[] = p.info.authority.split(";");
7253            for (int j = 0; j < names.length; j++) {
7254                if (mProvidersByAuthority.get(names[j]) == p) {
7255                    mProvidersByAuthority.remove(names[j]);
7256                    if (DEBUG_REMOVE) {
7257                        if (chatty)
7258                            Log.d(TAG, "Unregistered content provider: " + names[j]
7259                                    + ", className = " + p.info.name + ", isSyncable = "
7260                                    + p.info.isSyncable);
7261                    }
7262                }
7263            }
7264            if (DEBUG_REMOVE && chatty) {
7265                if (r == null) {
7266                    r = new StringBuilder(256);
7267                } else {
7268                    r.append(' ');
7269                }
7270                r.append(p.info.name);
7271            }
7272        }
7273        if (r != null) {
7274            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7275        }
7276
7277        N = pkg.services.size();
7278        r = null;
7279        for (i=0; i<N; i++) {
7280            PackageParser.Service s = pkg.services.get(i);
7281            mServices.removeService(s);
7282            if (chatty) {
7283                if (r == null) {
7284                    r = new StringBuilder(256);
7285                } else {
7286                    r.append(' ');
7287                }
7288                r.append(s.info.name);
7289            }
7290        }
7291        if (r != null) {
7292            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7293        }
7294
7295        N = pkg.receivers.size();
7296        r = null;
7297        for (i=0; i<N; i++) {
7298            PackageParser.Activity a = pkg.receivers.get(i);
7299            mReceivers.removeActivity(a, "receiver");
7300            if (DEBUG_REMOVE && chatty) {
7301                if (r == null) {
7302                    r = new StringBuilder(256);
7303                } else {
7304                    r.append(' ');
7305                }
7306                r.append(a.info.name);
7307            }
7308        }
7309        if (r != null) {
7310            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7311        }
7312
7313        N = pkg.activities.size();
7314        r = null;
7315        for (i=0; i<N; i++) {
7316            PackageParser.Activity a = pkg.activities.get(i);
7317            mActivities.removeActivity(a, "activity");
7318            if (DEBUG_REMOVE && chatty) {
7319                if (r == null) {
7320                    r = new StringBuilder(256);
7321                } else {
7322                    r.append(' ');
7323                }
7324                r.append(a.info.name);
7325            }
7326        }
7327        if (r != null) {
7328            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7329        }
7330
7331        N = pkg.permissions.size();
7332        r = null;
7333        for (i=0; i<N; i++) {
7334            PackageParser.Permission p = pkg.permissions.get(i);
7335            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7336            if (bp == null) {
7337                bp = mSettings.mPermissionTrees.get(p.info.name);
7338            }
7339            if (bp != null && bp.perm == p) {
7340                bp.perm = null;
7341                if (DEBUG_REMOVE && chatty) {
7342                    if (r == null) {
7343                        r = new StringBuilder(256);
7344                    } else {
7345                        r.append(' ');
7346                    }
7347                    r.append(p.info.name);
7348                }
7349            }
7350            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7351                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7352                if (appOpPerms != null) {
7353                    appOpPerms.remove(pkg.packageName);
7354                }
7355            }
7356        }
7357        if (r != null) {
7358            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7359        }
7360
7361        N = pkg.requestedPermissions.size();
7362        r = null;
7363        for (i=0; i<N; i++) {
7364            String perm = pkg.requestedPermissions.get(i);
7365            BasePermission bp = mSettings.mPermissions.get(perm);
7366            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7367                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7368                if (appOpPerms != null) {
7369                    appOpPerms.remove(pkg.packageName);
7370                    if (appOpPerms.isEmpty()) {
7371                        mAppOpPermissionPackages.remove(perm);
7372                    }
7373                }
7374            }
7375        }
7376        if (r != null) {
7377            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7378        }
7379
7380        N = pkg.instrumentation.size();
7381        r = null;
7382        for (i=0; i<N; i++) {
7383            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7384            mInstrumentation.remove(a.getComponentName());
7385            if (DEBUG_REMOVE && chatty) {
7386                if (r == null) {
7387                    r = new StringBuilder(256);
7388                } else {
7389                    r.append(' ');
7390                }
7391                r.append(a.info.name);
7392            }
7393        }
7394        if (r != null) {
7395            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7396        }
7397
7398        r = null;
7399        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7400            // Only system apps can hold shared libraries.
7401            if (pkg.libraryNames != null) {
7402                for (i=0; i<pkg.libraryNames.size(); i++) {
7403                    String name = pkg.libraryNames.get(i);
7404                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7405                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7406                        mSharedLibraries.remove(name);
7407                        if (DEBUG_REMOVE && chatty) {
7408                            if (r == null) {
7409                                r = new StringBuilder(256);
7410                            } else {
7411                                r.append(' ');
7412                            }
7413                            r.append(name);
7414                        }
7415                    }
7416                }
7417            }
7418        }
7419        if (r != null) {
7420            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7421        }
7422    }
7423
7424    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7425        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7426            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7427                return true;
7428            }
7429        }
7430        return false;
7431    }
7432
7433    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7434    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7435    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7436
7437    private void updatePermissionsLPw(String changingPkg,
7438            PackageParser.Package pkgInfo, int flags) {
7439        // Make sure there are no dangling permission trees.
7440        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7441        while (it.hasNext()) {
7442            final BasePermission bp = it.next();
7443            if (bp.packageSetting == null) {
7444                // We may not yet have parsed the package, so just see if
7445                // we still know about its settings.
7446                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7447            }
7448            if (bp.packageSetting == null) {
7449                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7450                        + " from package " + bp.sourcePackage);
7451                it.remove();
7452            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7453                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7454                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7455                            + " from package " + bp.sourcePackage);
7456                    flags |= UPDATE_PERMISSIONS_ALL;
7457                    it.remove();
7458                }
7459            }
7460        }
7461
7462        // Make sure all dynamic permissions have been assigned to a package,
7463        // and make sure there are no dangling permissions.
7464        it = mSettings.mPermissions.values().iterator();
7465        while (it.hasNext()) {
7466            final BasePermission bp = it.next();
7467            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7468                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7469                        + bp.name + " pkg=" + bp.sourcePackage
7470                        + " info=" + bp.pendingInfo);
7471                if (bp.packageSetting == null && bp.pendingInfo != null) {
7472                    final BasePermission tree = findPermissionTreeLP(bp.name);
7473                    if (tree != null && tree.perm != null) {
7474                        bp.packageSetting = tree.packageSetting;
7475                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7476                                new PermissionInfo(bp.pendingInfo));
7477                        bp.perm.info.packageName = tree.perm.info.packageName;
7478                        bp.perm.info.name = bp.name;
7479                        bp.uid = tree.uid;
7480                    }
7481                }
7482            }
7483            if (bp.packageSetting == null) {
7484                // We may not yet have parsed the package, so just see if
7485                // we still know about its settings.
7486                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7487            }
7488            if (bp.packageSetting == null) {
7489                Slog.w(TAG, "Removing dangling permission: " + bp.name
7490                        + " from package " + bp.sourcePackage);
7491                it.remove();
7492            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7493                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7494                    Slog.i(TAG, "Removing old permission: " + bp.name
7495                            + " from package " + bp.sourcePackage);
7496                    flags |= UPDATE_PERMISSIONS_ALL;
7497                    it.remove();
7498                }
7499            }
7500        }
7501
7502        // Now update the permissions for all packages, in particular
7503        // replace the granted permissions of the system packages.
7504        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7505            for (PackageParser.Package pkg : mPackages.values()) {
7506                if (pkg != pkgInfo) {
7507                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7508                            changingPkg);
7509                }
7510            }
7511        }
7512
7513        if (pkgInfo != null) {
7514            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7515        }
7516    }
7517
7518    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7519            String packageOfInterest) {
7520        // IMPORTANT: There are two types of permissions: install and runtime.
7521        // Install time permissions are granted when the app is installed to
7522        // all device users and users added in the future. Runtime permissions
7523        // are granted at runtime explicitly to specific users. Normal and signature
7524        // protected permissions are install time permissions. Dangerous permissions
7525        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7526        // otherwise they are runtime permissions. This function does not manage
7527        // runtime permissions except for the case an app targeting Lollipop MR1
7528        // being upgraded to target a newer SDK, in which case dangerous permissions
7529        // are transformed from install time to runtime ones.
7530
7531        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7532        if (ps == null) {
7533            return;
7534        }
7535
7536        PermissionsState permissionsState = ps.getPermissionsState();
7537        PermissionsState origPermissions = permissionsState;
7538
7539        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7540
7541        int[] upgradeUserIds = PermissionsState.USERS_NONE;
7542        int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE;
7543
7544        boolean changedInstallPermission = false;
7545
7546        if (replace) {
7547            ps.installPermissionsFixed = false;
7548            if (!ps.isSharedUser()) {
7549                origPermissions = new PermissionsState(permissionsState);
7550                permissionsState.reset();
7551            }
7552        }
7553
7554        permissionsState.setGlobalGids(mGlobalGids);
7555
7556        final int N = pkg.requestedPermissions.size();
7557        for (int i=0; i<N; i++) {
7558            final String name = pkg.requestedPermissions.get(i);
7559            final BasePermission bp = mSettings.mPermissions.get(name);
7560
7561            if (DEBUG_INSTALL) {
7562                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7563            }
7564
7565            if (bp == null || bp.packageSetting == null) {
7566                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7567                    Slog.w(TAG, "Unknown permission " + name
7568                            + " in package " + pkg.packageName);
7569                }
7570                continue;
7571            }
7572
7573            final String perm = bp.name;
7574            boolean allowedSig = false;
7575            int grant = GRANT_DENIED;
7576
7577            // Keep track of app op permissions.
7578            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7579                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7580                if (pkgs == null) {
7581                    pkgs = new ArraySet<>();
7582                    mAppOpPermissionPackages.put(bp.name, pkgs);
7583                }
7584                pkgs.add(pkg.packageName);
7585            }
7586
7587            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7588            switch (level) {
7589                case PermissionInfo.PROTECTION_NORMAL: {
7590                    // For all apps normal permissions are install time ones.
7591                    grant = GRANT_INSTALL;
7592                } break;
7593
7594                case PermissionInfo.PROTECTION_DANGEROUS: {
7595                    if (!RUNTIME_PERMISSIONS_ENABLED
7596                            || pkg.applicationInfo.targetSdkVersion
7597                                    <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7598                        // For legacy apps dangerous permissions are install time ones.
7599                        grant = GRANT_INSTALL;
7600                    } else if (ps.isSystem()) {
7601                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7602                        if (origPermissions.hasInstallPermission(bp.name)) {
7603                            // If a system app had an install permission, then the app was
7604                            // upgraded and we grant the permissions as runtime to all users.
7605                            grant = GRANT_UPGRADE;
7606                            upgradeUserIds = currentUserIds;
7607                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7608                            // If users changed since the last permissions update for a
7609                            // system app, we grant the permission as runtime to the new users.
7610                            grant = GRANT_UPGRADE;
7611                            upgradeUserIds = currentUserIds;
7612                            for (int userId : updatedUserIds) {
7613                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7614                            }
7615                        } else {
7616                            // Otherwise, we grant the permission as runtime if the app
7617                            // already had it, i.e. we preserve runtime permissions.
7618                            grant = GRANT_RUNTIME;
7619                        }
7620                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7621                        // For legacy apps that became modern, install becomes runtime.
7622                        grant = GRANT_UPGRADE;
7623                        upgradeUserIds = currentUserIds;
7624                    } else if (replace) {
7625                        // For upgraded modern apps keep runtime permissions unchanged.
7626                        grant = GRANT_RUNTIME;
7627                    }
7628                } break;
7629
7630                case PermissionInfo.PROTECTION_SIGNATURE: {
7631                    // For all apps signature permissions are install time ones.
7632                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7633                    if (allowedSig) {
7634                        grant = GRANT_INSTALL;
7635                    }
7636                } break;
7637            }
7638
7639            if (DEBUG_INSTALL) {
7640                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7641            }
7642
7643            if (grant != GRANT_DENIED) {
7644                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7645                    // If this is an existing, non-system package, then
7646                    // we can't add any new permissions to it.
7647                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7648                        // Except...  if this is a permission that was added
7649                        // to the platform (note: need to only do this when
7650                        // updating the platform).
7651                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7652                            grant = GRANT_DENIED;
7653                        }
7654                    }
7655                }
7656
7657                switch (grant) {
7658                    case GRANT_INSTALL: {
7659                        // Grant an install permission.
7660                        if (permissionsState.grantInstallPermission(bp) !=
7661                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7662                            changedInstallPermission = true;
7663                        }
7664                    } break;
7665
7666                    case GRANT_RUNTIME: {
7667                        // Grant previously granted runtime permissions.
7668                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7669                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7670                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7671                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7672                                    // If we cannot put the permission as it was, we have to write.
7673                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7674                                            changedRuntimePermissionUserIds, userId);
7675                                }
7676                            }
7677                        }
7678                    } break;
7679
7680                    case GRANT_UPGRADE: {
7681                        // Grant runtime permissions for a previously held install permission.
7682                        permissionsState.revokeInstallPermission(bp);
7683                        for (int userId : upgradeUserIds) {
7684                            if (permissionsState.grantRuntimePermission(bp, userId) !=
7685                                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
7686                                // If we granted the permission, we have to write.
7687                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7688                                        changedRuntimePermissionUserIds, userId);
7689                            }
7690                        }
7691                    } break;
7692
7693                    default: {
7694                        if (packageOfInterest == null
7695                                || packageOfInterest.equals(pkg.packageName)) {
7696                            Slog.w(TAG, "Not granting permission " + perm
7697                                    + " to package " + pkg.packageName
7698                                    + " because it was previously installed without");
7699                        }
7700                    } break;
7701                }
7702            } else {
7703                if (permissionsState.revokeInstallPermission(bp) !=
7704                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7705                    changedInstallPermission = true;
7706                    Slog.i(TAG, "Un-granting permission " + perm
7707                            + " from package " + pkg.packageName
7708                            + " (protectionLevel=" + bp.protectionLevel
7709                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7710                            + ")");
7711                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7712                    // Don't print warning for app op permissions, since it is fine for them
7713                    // not to be granted, there is a UI for the user to decide.
7714                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7715                        Slog.w(TAG, "Not granting permission " + perm
7716                                + " to package " + pkg.packageName
7717                                + " (protectionLevel=" + bp.protectionLevel
7718                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7719                                + ")");
7720                    }
7721                }
7722            }
7723        }
7724
7725        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7726                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7727            // This is the first that we have heard about this package, so the
7728            // permissions we have now selected are fixed until explicitly
7729            // changed.
7730            ps.installPermissionsFixed = true;
7731        }
7732
7733        ps.setPermissionsUpdatedForUserIds(currentUserIds);
7734
7735        // Persist the runtime permissions state for users with changes.
7736        if (RUNTIME_PERMISSIONS_ENABLED) {
7737            for (int userId : changedRuntimePermissionUserIds) {
7738                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
7739            }
7740        }
7741    }
7742
7743    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7744        boolean allowed = false;
7745        final int NP = PackageParser.NEW_PERMISSIONS.length;
7746        for (int ip=0; ip<NP; ip++) {
7747            final PackageParser.NewPermissionInfo npi
7748                    = PackageParser.NEW_PERMISSIONS[ip];
7749            if (npi.name.equals(perm)
7750                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7751                allowed = true;
7752                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7753                        + pkg.packageName);
7754                break;
7755            }
7756        }
7757        return allowed;
7758    }
7759
7760    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7761            BasePermission bp, PermissionsState origPermissions) {
7762        boolean allowed;
7763        allowed = (compareSignatures(
7764                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7765                        == PackageManager.SIGNATURE_MATCH)
7766                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7767                        == PackageManager.SIGNATURE_MATCH);
7768        if (!allowed && (bp.protectionLevel
7769                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7770            if (isSystemApp(pkg)) {
7771                // For updated system applications, a system permission
7772                // is granted only if it had been defined by the original application.
7773                if (pkg.isUpdatedSystemApp()) {
7774                    final PackageSetting sysPs = mSettings
7775                            .getDisabledSystemPkgLPr(pkg.packageName);
7776                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
7777                        // If the original was granted this permission, we take
7778                        // that grant decision as read and propagate it to the
7779                        // update.
7780                        if (sysPs.isPrivileged()) {
7781                            allowed = true;
7782                        }
7783                    } else {
7784                        // The system apk may have been updated with an older
7785                        // version of the one on the data partition, but which
7786                        // granted a new system permission that it didn't have
7787                        // before.  In this case we do want to allow the app to
7788                        // now get the new permission if the ancestral apk is
7789                        // privileged to get it.
7790                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7791                            for (int j=0;
7792                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7793                                if (perm.equals(
7794                                        sysPs.pkg.requestedPermissions.get(j))) {
7795                                    allowed = true;
7796                                    break;
7797                                }
7798                            }
7799                        }
7800                    }
7801                } else {
7802                    allowed = isPrivilegedApp(pkg);
7803                }
7804            }
7805        }
7806        if (!allowed && (bp.protectionLevel
7807                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7808            // For development permissions, a development permission
7809            // is granted only if it was already granted.
7810            allowed = origPermissions.hasInstallPermission(perm);
7811        }
7812        return allowed;
7813    }
7814
7815    final class ActivityIntentResolver
7816            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7817        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7818                boolean defaultOnly, int userId) {
7819            if (!sUserManager.exists(userId)) return null;
7820            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7821            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7822        }
7823
7824        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7825                int userId) {
7826            if (!sUserManager.exists(userId)) return null;
7827            mFlags = flags;
7828            return super.queryIntent(intent, resolvedType,
7829                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7830        }
7831
7832        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7833                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7834            if (!sUserManager.exists(userId)) return null;
7835            if (packageActivities == null) {
7836                return null;
7837            }
7838            mFlags = flags;
7839            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7840            final int N = packageActivities.size();
7841            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7842                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7843
7844            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7845            for (int i = 0; i < N; ++i) {
7846                intentFilters = packageActivities.get(i).intents;
7847                if (intentFilters != null && intentFilters.size() > 0) {
7848                    PackageParser.ActivityIntentInfo[] array =
7849                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7850                    intentFilters.toArray(array);
7851                    listCut.add(array);
7852                }
7853            }
7854            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7855        }
7856
7857        public final void addActivity(PackageParser.Activity a, String type) {
7858            final boolean systemApp = a.info.applicationInfo.isSystemApp();
7859            mActivities.put(a.getComponentName(), a);
7860            if (DEBUG_SHOW_INFO)
7861                Log.v(
7862                TAG, "  " + type + " " +
7863                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7864            if (DEBUG_SHOW_INFO)
7865                Log.v(TAG, "    Class=" + a.info.name);
7866            final int NI = a.intents.size();
7867            for (int j=0; j<NI; j++) {
7868                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7869                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7870                    intent.setPriority(0);
7871                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7872                            + a.className + " with priority > 0, forcing to 0");
7873                }
7874                if (DEBUG_SHOW_INFO) {
7875                    Log.v(TAG, "    IntentFilter:");
7876                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7877                }
7878                if (!intent.debugCheck()) {
7879                    Log.w(TAG, "==> For Activity " + a.info.name);
7880                }
7881                addFilter(intent);
7882            }
7883        }
7884
7885        public final void removeActivity(PackageParser.Activity a, String type) {
7886            mActivities.remove(a.getComponentName());
7887            if (DEBUG_SHOW_INFO) {
7888                Log.v(TAG, "  " + type + " "
7889                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7890                                : a.info.name) + ":");
7891                Log.v(TAG, "    Class=" + a.info.name);
7892            }
7893            final int NI = a.intents.size();
7894            for (int j=0; j<NI; j++) {
7895                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7896                if (DEBUG_SHOW_INFO) {
7897                    Log.v(TAG, "    IntentFilter:");
7898                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7899                }
7900                removeFilter(intent);
7901            }
7902        }
7903
7904        @Override
7905        protected boolean allowFilterResult(
7906                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7907            ActivityInfo filterAi = filter.activity.info;
7908            for (int i=dest.size()-1; i>=0; i--) {
7909                ActivityInfo destAi = dest.get(i).activityInfo;
7910                if (destAi.name == filterAi.name
7911                        && destAi.packageName == filterAi.packageName) {
7912                    return false;
7913                }
7914            }
7915            return true;
7916        }
7917
7918        @Override
7919        protected ActivityIntentInfo[] newArray(int size) {
7920            return new ActivityIntentInfo[size];
7921        }
7922
7923        @Override
7924        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7925            if (!sUserManager.exists(userId)) return true;
7926            PackageParser.Package p = filter.activity.owner;
7927            if (p != null) {
7928                PackageSetting ps = (PackageSetting)p.mExtras;
7929                if (ps != null) {
7930                    // System apps are never considered stopped for purposes of
7931                    // filtering, because there may be no way for the user to
7932                    // actually re-launch them.
7933                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7934                            && ps.getStopped(userId);
7935                }
7936            }
7937            return false;
7938        }
7939
7940        @Override
7941        protected boolean isPackageForFilter(String packageName,
7942                PackageParser.ActivityIntentInfo info) {
7943            return packageName.equals(info.activity.owner.packageName);
7944        }
7945
7946        @Override
7947        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7948                int match, int userId) {
7949            if (!sUserManager.exists(userId)) return null;
7950            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7951                return null;
7952            }
7953            final PackageParser.Activity activity = info.activity;
7954            if (mSafeMode && (activity.info.applicationInfo.flags
7955                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7956                return null;
7957            }
7958            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7959            if (ps == null) {
7960                return null;
7961            }
7962            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7963                    ps.readUserState(userId), userId);
7964            if (ai == null) {
7965                return null;
7966            }
7967            final ResolveInfo res = new ResolveInfo();
7968            res.activityInfo = ai;
7969            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7970                res.filter = info;
7971            }
7972            if (info != null) {
7973                res.handleAllWebDataURI = info.handleAllWebDataURI();
7974            }
7975            res.priority = info.getPriority();
7976            res.preferredOrder = activity.owner.mPreferredOrder;
7977            //System.out.println("Result: " + res.activityInfo.className +
7978            //                   " = " + res.priority);
7979            res.match = match;
7980            res.isDefault = info.hasDefault;
7981            res.labelRes = info.labelRes;
7982            res.nonLocalizedLabel = info.nonLocalizedLabel;
7983            if (userNeedsBadging(userId)) {
7984                res.noResourceId = true;
7985            } else {
7986                res.icon = info.icon;
7987            }
7988            res.system = res.activityInfo.applicationInfo.isSystemApp();
7989            return res;
7990        }
7991
7992        @Override
7993        protected void sortResults(List<ResolveInfo> results) {
7994            Collections.sort(results, mResolvePrioritySorter);
7995        }
7996
7997        @Override
7998        protected void dumpFilter(PrintWriter out, String prefix,
7999                PackageParser.ActivityIntentInfo filter) {
8000            out.print(prefix); out.print(
8001                    Integer.toHexString(System.identityHashCode(filter.activity)));
8002                    out.print(' ');
8003                    filter.activity.printComponentShortName(out);
8004                    out.print(" filter ");
8005                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8006        }
8007
8008        @Override
8009        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8010            return filter.activity;
8011        }
8012
8013        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8014            PackageParser.Activity activity = (PackageParser.Activity)label;
8015            out.print(prefix); out.print(
8016                    Integer.toHexString(System.identityHashCode(activity)));
8017                    out.print(' ');
8018                    activity.printComponentShortName(out);
8019            if (count > 1) {
8020                out.print(" ("); out.print(count); out.print(" filters)");
8021            }
8022            out.println();
8023        }
8024
8025//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8026//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8027//            final List<ResolveInfo> retList = Lists.newArrayList();
8028//            while (i.hasNext()) {
8029//                final ResolveInfo resolveInfo = i.next();
8030//                if (isEnabledLP(resolveInfo.activityInfo)) {
8031//                    retList.add(resolveInfo);
8032//                }
8033//            }
8034//            return retList;
8035//        }
8036
8037        // Keys are String (activity class name), values are Activity.
8038        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8039                = new ArrayMap<ComponentName, PackageParser.Activity>();
8040        private int mFlags;
8041    }
8042
8043    private final class ServiceIntentResolver
8044            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8045        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8046                boolean defaultOnly, int userId) {
8047            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8048            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8049        }
8050
8051        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8052                int userId) {
8053            if (!sUserManager.exists(userId)) return null;
8054            mFlags = flags;
8055            return super.queryIntent(intent, resolvedType,
8056                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8057        }
8058
8059        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8060                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8061            if (!sUserManager.exists(userId)) return null;
8062            if (packageServices == null) {
8063                return null;
8064            }
8065            mFlags = flags;
8066            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8067            final int N = packageServices.size();
8068            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8069                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8070
8071            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8072            for (int i = 0; i < N; ++i) {
8073                intentFilters = packageServices.get(i).intents;
8074                if (intentFilters != null && intentFilters.size() > 0) {
8075                    PackageParser.ServiceIntentInfo[] array =
8076                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8077                    intentFilters.toArray(array);
8078                    listCut.add(array);
8079                }
8080            }
8081            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8082        }
8083
8084        public final void addService(PackageParser.Service s) {
8085            mServices.put(s.getComponentName(), s);
8086            if (DEBUG_SHOW_INFO) {
8087                Log.v(TAG, "  "
8088                        + (s.info.nonLocalizedLabel != null
8089                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8090                Log.v(TAG, "    Class=" + s.info.name);
8091            }
8092            final int NI = s.intents.size();
8093            int j;
8094            for (j=0; j<NI; j++) {
8095                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8096                if (DEBUG_SHOW_INFO) {
8097                    Log.v(TAG, "    IntentFilter:");
8098                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8099                }
8100                if (!intent.debugCheck()) {
8101                    Log.w(TAG, "==> For Service " + s.info.name);
8102                }
8103                addFilter(intent);
8104            }
8105        }
8106
8107        public final void removeService(PackageParser.Service s) {
8108            mServices.remove(s.getComponentName());
8109            if (DEBUG_SHOW_INFO) {
8110                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8111                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8112                Log.v(TAG, "    Class=" + s.info.name);
8113            }
8114            final int NI = s.intents.size();
8115            int j;
8116            for (j=0; j<NI; j++) {
8117                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8118                if (DEBUG_SHOW_INFO) {
8119                    Log.v(TAG, "    IntentFilter:");
8120                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8121                }
8122                removeFilter(intent);
8123            }
8124        }
8125
8126        @Override
8127        protected boolean allowFilterResult(
8128                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8129            ServiceInfo filterSi = filter.service.info;
8130            for (int i=dest.size()-1; i>=0; i--) {
8131                ServiceInfo destAi = dest.get(i).serviceInfo;
8132                if (destAi.name == filterSi.name
8133                        && destAi.packageName == filterSi.packageName) {
8134                    return false;
8135                }
8136            }
8137            return true;
8138        }
8139
8140        @Override
8141        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8142            return new PackageParser.ServiceIntentInfo[size];
8143        }
8144
8145        @Override
8146        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8147            if (!sUserManager.exists(userId)) return true;
8148            PackageParser.Package p = filter.service.owner;
8149            if (p != null) {
8150                PackageSetting ps = (PackageSetting)p.mExtras;
8151                if (ps != null) {
8152                    // System apps are never considered stopped for purposes of
8153                    // filtering, because there may be no way for the user to
8154                    // actually re-launch them.
8155                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8156                            && ps.getStopped(userId);
8157                }
8158            }
8159            return false;
8160        }
8161
8162        @Override
8163        protected boolean isPackageForFilter(String packageName,
8164                PackageParser.ServiceIntentInfo info) {
8165            return packageName.equals(info.service.owner.packageName);
8166        }
8167
8168        @Override
8169        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8170                int match, int userId) {
8171            if (!sUserManager.exists(userId)) return null;
8172            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8173            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8174                return null;
8175            }
8176            final PackageParser.Service service = info.service;
8177            if (mSafeMode && (service.info.applicationInfo.flags
8178                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8179                return null;
8180            }
8181            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8182            if (ps == null) {
8183                return null;
8184            }
8185            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8186                    ps.readUserState(userId), userId);
8187            if (si == null) {
8188                return null;
8189            }
8190            final ResolveInfo res = new ResolveInfo();
8191            res.serviceInfo = si;
8192            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8193                res.filter = filter;
8194            }
8195            res.priority = info.getPriority();
8196            res.preferredOrder = service.owner.mPreferredOrder;
8197            res.match = match;
8198            res.isDefault = info.hasDefault;
8199            res.labelRes = info.labelRes;
8200            res.nonLocalizedLabel = info.nonLocalizedLabel;
8201            res.icon = info.icon;
8202            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8203            return res;
8204        }
8205
8206        @Override
8207        protected void sortResults(List<ResolveInfo> results) {
8208            Collections.sort(results, mResolvePrioritySorter);
8209        }
8210
8211        @Override
8212        protected void dumpFilter(PrintWriter out, String prefix,
8213                PackageParser.ServiceIntentInfo filter) {
8214            out.print(prefix); out.print(
8215                    Integer.toHexString(System.identityHashCode(filter.service)));
8216                    out.print(' ');
8217                    filter.service.printComponentShortName(out);
8218                    out.print(" filter ");
8219                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8220        }
8221
8222        @Override
8223        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8224            return filter.service;
8225        }
8226
8227        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8228            PackageParser.Service service = (PackageParser.Service)label;
8229            out.print(prefix); out.print(
8230                    Integer.toHexString(System.identityHashCode(service)));
8231                    out.print(' ');
8232                    service.printComponentShortName(out);
8233            if (count > 1) {
8234                out.print(" ("); out.print(count); out.print(" filters)");
8235            }
8236            out.println();
8237        }
8238
8239//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8240//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8241//            final List<ResolveInfo> retList = Lists.newArrayList();
8242//            while (i.hasNext()) {
8243//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8244//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8245//                    retList.add(resolveInfo);
8246//                }
8247//            }
8248//            return retList;
8249//        }
8250
8251        // Keys are String (activity class name), values are Activity.
8252        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8253                = new ArrayMap<ComponentName, PackageParser.Service>();
8254        private int mFlags;
8255    };
8256
8257    private final class ProviderIntentResolver
8258            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8259        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8260                boolean defaultOnly, int userId) {
8261            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8262            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8263        }
8264
8265        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8266                int userId) {
8267            if (!sUserManager.exists(userId))
8268                return null;
8269            mFlags = flags;
8270            return super.queryIntent(intent, resolvedType,
8271                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8272        }
8273
8274        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8275                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8276            if (!sUserManager.exists(userId))
8277                return null;
8278            if (packageProviders == null) {
8279                return null;
8280            }
8281            mFlags = flags;
8282            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8283            final int N = packageProviders.size();
8284            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8285                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8286
8287            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8288            for (int i = 0; i < N; ++i) {
8289                intentFilters = packageProviders.get(i).intents;
8290                if (intentFilters != null && intentFilters.size() > 0) {
8291                    PackageParser.ProviderIntentInfo[] array =
8292                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8293                    intentFilters.toArray(array);
8294                    listCut.add(array);
8295                }
8296            }
8297            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8298        }
8299
8300        public final void addProvider(PackageParser.Provider p) {
8301            if (mProviders.containsKey(p.getComponentName())) {
8302                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8303                return;
8304            }
8305
8306            mProviders.put(p.getComponentName(), p);
8307            if (DEBUG_SHOW_INFO) {
8308                Log.v(TAG, "  "
8309                        + (p.info.nonLocalizedLabel != null
8310                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8311                Log.v(TAG, "    Class=" + p.info.name);
8312            }
8313            final int NI = p.intents.size();
8314            int j;
8315            for (j = 0; j < NI; j++) {
8316                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8317                if (DEBUG_SHOW_INFO) {
8318                    Log.v(TAG, "    IntentFilter:");
8319                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8320                }
8321                if (!intent.debugCheck()) {
8322                    Log.w(TAG, "==> For Provider " + p.info.name);
8323                }
8324                addFilter(intent);
8325            }
8326        }
8327
8328        public final void removeProvider(PackageParser.Provider p) {
8329            mProviders.remove(p.getComponentName());
8330            if (DEBUG_SHOW_INFO) {
8331                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8332                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8333                Log.v(TAG, "    Class=" + p.info.name);
8334            }
8335            final int NI = p.intents.size();
8336            int j;
8337            for (j = 0; j < NI; j++) {
8338                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8339                if (DEBUG_SHOW_INFO) {
8340                    Log.v(TAG, "    IntentFilter:");
8341                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8342                }
8343                removeFilter(intent);
8344            }
8345        }
8346
8347        @Override
8348        protected boolean allowFilterResult(
8349                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8350            ProviderInfo filterPi = filter.provider.info;
8351            for (int i = dest.size() - 1; i >= 0; i--) {
8352                ProviderInfo destPi = dest.get(i).providerInfo;
8353                if (destPi.name == filterPi.name
8354                        && destPi.packageName == filterPi.packageName) {
8355                    return false;
8356                }
8357            }
8358            return true;
8359        }
8360
8361        @Override
8362        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8363            return new PackageParser.ProviderIntentInfo[size];
8364        }
8365
8366        @Override
8367        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8368            if (!sUserManager.exists(userId))
8369                return true;
8370            PackageParser.Package p = filter.provider.owner;
8371            if (p != null) {
8372                PackageSetting ps = (PackageSetting) p.mExtras;
8373                if (ps != null) {
8374                    // System apps are never considered stopped for purposes of
8375                    // filtering, because there may be no way for the user to
8376                    // actually re-launch them.
8377                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8378                            && ps.getStopped(userId);
8379                }
8380            }
8381            return false;
8382        }
8383
8384        @Override
8385        protected boolean isPackageForFilter(String packageName,
8386                PackageParser.ProviderIntentInfo info) {
8387            return packageName.equals(info.provider.owner.packageName);
8388        }
8389
8390        @Override
8391        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8392                int match, int userId) {
8393            if (!sUserManager.exists(userId))
8394                return null;
8395            final PackageParser.ProviderIntentInfo info = filter;
8396            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8397                return null;
8398            }
8399            final PackageParser.Provider provider = info.provider;
8400            if (mSafeMode && (provider.info.applicationInfo.flags
8401                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8402                return null;
8403            }
8404            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8405            if (ps == null) {
8406                return null;
8407            }
8408            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8409                    ps.readUserState(userId), userId);
8410            if (pi == null) {
8411                return null;
8412            }
8413            final ResolveInfo res = new ResolveInfo();
8414            res.providerInfo = pi;
8415            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8416                res.filter = filter;
8417            }
8418            res.priority = info.getPriority();
8419            res.preferredOrder = provider.owner.mPreferredOrder;
8420            res.match = match;
8421            res.isDefault = info.hasDefault;
8422            res.labelRes = info.labelRes;
8423            res.nonLocalizedLabel = info.nonLocalizedLabel;
8424            res.icon = info.icon;
8425            res.system = res.providerInfo.applicationInfo.isSystemApp();
8426            return res;
8427        }
8428
8429        @Override
8430        protected void sortResults(List<ResolveInfo> results) {
8431            Collections.sort(results, mResolvePrioritySorter);
8432        }
8433
8434        @Override
8435        protected void dumpFilter(PrintWriter out, String prefix,
8436                PackageParser.ProviderIntentInfo filter) {
8437            out.print(prefix);
8438            out.print(
8439                    Integer.toHexString(System.identityHashCode(filter.provider)));
8440            out.print(' ');
8441            filter.provider.printComponentShortName(out);
8442            out.print(" filter ");
8443            out.println(Integer.toHexString(System.identityHashCode(filter)));
8444        }
8445
8446        @Override
8447        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8448            return filter.provider;
8449        }
8450
8451        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8452            PackageParser.Provider provider = (PackageParser.Provider)label;
8453            out.print(prefix); out.print(
8454                    Integer.toHexString(System.identityHashCode(provider)));
8455                    out.print(' ');
8456                    provider.printComponentShortName(out);
8457            if (count > 1) {
8458                out.print(" ("); out.print(count); out.print(" filters)");
8459            }
8460            out.println();
8461        }
8462
8463        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8464                = new ArrayMap<ComponentName, PackageParser.Provider>();
8465        private int mFlags;
8466    };
8467
8468    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8469            new Comparator<ResolveInfo>() {
8470        public int compare(ResolveInfo r1, ResolveInfo r2) {
8471            int v1 = r1.priority;
8472            int v2 = r2.priority;
8473            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8474            if (v1 != v2) {
8475                return (v1 > v2) ? -1 : 1;
8476            }
8477            v1 = r1.preferredOrder;
8478            v2 = r2.preferredOrder;
8479            if (v1 != v2) {
8480                return (v1 > v2) ? -1 : 1;
8481            }
8482            if (r1.isDefault != r2.isDefault) {
8483                return r1.isDefault ? -1 : 1;
8484            }
8485            v1 = r1.match;
8486            v2 = r2.match;
8487            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8488            if (v1 != v2) {
8489                return (v1 > v2) ? -1 : 1;
8490            }
8491            if (r1.system != r2.system) {
8492                return r1.system ? -1 : 1;
8493            }
8494            return 0;
8495        }
8496    };
8497
8498    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8499            new Comparator<ProviderInfo>() {
8500        public int compare(ProviderInfo p1, ProviderInfo p2) {
8501            final int v1 = p1.initOrder;
8502            final int v2 = p2.initOrder;
8503            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8504        }
8505    };
8506
8507    final void sendPackageBroadcast(final String action, final String pkg,
8508            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8509            final int[] userIds) {
8510        mHandler.post(new Runnable() {
8511            @Override
8512            public void run() {
8513                try {
8514                    final IActivityManager am = ActivityManagerNative.getDefault();
8515                    if (am == null) return;
8516                    final int[] resolvedUserIds;
8517                    if (userIds == null) {
8518                        resolvedUserIds = am.getRunningUserIds();
8519                    } else {
8520                        resolvedUserIds = userIds;
8521                    }
8522                    for (int id : resolvedUserIds) {
8523                        final Intent intent = new Intent(action,
8524                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8525                        if (extras != null) {
8526                            intent.putExtras(extras);
8527                        }
8528                        if (targetPkg != null) {
8529                            intent.setPackage(targetPkg);
8530                        }
8531                        // Modify the UID when posting to other users
8532                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8533                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8534                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8535                            intent.putExtra(Intent.EXTRA_UID, uid);
8536                        }
8537                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8538                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8539                        if (DEBUG_BROADCASTS) {
8540                            RuntimeException here = new RuntimeException("here");
8541                            here.fillInStackTrace();
8542                            Slog.d(TAG, "Sending to user " + id + ": "
8543                                    + intent.toShortString(false, true, false, false)
8544                                    + " " + intent.getExtras(), here);
8545                        }
8546                        am.broadcastIntent(null, intent, null, finishedReceiver,
8547                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8548                                finishedReceiver != null, false, id);
8549                    }
8550                } catch (RemoteException ex) {
8551                }
8552            }
8553        });
8554    }
8555
8556    /**
8557     * Check if the external storage media is available. This is true if there
8558     * is a mounted external storage medium or if the external storage is
8559     * emulated.
8560     */
8561    private boolean isExternalMediaAvailable() {
8562        return mMediaMounted || Environment.isExternalStorageEmulated();
8563    }
8564
8565    @Override
8566    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8567        // writer
8568        synchronized (mPackages) {
8569            if (!isExternalMediaAvailable()) {
8570                // If the external storage is no longer mounted at this point,
8571                // the caller may not have been able to delete all of this
8572                // packages files and can not delete any more.  Bail.
8573                return null;
8574            }
8575            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8576            if (lastPackage != null) {
8577                pkgs.remove(lastPackage);
8578            }
8579            if (pkgs.size() > 0) {
8580                return pkgs.get(0);
8581            }
8582        }
8583        return null;
8584    }
8585
8586    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8587        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8588                userId, andCode ? 1 : 0, packageName);
8589        if (mSystemReady) {
8590            msg.sendToTarget();
8591        } else {
8592            if (mPostSystemReadyMessages == null) {
8593                mPostSystemReadyMessages = new ArrayList<>();
8594            }
8595            mPostSystemReadyMessages.add(msg);
8596        }
8597    }
8598
8599    void startCleaningPackages() {
8600        // reader
8601        synchronized (mPackages) {
8602            if (!isExternalMediaAvailable()) {
8603                return;
8604            }
8605            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8606                return;
8607            }
8608        }
8609        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8610        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8611        IActivityManager am = ActivityManagerNative.getDefault();
8612        if (am != null) {
8613            try {
8614                am.startService(null, intent, null, UserHandle.USER_OWNER);
8615            } catch (RemoteException e) {
8616            }
8617        }
8618    }
8619
8620    @Override
8621    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8622            int installFlags, String installerPackageName, VerificationParams verificationParams,
8623            String packageAbiOverride) {
8624        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8625                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8626    }
8627
8628    @Override
8629    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8630            int installFlags, String installerPackageName, VerificationParams verificationParams,
8631            String packageAbiOverride, int userId) {
8632        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8633
8634        final int callingUid = Binder.getCallingUid();
8635        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8636
8637        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8638            try {
8639                if (observer != null) {
8640                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8641                }
8642            } catch (RemoteException re) {
8643            }
8644            return;
8645        }
8646
8647        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8648            installFlags |= PackageManager.INSTALL_FROM_ADB;
8649
8650        } else {
8651            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8652            // about installerPackageName.
8653
8654            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8655            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8656        }
8657
8658        UserHandle user;
8659        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8660            user = UserHandle.ALL;
8661        } else {
8662            user = new UserHandle(userId);
8663        }
8664
8665        // Only system components can circumvent runtime permissions when installing.
8666        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
8667                && mContext.checkCallingOrSelfPermission(Manifest.permission
8668                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
8669            throw new SecurityException("You need the "
8670                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
8671                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
8672        }
8673
8674        verificationParams.setInstallerUid(callingUid);
8675
8676        final File originFile = new File(originPath);
8677        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8678
8679        final Message msg = mHandler.obtainMessage(INIT_COPY);
8680        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
8681                null, verificationParams, user, packageAbiOverride);
8682        mHandler.sendMessage(msg);
8683    }
8684
8685    void installStage(String packageName, File stagedDir, String stagedCid,
8686            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8687            String installerPackageName, int installerUid, UserHandle user) {
8688        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8689                params.referrerUri, installerUid, null);
8690
8691        final OriginInfo origin;
8692        if (stagedDir != null) {
8693            origin = OriginInfo.fromStagedFile(stagedDir);
8694        } else {
8695            origin = OriginInfo.fromStagedContainer(stagedCid);
8696        }
8697
8698        final Message msg = mHandler.obtainMessage(INIT_COPY);
8699        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
8700                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8701        mHandler.sendMessage(msg);
8702    }
8703
8704    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8705        Bundle extras = new Bundle(1);
8706        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8707
8708        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8709                packageName, extras, null, null, new int[] {userId});
8710        try {
8711            IActivityManager am = ActivityManagerNative.getDefault();
8712            final boolean isSystem =
8713                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8714            if (isSystem && am.isUserRunning(userId, false)) {
8715                // The just-installed/enabled app is bundled on the system, so presumed
8716                // to be able to run automatically without needing an explicit launch.
8717                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8718                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8719                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8720                        .setPackage(packageName);
8721                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8722                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8723            }
8724        } catch (RemoteException e) {
8725            // shouldn't happen
8726            Slog.w(TAG, "Unable to bootstrap installed package", e);
8727        }
8728    }
8729
8730    @Override
8731    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8732            int userId) {
8733        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8734        PackageSetting pkgSetting;
8735        final int uid = Binder.getCallingUid();
8736        enforceCrossUserPermission(uid, userId, true, true,
8737                "setApplicationHiddenSetting for user " + userId);
8738
8739        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8740            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8741            return false;
8742        }
8743
8744        long callingId = Binder.clearCallingIdentity();
8745        try {
8746            boolean sendAdded = false;
8747            boolean sendRemoved = false;
8748            // writer
8749            synchronized (mPackages) {
8750                pkgSetting = mSettings.mPackages.get(packageName);
8751                if (pkgSetting == null) {
8752                    return false;
8753                }
8754                if (pkgSetting.getHidden(userId) != hidden) {
8755                    pkgSetting.setHidden(hidden, userId);
8756                    mSettings.writePackageRestrictionsLPr(userId);
8757                    if (hidden) {
8758                        sendRemoved = true;
8759                    } else {
8760                        sendAdded = true;
8761                    }
8762                }
8763            }
8764            if (sendAdded) {
8765                sendPackageAddedForUser(packageName, pkgSetting, userId);
8766                return true;
8767            }
8768            if (sendRemoved) {
8769                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8770                        "hiding pkg");
8771                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8772            }
8773        } finally {
8774            Binder.restoreCallingIdentity(callingId);
8775        }
8776        return false;
8777    }
8778
8779    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8780            int userId) {
8781        final PackageRemovedInfo info = new PackageRemovedInfo();
8782        info.removedPackage = packageName;
8783        info.removedUsers = new int[] {userId};
8784        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8785        info.sendBroadcast(false, false, false);
8786    }
8787
8788    /**
8789     * Returns true if application is not found or there was an error. Otherwise it returns
8790     * the hidden state of the package for the given user.
8791     */
8792    @Override
8793    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8794        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8795        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8796                false, "getApplicationHidden for user " + userId);
8797        PackageSetting pkgSetting;
8798        long callingId = Binder.clearCallingIdentity();
8799        try {
8800            // writer
8801            synchronized (mPackages) {
8802                pkgSetting = mSettings.mPackages.get(packageName);
8803                if (pkgSetting == null) {
8804                    return true;
8805                }
8806                return pkgSetting.getHidden(userId);
8807            }
8808        } finally {
8809            Binder.restoreCallingIdentity(callingId);
8810        }
8811    }
8812
8813    /**
8814     * @hide
8815     */
8816    @Override
8817    public int installExistingPackageAsUser(String packageName, int userId) {
8818        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8819                null);
8820        PackageSetting pkgSetting;
8821        final int uid = Binder.getCallingUid();
8822        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8823                + userId);
8824        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8825            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8826        }
8827
8828        long callingId = Binder.clearCallingIdentity();
8829        try {
8830            boolean sendAdded = false;
8831
8832            // writer
8833            synchronized (mPackages) {
8834                pkgSetting = mSettings.mPackages.get(packageName);
8835                if (pkgSetting == null) {
8836                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8837                }
8838                if (!pkgSetting.getInstalled(userId)) {
8839                    pkgSetting.setInstalled(true, userId);
8840                    pkgSetting.setHidden(false, userId);
8841                    mSettings.writePackageRestrictionsLPr(userId);
8842                    sendAdded = true;
8843                }
8844            }
8845
8846            if (sendAdded) {
8847                sendPackageAddedForUser(packageName, pkgSetting, userId);
8848            }
8849        } finally {
8850            Binder.restoreCallingIdentity(callingId);
8851        }
8852
8853        return PackageManager.INSTALL_SUCCEEDED;
8854    }
8855
8856    boolean isUserRestricted(int userId, String restrictionKey) {
8857        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8858        if (restrictions.getBoolean(restrictionKey, false)) {
8859            Log.w(TAG, "User is restricted: " + restrictionKey);
8860            return true;
8861        }
8862        return false;
8863    }
8864
8865    @Override
8866    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8867        mContext.enforceCallingOrSelfPermission(
8868                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8869                "Only package verification agents can verify applications");
8870
8871        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8872        final PackageVerificationResponse response = new PackageVerificationResponse(
8873                verificationCode, Binder.getCallingUid());
8874        msg.arg1 = id;
8875        msg.obj = response;
8876        mHandler.sendMessage(msg);
8877    }
8878
8879    @Override
8880    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8881            long millisecondsToDelay) {
8882        mContext.enforceCallingOrSelfPermission(
8883                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8884                "Only package verification agents can extend verification timeouts");
8885
8886        final PackageVerificationState state = mPendingVerification.get(id);
8887        final PackageVerificationResponse response = new PackageVerificationResponse(
8888                verificationCodeAtTimeout, Binder.getCallingUid());
8889
8890        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8891            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8892        }
8893        if (millisecondsToDelay < 0) {
8894            millisecondsToDelay = 0;
8895        }
8896        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8897                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8898            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8899        }
8900
8901        if ((state != null) && !state.timeoutExtended()) {
8902            state.extendTimeout();
8903
8904            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8905            msg.arg1 = id;
8906            msg.obj = response;
8907            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8908        }
8909    }
8910
8911    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8912            int verificationCode, UserHandle user) {
8913        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8914        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8915        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8916        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8917        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8918
8919        mContext.sendBroadcastAsUser(intent, user,
8920                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8921    }
8922
8923    private ComponentName matchComponentForVerifier(String packageName,
8924            List<ResolveInfo> receivers) {
8925        ActivityInfo targetReceiver = null;
8926
8927        final int NR = receivers.size();
8928        for (int i = 0; i < NR; i++) {
8929            final ResolveInfo info = receivers.get(i);
8930            if (info.activityInfo == null) {
8931                continue;
8932            }
8933
8934            if (packageName.equals(info.activityInfo.packageName)) {
8935                targetReceiver = info.activityInfo;
8936                break;
8937            }
8938        }
8939
8940        if (targetReceiver == null) {
8941            return null;
8942        }
8943
8944        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8945    }
8946
8947    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8948            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8949        if (pkgInfo.verifiers.length == 0) {
8950            return null;
8951        }
8952
8953        final int N = pkgInfo.verifiers.length;
8954        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8955        for (int i = 0; i < N; i++) {
8956            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8957
8958            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8959                    receivers);
8960            if (comp == null) {
8961                continue;
8962            }
8963
8964            final int verifierUid = getUidForVerifier(verifierInfo);
8965            if (verifierUid == -1) {
8966                continue;
8967            }
8968
8969            if (DEBUG_VERIFY) {
8970                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8971                        + " with the correct signature");
8972            }
8973            sufficientVerifiers.add(comp);
8974            verificationState.addSufficientVerifier(verifierUid);
8975        }
8976
8977        return sufficientVerifiers;
8978    }
8979
8980    private int getUidForVerifier(VerifierInfo verifierInfo) {
8981        synchronized (mPackages) {
8982            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8983            if (pkg == null) {
8984                return -1;
8985            } else if (pkg.mSignatures.length != 1) {
8986                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8987                        + " has more than one signature; ignoring");
8988                return -1;
8989            }
8990
8991            /*
8992             * If the public key of the package's signature does not match
8993             * our expected public key, then this is a different package and
8994             * we should skip.
8995             */
8996
8997            final byte[] expectedPublicKey;
8998            try {
8999                final Signature verifierSig = pkg.mSignatures[0];
9000                final PublicKey publicKey = verifierSig.getPublicKey();
9001                expectedPublicKey = publicKey.getEncoded();
9002            } catch (CertificateException e) {
9003                return -1;
9004            }
9005
9006            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9007
9008            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9009                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9010                        + " does not have the expected public key; ignoring");
9011                return -1;
9012            }
9013
9014            return pkg.applicationInfo.uid;
9015        }
9016    }
9017
9018    @Override
9019    public void finishPackageInstall(int token) {
9020        enforceSystemOrRoot("Only the system is allowed to finish installs");
9021
9022        if (DEBUG_INSTALL) {
9023            Slog.v(TAG, "BM finishing package install for " + token);
9024        }
9025
9026        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9027        mHandler.sendMessage(msg);
9028    }
9029
9030    /**
9031     * Get the verification agent timeout.
9032     *
9033     * @return verification timeout in milliseconds
9034     */
9035    private long getVerificationTimeout() {
9036        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9037                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9038                DEFAULT_VERIFICATION_TIMEOUT);
9039    }
9040
9041    /**
9042     * Get the default verification agent response code.
9043     *
9044     * @return default verification response code
9045     */
9046    private int getDefaultVerificationResponse() {
9047        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9048                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9049                DEFAULT_VERIFICATION_RESPONSE);
9050    }
9051
9052    /**
9053     * Check whether or not package verification has been enabled.
9054     *
9055     * @return true if verification should be performed
9056     */
9057    private boolean isVerificationEnabled(int userId, int installFlags) {
9058        if (!DEFAULT_VERIFY_ENABLE) {
9059            return false;
9060        }
9061
9062        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9063
9064        // Check if installing from ADB
9065        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9066            // Do not run verification in a test harness environment
9067            if (ActivityManager.isRunningInTestHarness()) {
9068                return false;
9069            }
9070            if (ensureVerifyAppsEnabled) {
9071                return true;
9072            }
9073            // Check if the developer does not want package verification for ADB installs
9074            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9075                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9076                return false;
9077            }
9078        }
9079
9080        if (ensureVerifyAppsEnabled) {
9081            return true;
9082        }
9083
9084        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9085                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9086    }
9087
9088    @Override
9089    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9090            throws RemoteException {
9091        mContext.enforceCallingOrSelfPermission(
9092                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9093                "Only intentfilter verification agents can verify applications");
9094
9095        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9096        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9097                Binder.getCallingUid(), verificationCode, failedDomains);
9098        msg.arg1 = id;
9099        msg.obj = response;
9100        mHandler.sendMessage(msg);
9101    }
9102
9103    @Override
9104    public int getIntentVerificationStatus(String packageName, int userId) {
9105        synchronized (mPackages) {
9106            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9107        }
9108    }
9109
9110    @Override
9111    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9112        boolean result = false;
9113        synchronized (mPackages) {
9114            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9115        }
9116        scheduleWritePackageRestrictionsLocked(userId);
9117        return result;
9118    }
9119
9120    @Override
9121    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9122        synchronized (mPackages) {
9123            return mSettings.getIntentFilterVerificationsLPr(packageName);
9124        }
9125    }
9126
9127    @Override
9128    public List<IntentFilter> getAllIntentFilters(String packageName) {
9129        if (TextUtils.isEmpty(packageName)) {
9130            return Collections.<IntentFilter>emptyList();
9131        }
9132        synchronized (mPackages) {
9133            PackageParser.Package pkg = mPackages.get(packageName);
9134            if (pkg == null || pkg.activities == null) {
9135                return Collections.<IntentFilter>emptyList();
9136            }
9137            final int count = pkg.activities.size();
9138            ArrayList<IntentFilter> result = new ArrayList<>();
9139            for (int n=0; n<count; n++) {
9140                PackageParser.Activity activity = pkg.activities.get(n);
9141                if (activity.intents != null || activity.intents.size() > 0) {
9142                    result.addAll(activity.intents);
9143                }
9144            }
9145            return result;
9146        }
9147    }
9148
9149    @Override
9150    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9151        synchronized (mPackages) {
9152            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9153            result |= updateIntentVerificationStatus(packageName,
9154                    PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9155                    UserHandle.myUserId());
9156            return result;
9157        }
9158    }
9159
9160    @Override
9161    public String getDefaultBrowserPackageName(int userId) {
9162        synchronized (mPackages) {
9163            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9164        }
9165    }
9166
9167    /**
9168     * Get the "allow unknown sources" setting.
9169     *
9170     * @return the current "allow unknown sources" setting
9171     */
9172    private int getUnknownSourcesSettings() {
9173        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9174                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9175                -1);
9176    }
9177
9178    @Override
9179    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9180        final int uid = Binder.getCallingUid();
9181        // writer
9182        synchronized (mPackages) {
9183            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9184            if (targetPackageSetting == null) {
9185                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9186            }
9187
9188            PackageSetting installerPackageSetting;
9189            if (installerPackageName != null) {
9190                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9191                if (installerPackageSetting == null) {
9192                    throw new IllegalArgumentException("Unknown installer package: "
9193                            + installerPackageName);
9194                }
9195            } else {
9196                installerPackageSetting = null;
9197            }
9198
9199            Signature[] callerSignature;
9200            Object obj = mSettings.getUserIdLPr(uid);
9201            if (obj != null) {
9202                if (obj instanceof SharedUserSetting) {
9203                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9204                } else if (obj instanceof PackageSetting) {
9205                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9206                } else {
9207                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9208                }
9209            } else {
9210                throw new SecurityException("Unknown calling uid " + uid);
9211            }
9212
9213            // Verify: can't set installerPackageName to a package that is
9214            // not signed with the same cert as the caller.
9215            if (installerPackageSetting != null) {
9216                if (compareSignatures(callerSignature,
9217                        installerPackageSetting.signatures.mSignatures)
9218                        != PackageManager.SIGNATURE_MATCH) {
9219                    throw new SecurityException(
9220                            "Caller does not have same cert as new installer package "
9221                            + installerPackageName);
9222                }
9223            }
9224
9225            // Verify: if target already has an installer package, it must
9226            // be signed with the same cert as the caller.
9227            if (targetPackageSetting.installerPackageName != null) {
9228                PackageSetting setting = mSettings.mPackages.get(
9229                        targetPackageSetting.installerPackageName);
9230                // If the currently set package isn't valid, then it's always
9231                // okay to change it.
9232                if (setting != null) {
9233                    if (compareSignatures(callerSignature,
9234                            setting.signatures.mSignatures)
9235                            != PackageManager.SIGNATURE_MATCH) {
9236                        throw new SecurityException(
9237                                "Caller does not have same cert as old installer package "
9238                                + targetPackageSetting.installerPackageName);
9239                    }
9240                }
9241            }
9242
9243            // Okay!
9244            targetPackageSetting.installerPackageName = installerPackageName;
9245            scheduleWriteSettingsLocked();
9246        }
9247    }
9248
9249    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9250        // Queue up an async operation since the package installation may take a little while.
9251        mHandler.post(new Runnable() {
9252            public void run() {
9253                mHandler.removeCallbacks(this);
9254                 // Result object to be returned
9255                PackageInstalledInfo res = new PackageInstalledInfo();
9256                res.returnCode = currentStatus;
9257                res.uid = -1;
9258                res.pkg = null;
9259                res.removedInfo = new PackageRemovedInfo();
9260                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9261                    args.doPreInstall(res.returnCode);
9262                    synchronized (mInstallLock) {
9263                        installPackageLI(args, res);
9264                    }
9265                    args.doPostInstall(res.returnCode, res.uid);
9266                }
9267
9268                // A restore should be performed at this point if (a) the install
9269                // succeeded, (b) the operation is not an update, and (c) the new
9270                // package has not opted out of backup participation.
9271                final boolean update = res.removedInfo.removedPackage != null;
9272                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9273                boolean doRestore = !update
9274                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9275
9276                // Set up the post-install work request bookkeeping.  This will be used
9277                // and cleaned up by the post-install event handling regardless of whether
9278                // there's a restore pass performed.  Token values are >= 1.
9279                int token;
9280                if (mNextInstallToken < 0) mNextInstallToken = 1;
9281                token = mNextInstallToken++;
9282
9283                PostInstallData data = new PostInstallData(args, res);
9284                mRunningInstalls.put(token, data);
9285                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9286
9287                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9288                    // Pass responsibility to the Backup Manager.  It will perform a
9289                    // restore if appropriate, then pass responsibility back to the
9290                    // Package Manager to run the post-install observer callbacks
9291                    // and broadcasts.
9292                    IBackupManager bm = IBackupManager.Stub.asInterface(
9293                            ServiceManager.getService(Context.BACKUP_SERVICE));
9294                    if (bm != null) {
9295                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9296                                + " to BM for possible restore");
9297                        try {
9298                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9299                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9300                            } else {
9301                                doRestore = false;
9302                            }
9303                        } catch (RemoteException e) {
9304                            // can't happen; the backup manager is local
9305                        } catch (Exception e) {
9306                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9307                            doRestore = false;
9308                        }
9309                    } else {
9310                        Slog.e(TAG, "Backup Manager not found!");
9311                        doRestore = false;
9312                    }
9313                }
9314
9315                if (!doRestore) {
9316                    // No restore possible, or the Backup Manager was mysteriously not
9317                    // available -- just fire the post-install work request directly.
9318                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9319                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9320                    mHandler.sendMessage(msg);
9321                }
9322            }
9323        });
9324    }
9325
9326    private abstract class HandlerParams {
9327        private static final int MAX_RETRIES = 4;
9328
9329        /**
9330         * Number of times startCopy() has been attempted and had a non-fatal
9331         * error.
9332         */
9333        private int mRetries = 0;
9334
9335        /** User handle for the user requesting the information or installation. */
9336        private final UserHandle mUser;
9337
9338        HandlerParams(UserHandle user) {
9339            mUser = user;
9340        }
9341
9342        UserHandle getUser() {
9343            return mUser;
9344        }
9345
9346        final boolean startCopy() {
9347            boolean res;
9348            try {
9349                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9350
9351                if (++mRetries > MAX_RETRIES) {
9352                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9353                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9354                    handleServiceError();
9355                    return false;
9356                } else {
9357                    handleStartCopy();
9358                    res = true;
9359                }
9360            } catch (RemoteException e) {
9361                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9362                mHandler.sendEmptyMessage(MCS_RECONNECT);
9363                res = false;
9364            }
9365            handleReturnCode();
9366            return res;
9367        }
9368
9369        final void serviceError() {
9370            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9371            handleServiceError();
9372            handleReturnCode();
9373        }
9374
9375        abstract void handleStartCopy() throws RemoteException;
9376        abstract void handleServiceError();
9377        abstract void handleReturnCode();
9378    }
9379
9380    class MeasureParams extends HandlerParams {
9381        private final PackageStats mStats;
9382        private boolean mSuccess;
9383
9384        private final IPackageStatsObserver mObserver;
9385
9386        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9387            super(new UserHandle(stats.userHandle));
9388            mObserver = observer;
9389            mStats = stats;
9390        }
9391
9392        @Override
9393        public String toString() {
9394            return "MeasureParams{"
9395                + Integer.toHexString(System.identityHashCode(this))
9396                + " " + mStats.packageName + "}";
9397        }
9398
9399        @Override
9400        void handleStartCopy() throws RemoteException {
9401            synchronized (mInstallLock) {
9402                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9403            }
9404
9405            if (mSuccess) {
9406                final boolean mounted;
9407                if (Environment.isExternalStorageEmulated()) {
9408                    mounted = true;
9409                } else {
9410                    final String status = Environment.getExternalStorageState();
9411                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9412                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9413                }
9414
9415                if (mounted) {
9416                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9417
9418                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9419                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9420
9421                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9422                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9423
9424                    // Always subtract cache size, since it's a subdirectory
9425                    mStats.externalDataSize -= mStats.externalCacheSize;
9426
9427                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9428                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9429
9430                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9431                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9432                }
9433            }
9434        }
9435
9436        @Override
9437        void handleReturnCode() {
9438            if (mObserver != null) {
9439                try {
9440                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9441                } catch (RemoteException e) {
9442                    Slog.i(TAG, "Observer no longer exists.");
9443                }
9444            }
9445        }
9446
9447        @Override
9448        void handleServiceError() {
9449            Slog.e(TAG, "Could not measure application " + mStats.packageName
9450                            + " external storage");
9451        }
9452    }
9453
9454    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9455            throws RemoteException {
9456        long result = 0;
9457        for (File path : paths) {
9458            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9459        }
9460        return result;
9461    }
9462
9463    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9464        for (File path : paths) {
9465            try {
9466                mcs.clearDirectory(path.getAbsolutePath());
9467            } catch (RemoteException e) {
9468            }
9469        }
9470    }
9471
9472    static class OriginInfo {
9473        /**
9474         * Location where install is coming from, before it has been
9475         * copied/renamed into place. This could be a single monolithic APK
9476         * file, or a cluster directory. This location may be untrusted.
9477         */
9478        final File file;
9479        final String cid;
9480
9481        /**
9482         * Flag indicating that {@link #file} or {@link #cid} has already been
9483         * staged, meaning downstream users don't need to defensively copy the
9484         * contents.
9485         */
9486        final boolean staged;
9487
9488        /**
9489         * Flag indicating that {@link #file} or {@link #cid} is an already
9490         * installed app that is being moved.
9491         */
9492        final boolean existing;
9493
9494        final String resolvedPath;
9495        final File resolvedFile;
9496
9497        static OriginInfo fromNothing() {
9498            return new OriginInfo(null, null, false, false);
9499        }
9500
9501        static OriginInfo fromUntrustedFile(File file) {
9502            return new OriginInfo(file, null, false, false);
9503        }
9504
9505        static OriginInfo fromExistingFile(File file) {
9506            return new OriginInfo(file, null, false, true);
9507        }
9508
9509        static OriginInfo fromStagedFile(File file) {
9510            return new OriginInfo(file, null, true, false);
9511        }
9512
9513        static OriginInfo fromStagedContainer(String cid) {
9514            return new OriginInfo(null, cid, true, false);
9515        }
9516
9517        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9518            this.file = file;
9519            this.cid = cid;
9520            this.staged = staged;
9521            this.existing = existing;
9522
9523            if (cid != null) {
9524                resolvedPath = PackageHelper.getSdDir(cid);
9525                resolvedFile = new File(resolvedPath);
9526            } else if (file != null) {
9527                resolvedPath = file.getAbsolutePath();
9528                resolvedFile = file;
9529            } else {
9530                resolvedPath = null;
9531                resolvedFile = null;
9532            }
9533        }
9534    }
9535
9536    class MoveInfo {
9537        final int moveId;
9538        final String fromUuid;
9539        final String toUuid;
9540        final String packageName;
9541        final String dataAppName;
9542        final int appId;
9543        final String seinfo;
9544
9545        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9546                String dataAppName, int appId, String seinfo) {
9547            this.moveId = moveId;
9548            this.fromUuid = fromUuid;
9549            this.toUuid = toUuid;
9550            this.packageName = packageName;
9551            this.dataAppName = dataAppName;
9552            this.appId = appId;
9553            this.seinfo = seinfo;
9554        }
9555    }
9556
9557    class InstallParams extends HandlerParams {
9558        final OriginInfo origin;
9559        final MoveInfo move;
9560        final IPackageInstallObserver2 observer;
9561        int installFlags;
9562        final String installerPackageName;
9563        final String volumeUuid;
9564        final VerificationParams verificationParams;
9565        private InstallArgs mArgs;
9566        private int mRet;
9567        final String packageAbiOverride;
9568
9569        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
9570                int installFlags, String installerPackageName, String volumeUuid,
9571                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9572            super(user);
9573            this.origin = origin;
9574            this.move = move;
9575            this.observer = observer;
9576            this.installFlags = installFlags;
9577            this.installerPackageName = installerPackageName;
9578            this.volumeUuid = volumeUuid;
9579            this.verificationParams = verificationParams;
9580            this.packageAbiOverride = packageAbiOverride;
9581        }
9582
9583        @Override
9584        public String toString() {
9585            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9586                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9587        }
9588
9589        public ManifestDigest getManifestDigest() {
9590            if (verificationParams == null) {
9591                return null;
9592            }
9593            return verificationParams.getManifestDigest();
9594        }
9595
9596        private int installLocationPolicy(PackageInfoLite pkgLite) {
9597            String packageName = pkgLite.packageName;
9598            int installLocation = pkgLite.installLocation;
9599            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9600            // reader
9601            synchronized (mPackages) {
9602                PackageParser.Package pkg = mPackages.get(packageName);
9603                if (pkg != null) {
9604                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9605                        // Check for downgrading.
9606                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9607                            try {
9608                                checkDowngrade(pkg, pkgLite);
9609                            } catch (PackageManagerException e) {
9610                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9611                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9612                            }
9613                        }
9614                        // Check for updated system application.
9615                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9616                            if (onSd) {
9617                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9618                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9619                            }
9620                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9621                        } else {
9622                            if (onSd) {
9623                                // Install flag overrides everything.
9624                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9625                            }
9626                            // If current upgrade specifies particular preference
9627                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9628                                // Application explicitly specified internal.
9629                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9630                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9631                                // App explictly prefers external. Let policy decide
9632                            } else {
9633                                // Prefer previous location
9634                                if (isExternal(pkg)) {
9635                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9636                                }
9637                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9638                            }
9639                        }
9640                    } else {
9641                        // Invalid install. Return error code
9642                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9643                    }
9644                }
9645            }
9646            // All the special cases have been taken care of.
9647            // Return result based on recommended install location.
9648            if (onSd) {
9649                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9650            }
9651            return pkgLite.recommendedInstallLocation;
9652        }
9653
9654        /*
9655         * Invoke remote method to get package information and install
9656         * location values. Override install location based on default
9657         * policy if needed and then create install arguments based
9658         * on the install location.
9659         */
9660        public void handleStartCopy() throws RemoteException {
9661            int ret = PackageManager.INSTALL_SUCCEEDED;
9662
9663            // If we're already staged, we've firmly committed to an install location
9664            if (origin.staged) {
9665                if (origin.file != null) {
9666                    installFlags |= PackageManager.INSTALL_INTERNAL;
9667                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9668                } else if (origin.cid != null) {
9669                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9670                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9671                } else {
9672                    throw new IllegalStateException("Invalid stage location");
9673                }
9674            }
9675
9676            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9677            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9678
9679            PackageInfoLite pkgLite = null;
9680
9681            if (onInt && onSd) {
9682                // Check if both bits are set.
9683                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9684                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9685            } else {
9686                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9687                        packageAbiOverride);
9688
9689                /*
9690                 * If we have too little free space, try to free cache
9691                 * before giving up.
9692                 */
9693                if (!origin.staged && pkgLite.recommendedInstallLocation
9694                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9695                    // TODO: focus freeing disk space on the target device
9696                    final StorageManager storage = StorageManager.from(mContext);
9697                    final long lowThreshold = storage.getStorageLowBytes(
9698                            Environment.getDataDirectory());
9699
9700                    final long sizeBytes = mContainerService.calculateInstalledSize(
9701                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9702
9703                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
9704                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9705                                installFlags, packageAbiOverride);
9706                    }
9707
9708                    /*
9709                     * The cache free must have deleted the file we
9710                     * downloaded to install.
9711                     *
9712                     * TODO: fix the "freeCache" call to not delete
9713                     *       the file we care about.
9714                     */
9715                    if (pkgLite.recommendedInstallLocation
9716                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9717                        pkgLite.recommendedInstallLocation
9718                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9719                    }
9720                }
9721            }
9722
9723            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9724                int loc = pkgLite.recommendedInstallLocation;
9725                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9726                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9727                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9728                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9729                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9730                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9731                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9732                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9733                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9734                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9735                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9736                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9737                } else {
9738                    // Override with defaults if needed.
9739                    loc = installLocationPolicy(pkgLite);
9740                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9741                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9742                    } else if (!onSd && !onInt) {
9743                        // Override install location with flags
9744                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9745                            // Set the flag to install on external media.
9746                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9747                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9748                        } else {
9749                            // Make sure the flag for installing on external
9750                            // media is unset
9751                            installFlags |= PackageManager.INSTALL_INTERNAL;
9752                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9753                        }
9754                    }
9755                }
9756            }
9757
9758            final InstallArgs args = createInstallArgs(this);
9759            mArgs = args;
9760
9761            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9762                 /*
9763                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9764                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9765                 */
9766                int userIdentifier = getUser().getIdentifier();
9767                if (userIdentifier == UserHandle.USER_ALL
9768                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9769                    userIdentifier = UserHandle.USER_OWNER;
9770                }
9771
9772                /*
9773                 * Determine if we have any installed package verifiers. If we
9774                 * do, then we'll defer to them to verify the packages.
9775                 */
9776                final int requiredUid = mRequiredVerifierPackage == null ? -1
9777                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9778                if (!origin.existing && requiredUid != -1
9779                        && isVerificationEnabled(userIdentifier, installFlags)) {
9780                    final Intent verification = new Intent(
9781                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9782                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9783                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9784                            PACKAGE_MIME_TYPE);
9785                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9786
9787                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9788                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9789                            0 /* TODO: Which userId? */);
9790
9791                    if (DEBUG_VERIFY) {
9792                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9793                                + verification.toString() + " with " + pkgLite.verifiers.length
9794                                + " optional verifiers");
9795                    }
9796
9797                    final int verificationId = mPendingVerificationToken++;
9798
9799                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9800
9801                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9802                            installerPackageName);
9803
9804                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9805                            installFlags);
9806
9807                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9808                            pkgLite.packageName);
9809
9810                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9811                            pkgLite.versionCode);
9812
9813                    if (verificationParams != null) {
9814                        if (verificationParams.getVerificationURI() != null) {
9815                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9816                                 verificationParams.getVerificationURI());
9817                        }
9818                        if (verificationParams.getOriginatingURI() != null) {
9819                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9820                                  verificationParams.getOriginatingURI());
9821                        }
9822                        if (verificationParams.getReferrer() != null) {
9823                            verification.putExtra(Intent.EXTRA_REFERRER,
9824                                  verificationParams.getReferrer());
9825                        }
9826                        if (verificationParams.getOriginatingUid() >= 0) {
9827                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9828                                  verificationParams.getOriginatingUid());
9829                        }
9830                        if (verificationParams.getInstallerUid() >= 0) {
9831                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9832                                  verificationParams.getInstallerUid());
9833                        }
9834                    }
9835
9836                    final PackageVerificationState verificationState = new PackageVerificationState(
9837                            requiredUid, args);
9838
9839                    mPendingVerification.append(verificationId, verificationState);
9840
9841                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9842                            receivers, verificationState);
9843
9844                    /*
9845                     * If any sufficient verifiers were listed in the package
9846                     * manifest, attempt to ask them.
9847                     */
9848                    if (sufficientVerifiers != null) {
9849                        final int N = sufficientVerifiers.size();
9850                        if (N == 0) {
9851                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9852                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9853                        } else {
9854                            for (int i = 0; i < N; i++) {
9855                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9856
9857                                final Intent sufficientIntent = new Intent(verification);
9858                                sufficientIntent.setComponent(verifierComponent);
9859
9860                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9861                            }
9862                        }
9863                    }
9864
9865                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9866                            mRequiredVerifierPackage, receivers);
9867                    if (ret == PackageManager.INSTALL_SUCCEEDED
9868                            && mRequiredVerifierPackage != null) {
9869                        /*
9870                         * Send the intent to the required verification agent,
9871                         * but only start the verification timeout after the
9872                         * target BroadcastReceivers have run.
9873                         */
9874                        verification.setComponent(requiredVerifierComponent);
9875                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9876                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9877                                new BroadcastReceiver() {
9878                                    @Override
9879                                    public void onReceive(Context context, Intent intent) {
9880                                        final Message msg = mHandler
9881                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9882                                        msg.arg1 = verificationId;
9883                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9884                                    }
9885                                }, null, 0, null, null);
9886
9887                        /*
9888                         * We don't want the copy to proceed until verification
9889                         * succeeds, so null out this field.
9890                         */
9891                        mArgs = null;
9892                    }
9893                } else {
9894                    /*
9895                     * No package verification is enabled, so immediately start
9896                     * the remote call to initiate copy using temporary file.
9897                     */
9898                    ret = args.copyApk(mContainerService, true);
9899                }
9900            }
9901
9902            mRet = ret;
9903        }
9904
9905        @Override
9906        void handleReturnCode() {
9907            // If mArgs is null, then MCS couldn't be reached. When it
9908            // reconnects, it will try again to install. At that point, this
9909            // will succeed.
9910            if (mArgs != null) {
9911                processPendingInstall(mArgs, mRet);
9912            }
9913        }
9914
9915        @Override
9916        void handleServiceError() {
9917            mArgs = createInstallArgs(this);
9918            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9919        }
9920
9921        public boolean isForwardLocked() {
9922            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9923        }
9924    }
9925
9926    /**
9927     * Used during creation of InstallArgs
9928     *
9929     * @param installFlags package installation flags
9930     * @return true if should be installed on external storage
9931     */
9932    private static boolean installOnExternalAsec(int installFlags) {
9933        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9934            return false;
9935        }
9936        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9937            return true;
9938        }
9939        return false;
9940    }
9941
9942    /**
9943     * Used during creation of InstallArgs
9944     *
9945     * @param installFlags package installation flags
9946     * @return true if should be installed as forward locked
9947     */
9948    private static boolean installForwardLocked(int installFlags) {
9949        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9950    }
9951
9952    private InstallArgs createInstallArgs(InstallParams params) {
9953        if (params.move != null) {
9954            return new MoveInstallArgs(params);
9955        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
9956            return new AsecInstallArgs(params);
9957        } else {
9958            return new FileInstallArgs(params);
9959        }
9960    }
9961
9962    /**
9963     * Create args that describe an existing installed package. Typically used
9964     * when cleaning up old installs, or used as a move source.
9965     */
9966    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9967            String resourcePath, String[] instructionSets) {
9968        final boolean isInAsec;
9969        if (installOnExternalAsec(installFlags)) {
9970            /* Apps on SD card are always in ASEC containers. */
9971            isInAsec = true;
9972        } else if (installForwardLocked(installFlags)
9973                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9974            /*
9975             * Forward-locked apps are only in ASEC containers if they're the
9976             * new style
9977             */
9978            isInAsec = true;
9979        } else {
9980            isInAsec = false;
9981        }
9982
9983        if (isInAsec) {
9984            return new AsecInstallArgs(codePath, instructionSets,
9985                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
9986        } else {
9987            return new FileInstallArgs(codePath, resourcePath, instructionSets);
9988        }
9989    }
9990
9991    static abstract class InstallArgs {
9992        /** @see InstallParams#origin */
9993        final OriginInfo origin;
9994        /** @see InstallParams#move */
9995        final MoveInfo move;
9996
9997        final IPackageInstallObserver2 observer;
9998        // Always refers to PackageManager flags only
9999        final int installFlags;
10000        final String installerPackageName;
10001        final String volumeUuid;
10002        final ManifestDigest manifestDigest;
10003        final UserHandle user;
10004        final String abiOverride;
10005
10006        // The list of instruction sets supported by this app. This is currently
10007        // only used during the rmdex() phase to clean up resources. We can get rid of this
10008        // if we move dex files under the common app path.
10009        /* nullable */ String[] instructionSets;
10010
10011        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10012                int installFlags, String installerPackageName, String volumeUuid,
10013                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10014                String abiOverride) {
10015            this.origin = origin;
10016            this.move = move;
10017            this.installFlags = installFlags;
10018            this.observer = observer;
10019            this.installerPackageName = installerPackageName;
10020            this.volumeUuid = volumeUuid;
10021            this.manifestDigest = manifestDigest;
10022            this.user = user;
10023            this.instructionSets = instructionSets;
10024            this.abiOverride = abiOverride;
10025        }
10026
10027        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10028        abstract int doPreInstall(int status);
10029
10030        /**
10031         * Rename package into final resting place. All paths on the given
10032         * scanned package should be updated to reflect the rename.
10033         */
10034        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10035        abstract int doPostInstall(int status, int uid);
10036
10037        /** @see PackageSettingBase#codePathString */
10038        abstract String getCodePath();
10039        /** @see PackageSettingBase#resourcePathString */
10040        abstract String getResourcePath();
10041
10042        // Need installer lock especially for dex file removal.
10043        abstract void cleanUpResourcesLI();
10044        abstract boolean doPostDeleteLI(boolean delete);
10045
10046        /**
10047         * Called before the source arguments are copied. This is used mostly
10048         * for MoveParams when it needs to read the source file to put it in the
10049         * destination.
10050         */
10051        int doPreCopy() {
10052            return PackageManager.INSTALL_SUCCEEDED;
10053        }
10054
10055        /**
10056         * Called after the source arguments are copied. This is used mostly for
10057         * MoveParams when it needs to read the source file to put it in the
10058         * destination.
10059         *
10060         * @return
10061         */
10062        int doPostCopy(int uid) {
10063            return PackageManager.INSTALL_SUCCEEDED;
10064        }
10065
10066        protected boolean isFwdLocked() {
10067            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10068        }
10069
10070        protected boolean isExternalAsec() {
10071            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10072        }
10073
10074        UserHandle getUser() {
10075            return user;
10076        }
10077    }
10078
10079    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10080        if (!allCodePaths.isEmpty()) {
10081            if (instructionSets == null) {
10082                throw new IllegalStateException("instructionSet == null");
10083            }
10084            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10085            for (String codePath : allCodePaths) {
10086                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10087                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10088                    if (retCode < 0) {
10089                        Slog.w(TAG, "Couldn't remove dex file for package: "
10090                                + " at location " + codePath + ", retcode=" + retCode);
10091                        // we don't consider this to be a failure of the core package deletion
10092                    }
10093                }
10094            }
10095        }
10096    }
10097
10098    /**
10099     * Logic to handle installation of non-ASEC applications, including copying
10100     * and renaming logic.
10101     */
10102    class FileInstallArgs extends InstallArgs {
10103        private File codeFile;
10104        private File resourceFile;
10105
10106        // Example topology:
10107        // /data/app/com.example/base.apk
10108        // /data/app/com.example/split_foo.apk
10109        // /data/app/com.example/lib/arm/libfoo.so
10110        // /data/app/com.example/lib/arm64/libfoo.so
10111        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10112
10113        /** New install */
10114        FileInstallArgs(InstallParams params) {
10115            super(params.origin, params.move, params.observer, params.installFlags,
10116                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10117                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10118            if (isFwdLocked()) {
10119                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10120            }
10121        }
10122
10123        /** Existing install */
10124        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10125            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10126                    null);
10127            this.codeFile = (codePath != null) ? new File(codePath) : null;
10128            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10129        }
10130
10131        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10132            if (origin.staged) {
10133                Slog.d(TAG, origin.file + " already staged; skipping copy");
10134                codeFile = origin.file;
10135                resourceFile = origin.file;
10136                return PackageManager.INSTALL_SUCCEEDED;
10137            }
10138
10139            try {
10140                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10141                codeFile = tempDir;
10142                resourceFile = tempDir;
10143            } catch (IOException e) {
10144                Slog.w(TAG, "Failed to create copy file: " + e);
10145                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10146            }
10147
10148            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10149                @Override
10150                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10151                    if (!FileUtils.isValidExtFilename(name)) {
10152                        throw new IllegalArgumentException("Invalid filename: " + name);
10153                    }
10154                    try {
10155                        final File file = new File(codeFile, name);
10156                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10157                                O_RDWR | O_CREAT, 0644);
10158                        Os.chmod(file.getAbsolutePath(), 0644);
10159                        return new ParcelFileDescriptor(fd);
10160                    } catch (ErrnoException e) {
10161                        throw new RemoteException("Failed to open: " + e.getMessage());
10162                    }
10163                }
10164            };
10165
10166            int ret = PackageManager.INSTALL_SUCCEEDED;
10167            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10168            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10169                Slog.e(TAG, "Failed to copy package");
10170                return ret;
10171            }
10172
10173            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10174            NativeLibraryHelper.Handle handle = null;
10175            try {
10176                handle = NativeLibraryHelper.Handle.create(codeFile);
10177                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10178                        abiOverride);
10179            } catch (IOException e) {
10180                Slog.e(TAG, "Copying native libraries failed", e);
10181                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10182            } finally {
10183                IoUtils.closeQuietly(handle);
10184            }
10185
10186            return ret;
10187        }
10188
10189        int doPreInstall(int status) {
10190            if (status != PackageManager.INSTALL_SUCCEEDED) {
10191                cleanUp();
10192            }
10193            return status;
10194        }
10195
10196        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10197            if (status != PackageManager.INSTALL_SUCCEEDED) {
10198                cleanUp();
10199                return false;
10200            }
10201
10202            final File targetDir = codeFile.getParentFile();
10203            final File beforeCodeFile = codeFile;
10204            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10205
10206            Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10207            try {
10208                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10209            } catch (ErrnoException e) {
10210                Slog.d(TAG, "Failed to rename", e);
10211                return false;
10212            }
10213
10214            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10215                Slog.d(TAG, "Failed to restorecon");
10216                return false;
10217            }
10218
10219            // Reflect the rename internally
10220            codeFile = afterCodeFile;
10221            resourceFile = afterCodeFile;
10222
10223            // Reflect the rename in scanned details
10224            pkg.codePath = afterCodeFile.getAbsolutePath();
10225            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10226                    pkg.baseCodePath);
10227            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10228                    pkg.splitCodePaths);
10229
10230            // Reflect the rename in app info
10231            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10232            pkg.applicationInfo.setCodePath(pkg.codePath);
10233            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10234            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10235            pkg.applicationInfo.setResourcePath(pkg.codePath);
10236            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10237            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10238
10239            return true;
10240        }
10241
10242        int doPostInstall(int status, int uid) {
10243            if (status != PackageManager.INSTALL_SUCCEEDED) {
10244                cleanUp();
10245            }
10246            return status;
10247        }
10248
10249        @Override
10250        String getCodePath() {
10251            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10252        }
10253
10254        @Override
10255        String getResourcePath() {
10256            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10257        }
10258
10259        private boolean cleanUp() {
10260            if (codeFile == null || !codeFile.exists()) {
10261                return false;
10262            }
10263
10264            if (codeFile.isDirectory()) {
10265                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10266            } else {
10267                codeFile.delete();
10268            }
10269
10270            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10271                resourceFile.delete();
10272            }
10273
10274            return true;
10275        }
10276
10277        void cleanUpResourcesLI() {
10278            // Try enumerating all code paths before deleting
10279            List<String> allCodePaths = Collections.EMPTY_LIST;
10280            if (codeFile != null && codeFile.exists()) {
10281                try {
10282                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10283                    allCodePaths = pkg.getAllCodePaths();
10284                } catch (PackageParserException e) {
10285                    // Ignored; we tried our best
10286                }
10287            }
10288
10289            cleanUp();
10290            removeDexFiles(allCodePaths, instructionSets);
10291        }
10292
10293        boolean doPostDeleteLI(boolean delete) {
10294            // XXX err, shouldn't we respect the delete flag?
10295            cleanUpResourcesLI();
10296            return true;
10297        }
10298    }
10299
10300    private boolean isAsecExternal(String cid) {
10301        final String asecPath = PackageHelper.getSdFilesystem(cid);
10302        return !asecPath.startsWith(mAsecInternalPath);
10303    }
10304
10305    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10306            PackageManagerException {
10307        if (copyRet < 0) {
10308            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10309                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10310                throw new PackageManagerException(copyRet, message);
10311            }
10312        }
10313    }
10314
10315    /**
10316     * Extract the MountService "container ID" from the full code path of an
10317     * .apk.
10318     */
10319    static String cidFromCodePath(String fullCodePath) {
10320        int eidx = fullCodePath.lastIndexOf("/");
10321        String subStr1 = fullCodePath.substring(0, eidx);
10322        int sidx = subStr1.lastIndexOf("/");
10323        return subStr1.substring(sidx+1, eidx);
10324    }
10325
10326    /**
10327     * Logic to handle installation of ASEC applications, including copying and
10328     * renaming logic.
10329     */
10330    class AsecInstallArgs extends InstallArgs {
10331        static final String RES_FILE_NAME = "pkg.apk";
10332        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10333
10334        String cid;
10335        String packagePath;
10336        String resourcePath;
10337
10338        /** New install */
10339        AsecInstallArgs(InstallParams params) {
10340            super(params.origin, params.move, params.observer, params.installFlags,
10341                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10342                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10343        }
10344
10345        /** Existing install */
10346        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10347                        boolean isExternal, boolean isForwardLocked) {
10348            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10349                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10350                    instructionSets, null);
10351            // Hackily pretend we're still looking at a full code path
10352            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10353                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10354            }
10355
10356            // Extract cid from fullCodePath
10357            int eidx = fullCodePath.lastIndexOf("/");
10358            String subStr1 = fullCodePath.substring(0, eidx);
10359            int sidx = subStr1.lastIndexOf("/");
10360            cid = subStr1.substring(sidx+1, eidx);
10361            setMountPath(subStr1);
10362        }
10363
10364        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10365            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10366                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10367                    instructionSets, null);
10368            this.cid = cid;
10369            setMountPath(PackageHelper.getSdDir(cid));
10370        }
10371
10372        void createCopyFile() {
10373            cid = mInstallerService.allocateExternalStageCidLegacy();
10374        }
10375
10376        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10377            if (origin.staged) {
10378                Slog.d(TAG, origin.cid + " already staged; skipping copy");
10379                cid = origin.cid;
10380                setMountPath(PackageHelper.getSdDir(cid));
10381                return PackageManager.INSTALL_SUCCEEDED;
10382            }
10383
10384            if (temp) {
10385                createCopyFile();
10386            } else {
10387                /*
10388                 * Pre-emptively destroy the container since it's destroyed if
10389                 * copying fails due to it existing anyway.
10390                 */
10391                PackageHelper.destroySdDir(cid);
10392            }
10393
10394            final String newMountPath = imcs.copyPackageToContainer(
10395                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10396                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10397
10398            if (newMountPath != null) {
10399                setMountPath(newMountPath);
10400                return PackageManager.INSTALL_SUCCEEDED;
10401            } else {
10402                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10403            }
10404        }
10405
10406        @Override
10407        String getCodePath() {
10408            return packagePath;
10409        }
10410
10411        @Override
10412        String getResourcePath() {
10413            return resourcePath;
10414        }
10415
10416        int doPreInstall(int status) {
10417            if (status != PackageManager.INSTALL_SUCCEEDED) {
10418                // Destroy container
10419                PackageHelper.destroySdDir(cid);
10420            } else {
10421                boolean mounted = PackageHelper.isContainerMounted(cid);
10422                if (!mounted) {
10423                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10424                            Process.SYSTEM_UID);
10425                    if (newMountPath != null) {
10426                        setMountPath(newMountPath);
10427                    } else {
10428                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10429                    }
10430                }
10431            }
10432            return status;
10433        }
10434
10435        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10436            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10437            String newMountPath = null;
10438            if (PackageHelper.isContainerMounted(cid)) {
10439                // Unmount the container
10440                if (!PackageHelper.unMountSdDir(cid)) {
10441                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10442                    return false;
10443                }
10444            }
10445            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10446                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10447                        " which might be stale. Will try to clean up.");
10448                // Clean up the stale container and proceed to recreate.
10449                if (!PackageHelper.destroySdDir(newCacheId)) {
10450                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10451                    return false;
10452                }
10453                // Successfully cleaned up stale container. Try to rename again.
10454                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10455                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10456                            + " inspite of cleaning it up.");
10457                    return false;
10458                }
10459            }
10460            if (!PackageHelper.isContainerMounted(newCacheId)) {
10461                Slog.w(TAG, "Mounting container " + newCacheId);
10462                newMountPath = PackageHelper.mountSdDir(newCacheId,
10463                        getEncryptKey(), Process.SYSTEM_UID);
10464            } else {
10465                newMountPath = PackageHelper.getSdDir(newCacheId);
10466            }
10467            if (newMountPath == null) {
10468                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10469                return false;
10470            }
10471            Log.i(TAG, "Succesfully renamed " + cid +
10472                    " to " + newCacheId +
10473                    " at new path: " + newMountPath);
10474            cid = newCacheId;
10475
10476            final File beforeCodeFile = new File(packagePath);
10477            setMountPath(newMountPath);
10478            final File afterCodeFile = new File(packagePath);
10479
10480            // Reflect the rename in scanned details
10481            pkg.codePath = afterCodeFile.getAbsolutePath();
10482            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10483                    pkg.baseCodePath);
10484            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10485                    pkg.splitCodePaths);
10486
10487            // Reflect the rename in app info
10488            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10489            pkg.applicationInfo.setCodePath(pkg.codePath);
10490            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10491            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10492            pkg.applicationInfo.setResourcePath(pkg.codePath);
10493            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10494            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10495
10496            return true;
10497        }
10498
10499        private void setMountPath(String mountPath) {
10500            final File mountFile = new File(mountPath);
10501
10502            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10503            if (monolithicFile.exists()) {
10504                packagePath = monolithicFile.getAbsolutePath();
10505                if (isFwdLocked()) {
10506                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10507                } else {
10508                    resourcePath = packagePath;
10509                }
10510            } else {
10511                packagePath = mountFile.getAbsolutePath();
10512                resourcePath = packagePath;
10513            }
10514        }
10515
10516        int doPostInstall(int status, int uid) {
10517            if (status != PackageManager.INSTALL_SUCCEEDED) {
10518                cleanUp();
10519            } else {
10520                final int groupOwner;
10521                final String protectedFile;
10522                if (isFwdLocked()) {
10523                    groupOwner = UserHandle.getSharedAppGid(uid);
10524                    protectedFile = RES_FILE_NAME;
10525                } else {
10526                    groupOwner = -1;
10527                    protectedFile = null;
10528                }
10529
10530                if (uid < Process.FIRST_APPLICATION_UID
10531                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10532                    Slog.e(TAG, "Failed to finalize " + cid);
10533                    PackageHelper.destroySdDir(cid);
10534                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10535                }
10536
10537                boolean mounted = PackageHelper.isContainerMounted(cid);
10538                if (!mounted) {
10539                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10540                }
10541            }
10542            return status;
10543        }
10544
10545        private void cleanUp() {
10546            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10547
10548            // Destroy secure container
10549            PackageHelper.destroySdDir(cid);
10550        }
10551
10552        private List<String> getAllCodePaths() {
10553            final File codeFile = new File(getCodePath());
10554            if (codeFile != null && codeFile.exists()) {
10555                try {
10556                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10557                    return pkg.getAllCodePaths();
10558                } catch (PackageParserException e) {
10559                    // Ignored; we tried our best
10560                }
10561            }
10562            return Collections.EMPTY_LIST;
10563        }
10564
10565        void cleanUpResourcesLI() {
10566            // Enumerate all code paths before deleting
10567            cleanUpResourcesLI(getAllCodePaths());
10568        }
10569
10570        private void cleanUpResourcesLI(List<String> allCodePaths) {
10571            cleanUp();
10572            removeDexFiles(allCodePaths, instructionSets);
10573        }
10574
10575        String getPackageName() {
10576            return getAsecPackageName(cid);
10577        }
10578
10579        boolean doPostDeleteLI(boolean delete) {
10580            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10581            final List<String> allCodePaths = getAllCodePaths();
10582            boolean mounted = PackageHelper.isContainerMounted(cid);
10583            if (mounted) {
10584                // Unmount first
10585                if (PackageHelper.unMountSdDir(cid)) {
10586                    mounted = false;
10587                }
10588            }
10589            if (!mounted && delete) {
10590                cleanUpResourcesLI(allCodePaths);
10591            }
10592            return !mounted;
10593        }
10594
10595        @Override
10596        int doPreCopy() {
10597            if (isFwdLocked()) {
10598                if (!PackageHelper.fixSdPermissions(cid,
10599                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10600                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10601                }
10602            }
10603
10604            return PackageManager.INSTALL_SUCCEEDED;
10605        }
10606
10607        @Override
10608        int doPostCopy(int uid) {
10609            if (isFwdLocked()) {
10610                if (uid < Process.FIRST_APPLICATION_UID
10611                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10612                                RES_FILE_NAME)) {
10613                    Slog.e(TAG, "Failed to finalize " + cid);
10614                    PackageHelper.destroySdDir(cid);
10615                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10616                }
10617            }
10618
10619            return PackageManager.INSTALL_SUCCEEDED;
10620        }
10621    }
10622
10623    /**
10624     * Logic to handle movement of existing installed applications.
10625     */
10626    class MoveInstallArgs extends InstallArgs {
10627        private File codeFile;
10628        private File resourceFile;
10629
10630        /** New install */
10631        MoveInstallArgs(InstallParams params) {
10632            super(params.origin, params.move, params.observer, params.installFlags,
10633                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10634                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10635        }
10636
10637        int copyApk(IMediaContainerService imcs, boolean temp) {
10638            Slog.d(TAG, "Moving " + move.packageName + " from " + move.fromUuid + " to "
10639                    + move.toUuid);
10640            synchronized (mInstaller) {
10641                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
10642                        move.dataAppName, move.appId, move.seinfo) != 0) {
10643                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10644                }
10645            }
10646
10647            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
10648            resourceFile = codeFile;
10649            Slog.d(TAG, "codeFile after move is " + codeFile);
10650
10651            return PackageManager.INSTALL_SUCCEEDED;
10652        }
10653
10654        int doPreInstall(int status) {
10655            if (status != PackageManager.INSTALL_SUCCEEDED) {
10656                cleanUp();
10657            }
10658            return status;
10659        }
10660
10661        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10662            if (status != PackageManager.INSTALL_SUCCEEDED) {
10663                cleanUp();
10664                return false;
10665            }
10666
10667            // Reflect the move in app info
10668            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10669            pkg.applicationInfo.setCodePath(pkg.codePath);
10670            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10671            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10672            pkg.applicationInfo.setResourcePath(pkg.codePath);
10673            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10674            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10675
10676            return true;
10677        }
10678
10679        int doPostInstall(int status, int uid) {
10680            if (status != PackageManager.INSTALL_SUCCEEDED) {
10681                cleanUp();
10682            }
10683            return status;
10684        }
10685
10686        @Override
10687        String getCodePath() {
10688            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10689        }
10690
10691        @Override
10692        String getResourcePath() {
10693            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10694        }
10695
10696        private boolean cleanUp() {
10697            if (codeFile == null || !codeFile.exists()) {
10698                return false;
10699            }
10700
10701            if (codeFile.isDirectory()) {
10702                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10703            } else {
10704                codeFile.delete();
10705            }
10706
10707            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10708                resourceFile.delete();
10709            }
10710
10711            return true;
10712        }
10713
10714        void cleanUpResourcesLI() {
10715            cleanUp();
10716        }
10717
10718        boolean doPostDeleteLI(boolean delete) {
10719            // XXX err, shouldn't we respect the delete flag?
10720            cleanUpResourcesLI();
10721            return true;
10722        }
10723    }
10724
10725    static String getAsecPackageName(String packageCid) {
10726        int idx = packageCid.lastIndexOf("-");
10727        if (idx == -1) {
10728            return packageCid;
10729        }
10730        return packageCid.substring(0, idx);
10731    }
10732
10733    // Utility method used to create code paths based on package name and available index.
10734    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
10735        String idxStr = "";
10736        int idx = 1;
10737        // Fall back to default value of idx=1 if prefix is not
10738        // part of oldCodePath
10739        if (oldCodePath != null) {
10740            String subStr = oldCodePath;
10741            // Drop the suffix right away
10742            if (suffix != null && subStr.endsWith(suffix)) {
10743                subStr = subStr.substring(0, subStr.length() - suffix.length());
10744            }
10745            // If oldCodePath already contains prefix find out the
10746            // ending index to either increment or decrement.
10747            int sidx = subStr.lastIndexOf(prefix);
10748            if (sidx != -1) {
10749                subStr = subStr.substring(sidx + prefix.length());
10750                if (subStr != null) {
10751                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10752                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10753                    }
10754                    try {
10755                        idx = Integer.parseInt(subStr);
10756                        if (idx <= 1) {
10757                            idx++;
10758                        } else {
10759                            idx--;
10760                        }
10761                    } catch(NumberFormatException e) {
10762                    }
10763                }
10764            }
10765        }
10766        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10767        return prefix + idxStr;
10768    }
10769
10770    private File getNextCodePath(File targetDir, String packageName) {
10771        int suffix = 1;
10772        File result;
10773        do {
10774            result = new File(targetDir, packageName + "-" + suffix);
10775            suffix++;
10776        } while (result.exists());
10777        return result;
10778    }
10779
10780    // Utility method that returns the relative package path with respect
10781    // to the installation directory. Like say for /data/data/com.test-1.apk
10782    // string com.test-1 is returned.
10783    static String deriveCodePathName(String codePath) {
10784        if (codePath == null) {
10785            return null;
10786        }
10787        final File codeFile = new File(codePath);
10788        final String name = codeFile.getName();
10789        if (codeFile.isDirectory()) {
10790            return name;
10791        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10792            final int lastDot = name.lastIndexOf('.');
10793            return name.substring(0, lastDot);
10794        } else {
10795            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10796            return null;
10797        }
10798    }
10799
10800    class PackageInstalledInfo {
10801        String name;
10802        int uid;
10803        // The set of users that originally had this package installed.
10804        int[] origUsers;
10805        // The set of users that now have this package installed.
10806        int[] newUsers;
10807        PackageParser.Package pkg;
10808        int returnCode;
10809        String returnMsg;
10810        PackageRemovedInfo removedInfo;
10811
10812        public void setError(int code, String msg) {
10813            returnCode = code;
10814            returnMsg = msg;
10815            Slog.w(TAG, msg);
10816        }
10817
10818        public void setError(String msg, PackageParserException e) {
10819            returnCode = e.error;
10820            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10821            Slog.w(TAG, msg, e);
10822        }
10823
10824        public void setError(String msg, PackageManagerException e) {
10825            returnCode = e.error;
10826            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10827            Slog.w(TAG, msg, e);
10828        }
10829
10830        // In some error cases we want to convey more info back to the observer
10831        String origPackage;
10832        String origPermission;
10833    }
10834
10835    /*
10836     * Install a non-existing package.
10837     */
10838    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
10839            UserHandle user, String installerPackageName, String volumeUuid,
10840            PackageInstalledInfo res) {
10841        // Remember this for later, in case we need to rollback this install
10842        String pkgName = pkg.packageName;
10843
10844        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10845        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
10846                UserHandle.USER_OWNER).exists();
10847        synchronized(mPackages) {
10848            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10849                // A package with the same name is already installed, though
10850                // it has been renamed to an older name.  The package we
10851                // are trying to install should be installed as an update to
10852                // the existing one, but that has not been requested, so bail.
10853                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10854                        + " without first uninstalling package running as "
10855                        + mSettings.mRenamedPackages.get(pkgName));
10856                return;
10857            }
10858            if (mPackages.containsKey(pkgName)) {
10859                // Don't allow installation over an existing package with the same name.
10860                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10861                        + " without first uninstalling.");
10862                return;
10863            }
10864        }
10865
10866        try {
10867            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10868                    System.currentTimeMillis(), user);
10869
10870            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
10871            // delete the partially installed application. the data directory will have to be
10872            // restored if it was already existing
10873            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10874                // remove package from internal structures.  Note that we want deletePackageX to
10875                // delete the package data and cache directories that it created in
10876                // scanPackageLocked, unless those directories existed before we even tried to
10877                // install.
10878                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10879                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10880                                res.removedInfo, true);
10881            }
10882
10883        } catch (PackageManagerException e) {
10884            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10885        }
10886    }
10887
10888    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10889        // Upgrade keysets are being used.  Determine if new package has a superset of the
10890        // required keys.
10891        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10892        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10893        for (int i = 0; i < upgradeKeySets.length; i++) {
10894            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10895            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10896                return true;
10897            }
10898        }
10899        return false;
10900    }
10901
10902    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
10903            UserHandle user, String installerPackageName, String volumeUuid,
10904            PackageInstalledInfo res) {
10905        final PackageParser.Package oldPackage;
10906        final String pkgName = pkg.packageName;
10907        final int[] allUsers;
10908        final boolean[] perUserInstalled;
10909        final boolean weFroze;
10910
10911        // First find the old package info and check signatures
10912        synchronized(mPackages) {
10913            oldPackage = mPackages.get(pkgName);
10914            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10915            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10916            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10917                // default to original signature matching
10918                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10919                    != PackageManager.SIGNATURE_MATCH) {
10920                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10921                            "New package has a different signature: " + pkgName);
10922                    return;
10923                }
10924            } else {
10925                if(!checkUpgradeKeySetLP(ps, pkg)) {
10926                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10927                            "New package not signed by keys specified by upgrade-keysets: "
10928                            + pkgName);
10929                    return;
10930                }
10931            }
10932
10933            // In case of rollback, remember per-user/profile install state
10934            allUsers = sUserManager.getUserIds();
10935            perUserInstalled = new boolean[allUsers.length];
10936            for (int i = 0; i < allUsers.length; i++) {
10937                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10938            }
10939
10940            // Mark the app as frozen to prevent launching during the upgrade
10941            // process, and then kill all running instances
10942            if (!ps.frozen) {
10943                ps.frozen = true;
10944                weFroze = true;
10945            } else {
10946                weFroze = false;
10947            }
10948        }
10949
10950        // Now that we're guarded by frozen state, kill app during upgrade
10951        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
10952
10953        try {
10954            boolean sysPkg = (isSystemApp(oldPackage));
10955            if (sysPkg) {
10956                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10957                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
10958            } else {
10959                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10960                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
10961            }
10962        } finally {
10963            // Regardless of success or failure of upgrade steps above, always
10964            // unfreeze the package if we froze it
10965            if (weFroze) {
10966                unfreezePackage(pkgName);
10967            }
10968        }
10969    }
10970
10971    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10972            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10973            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
10974            String volumeUuid, PackageInstalledInfo res) {
10975        String pkgName = deletedPackage.packageName;
10976        boolean deletedPkg = true;
10977        boolean updatedSettings = false;
10978
10979        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10980                + deletedPackage);
10981        long origUpdateTime;
10982        if (pkg.mExtras != null) {
10983            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10984        } else {
10985            origUpdateTime = 0;
10986        }
10987
10988        // First delete the existing package while retaining the data directory
10989        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10990                res.removedInfo, true)) {
10991            // If the existing package wasn't successfully deleted
10992            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10993            deletedPkg = false;
10994        } else {
10995            // Successfully deleted the old package; proceed with replace.
10996
10997            // If deleted package lived in a container, give users a chance to
10998            // relinquish resources before killing.
10999            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11000                if (DEBUG_INSTALL) {
11001                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11002                }
11003                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11004                final ArrayList<String> pkgList = new ArrayList<String>(1);
11005                pkgList.add(deletedPackage.applicationInfo.packageName);
11006                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11007            }
11008
11009            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11010            try {
11011                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11012                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11013                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11014                        perUserInstalled, res, user);
11015                updatedSettings = true;
11016            } catch (PackageManagerException e) {
11017                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11018            }
11019        }
11020
11021        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11022            // remove package from internal structures.  Note that we want deletePackageX to
11023            // delete the package data and cache directories that it created in
11024            // scanPackageLocked, unless those directories existed before we even tried to
11025            // install.
11026            if(updatedSettings) {
11027                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11028                deletePackageLI(
11029                        pkgName, null, true, allUsers, perUserInstalled,
11030                        PackageManager.DELETE_KEEP_DATA,
11031                                res.removedInfo, true);
11032            }
11033            // Since we failed to install the new package we need to restore the old
11034            // package that we deleted.
11035            if (deletedPkg) {
11036                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11037                File restoreFile = new File(deletedPackage.codePath);
11038                // Parse old package
11039                boolean oldExternal = isExternal(deletedPackage);
11040                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11041                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11042                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11043                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11044                try {
11045                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11046                } catch (PackageManagerException e) {
11047                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11048                            + e.getMessage());
11049                    return;
11050                }
11051                // Restore of old package succeeded. Update permissions.
11052                // writer
11053                synchronized (mPackages) {
11054                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11055                            UPDATE_PERMISSIONS_ALL);
11056                    // can downgrade to reader
11057                    mSettings.writeLPr();
11058                }
11059                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11060            }
11061        }
11062    }
11063
11064    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11065            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11066            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11067            String volumeUuid, PackageInstalledInfo res) {
11068        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11069                + ", old=" + deletedPackage);
11070        boolean disabledSystem = false;
11071        boolean updatedSettings = false;
11072        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11073        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11074                != 0) {
11075            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11076        }
11077        String packageName = deletedPackage.packageName;
11078        if (packageName == null) {
11079            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11080                    "Attempt to delete null packageName.");
11081            return;
11082        }
11083        PackageParser.Package oldPkg;
11084        PackageSetting oldPkgSetting;
11085        // reader
11086        synchronized (mPackages) {
11087            oldPkg = mPackages.get(packageName);
11088            oldPkgSetting = mSettings.mPackages.get(packageName);
11089            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11090                    (oldPkgSetting == null)) {
11091                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11092                        "Couldn't find package:" + packageName + " information");
11093                return;
11094            }
11095        }
11096
11097        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11098        res.removedInfo.removedPackage = packageName;
11099        // Remove existing system package
11100        removePackageLI(oldPkgSetting, true);
11101        // writer
11102        synchronized (mPackages) {
11103            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11104            if (!disabledSystem && deletedPackage != null) {
11105                // We didn't need to disable the .apk as a current system package,
11106                // which means we are replacing another update that is already
11107                // installed.  We need to make sure to delete the older one's .apk.
11108                res.removedInfo.args = createInstallArgsForExisting(0,
11109                        deletedPackage.applicationInfo.getCodePath(),
11110                        deletedPackage.applicationInfo.getResourcePath(),
11111                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11112            } else {
11113                res.removedInfo.args = null;
11114            }
11115        }
11116
11117        // Successfully disabled the old package. Now proceed with re-installation
11118        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11119
11120        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11121        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11122
11123        PackageParser.Package newPackage = null;
11124        try {
11125            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11126            if (newPackage.mExtras != null) {
11127                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11128                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11129                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11130
11131                // is the update attempting to change shared user? that isn't going to work...
11132                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11133                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11134                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11135                            + " to " + newPkgSetting.sharedUser);
11136                    updatedSettings = true;
11137                }
11138            }
11139
11140            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11141                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11142                        perUserInstalled, res, user);
11143                updatedSettings = true;
11144            }
11145
11146        } catch (PackageManagerException e) {
11147            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11148        }
11149
11150        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11151            // Re installation failed. Restore old information
11152            // Remove new pkg information
11153            if (newPackage != null) {
11154                removeInstalledPackageLI(newPackage, true);
11155            }
11156            // Add back the old system package
11157            try {
11158                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11159            } catch (PackageManagerException e) {
11160                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11161            }
11162            // Restore the old system information in Settings
11163            synchronized (mPackages) {
11164                if (disabledSystem) {
11165                    mSettings.enableSystemPackageLPw(packageName);
11166                }
11167                if (updatedSettings) {
11168                    mSettings.setInstallerPackageName(packageName,
11169                            oldPkgSetting.installerPackageName);
11170                }
11171                mSettings.writeLPr();
11172            }
11173        }
11174    }
11175
11176    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11177            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11178            UserHandle user) {
11179        String pkgName = newPackage.packageName;
11180        synchronized (mPackages) {
11181            //write settings. the installStatus will be incomplete at this stage.
11182            //note that the new package setting would have already been
11183            //added to mPackages. It hasn't been persisted yet.
11184            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11185            mSettings.writeLPr();
11186        }
11187
11188        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11189
11190        synchronized (mPackages) {
11191            updatePermissionsLPw(newPackage.packageName, newPackage,
11192                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11193                            ? UPDATE_PERMISSIONS_ALL : 0));
11194            // For system-bundled packages, we assume that installing an upgraded version
11195            // of the package implies that the user actually wants to run that new code,
11196            // so we enable the package.
11197            PackageSetting ps = mSettings.mPackages.get(pkgName);
11198            if (ps != null) {
11199                if (isSystemApp(newPackage)) {
11200                    // NB: implicit assumption that system package upgrades apply to all users
11201                    if (DEBUG_INSTALL) {
11202                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11203                    }
11204                    if (res.origUsers != null) {
11205                        for (int userHandle : res.origUsers) {
11206                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11207                                    userHandle, installerPackageName);
11208                        }
11209                    }
11210                    // Also convey the prior install/uninstall state
11211                    if (allUsers != null && perUserInstalled != null) {
11212                        for (int i = 0; i < allUsers.length; i++) {
11213                            if (DEBUG_INSTALL) {
11214                                Slog.d(TAG, "    user " + allUsers[i]
11215                                        + " => " + perUserInstalled[i]);
11216                            }
11217                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11218                        }
11219                        // these install state changes will be persisted in the
11220                        // upcoming call to mSettings.writeLPr().
11221                    }
11222                }
11223                // It's implied that when a user requests installation, they want the app to be
11224                // installed and enabled.
11225                int userId = user.getIdentifier();
11226                if (userId != UserHandle.USER_ALL) {
11227                    ps.setInstalled(true, userId);
11228                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11229                }
11230            }
11231            res.name = pkgName;
11232            res.uid = newPackage.applicationInfo.uid;
11233            res.pkg = newPackage;
11234            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11235            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11236            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11237            //to update install status
11238            mSettings.writeLPr();
11239        }
11240    }
11241
11242    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11243        final int installFlags = args.installFlags;
11244        final String installerPackageName = args.installerPackageName;
11245        final String volumeUuid = args.volumeUuid;
11246        final File tmpPackageFile = new File(args.getCodePath());
11247        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11248        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11249                || (args.volumeUuid != null));
11250        boolean replace = false;
11251        int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
11252        // Result object to be returned
11253        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11254
11255        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11256        // Retrieve PackageSettings and parse package
11257        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11258                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11259                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11260        PackageParser pp = new PackageParser();
11261        pp.setSeparateProcesses(mSeparateProcesses);
11262        pp.setDisplayMetrics(mMetrics);
11263
11264        final PackageParser.Package pkg;
11265        try {
11266            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11267        } catch (PackageParserException e) {
11268            res.setError("Failed parse during installPackageLI", e);
11269            return;
11270        }
11271
11272        // Mark that we have an install time CPU ABI override.
11273        pkg.cpuAbiOverride = args.abiOverride;
11274
11275        String pkgName = res.name = pkg.packageName;
11276        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11277            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11278                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11279                return;
11280            }
11281        }
11282
11283        try {
11284            pp.collectCertificates(pkg, parseFlags);
11285            pp.collectManifestDigest(pkg);
11286        } catch (PackageParserException e) {
11287            res.setError("Failed collect during installPackageLI", e);
11288            return;
11289        }
11290
11291        /* If the installer passed in a manifest digest, compare it now. */
11292        if (args.manifestDigest != null) {
11293            if (DEBUG_INSTALL) {
11294                final String parsedManifest = pkg.manifestDigest == null ? "null"
11295                        : pkg.manifestDigest.toString();
11296                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11297                        + parsedManifest);
11298            }
11299
11300            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11301                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11302                return;
11303            }
11304        } else if (DEBUG_INSTALL) {
11305            final String parsedManifest = pkg.manifestDigest == null
11306                    ? "null" : pkg.manifestDigest.toString();
11307            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11308        }
11309
11310        // Get rid of all references to package scan path via parser.
11311        pp = null;
11312        String oldCodePath = null;
11313        boolean systemApp = false;
11314        synchronized (mPackages) {
11315            // Check if installing already existing package
11316            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11317                String oldName = mSettings.mRenamedPackages.get(pkgName);
11318                if (pkg.mOriginalPackages != null
11319                        && pkg.mOriginalPackages.contains(oldName)
11320                        && mPackages.containsKey(oldName)) {
11321                    // This package is derived from an original package,
11322                    // and this device has been updating from that original
11323                    // name.  We must continue using the original name, so
11324                    // rename the new package here.
11325                    pkg.setPackageName(oldName);
11326                    pkgName = pkg.packageName;
11327                    replace = true;
11328                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11329                            + oldName + " pkgName=" + pkgName);
11330                } else if (mPackages.containsKey(pkgName)) {
11331                    // This package, under its official name, already exists
11332                    // on the device; we should replace it.
11333                    replace = true;
11334                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11335                }
11336            }
11337
11338            PackageSetting ps = mSettings.mPackages.get(pkgName);
11339            if (ps != null) {
11340                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11341
11342                // Quick sanity check that we're signed correctly if updating;
11343                // we'll check this again later when scanning, but we want to
11344                // bail early here before tripping over redefined permissions.
11345                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11346                    try {
11347                        verifySignaturesLP(ps, pkg);
11348                    } catch (PackageManagerException e) {
11349                        res.setError(e.error, e.getMessage());
11350                        return;
11351                    }
11352                } else {
11353                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11354                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11355                                + pkg.packageName + " upgrade keys do not match the "
11356                                + "previously installed version");
11357                        return;
11358                    }
11359                }
11360
11361                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11362                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11363                    systemApp = (ps.pkg.applicationInfo.flags &
11364                            ApplicationInfo.FLAG_SYSTEM) != 0;
11365                }
11366                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11367            }
11368
11369            // Check whether the newly-scanned package wants to define an already-defined perm
11370            int N = pkg.permissions.size();
11371            for (int i = N-1; i >= 0; i--) {
11372                PackageParser.Permission perm = pkg.permissions.get(i);
11373                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11374                if (bp != null) {
11375                    // If the defining package is signed with our cert, it's okay.  This
11376                    // also includes the "updating the same package" case, of course.
11377                    // "updating same package" could also involve key-rotation.
11378                    final boolean sigsOk;
11379                    if (!bp.sourcePackage.equals(pkg.packageName)
11380                            || !(bp.packageSetting instanceof PackageSetting)
11381                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
11382                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
11383                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11384                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11385                    } else {
11386                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11387                    }
11388                    if (!sigsOk) {
11389                        // If the owning package is the system itself, we log but allow
11390                        // install to proceed; we fail the install on all other permission
11391                        // redefinitions.
11392                        if (!bp.sourcePackage.equals("android")) {
11393                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11394                                    + pkg.packageName + " attempting to redeclare permission "
11395                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11396                            res.origPermission = perm.info.name;
11397                            res.origPackage = bp.sourcePackage;
11398                            return;
11399                        } else {
11400                            Slog.w(TAG, "Package " + pkg.packageName
11401                                    + " attempting to redeclare system permission "
11402                                    + perm.info.name + "; ignoring new declaration");
11403                            pkg.permissions.remove(i);
11404                        }
11405                    }
11406                }
11407            }
11408
11409        }
11410
11411        if (systemApp && onExternal) {
11412            // Disable updates to system apps on sdcard
11413            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11414                    "Cannot install updates to system apps on sdcard");
11415            return;
11416        }
11417
11418        if (args.move != null) {
11419            // We did an in-place move, so dex is ready to roll
11420            scanFlags |= SCAN_NO_DEX;
11421        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11422            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11423            scanFlags |= SCAN_NO_DEX;
11424            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11425            int result = mPackageDexOptimizer
11426                    .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */,
11427                            false /* defer */, false /* inclDependencies */);
11428            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11429                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11430                return;
11431            }
11432        }
11433
11434        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11435            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11436            return;
11437        }
11438
11439        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11440
11441        if (replace) {
11442            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11443                    installerPackageName, volumeUuid, res);
11444        } else {
11445            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11446                    args.user, installerPackageName, volumeUuid, res);
11447        }
11448        synchronized (mPackages) {
11449            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11450            if (ps != null) {
11451                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11452            }
11453        }
11454    }
11455
11456    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11457        if (mIntentFilterVerifierComponent == null) {
11458            Slog.d(TAG, "No IntentFilter verification will not be done as "
11459                    + "there is no IntentFilterVerifier available!");
11460            return;
11461        }
11462
11463        final int verifierUid = getPackageUid(
11464                mIntentFilterVerifierComponent.getPackageName(),
11465                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11466
11467        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11468        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11469        msg.obj = pkg;
11470        msg.arg1 = userId;
11471        msg.arg2 = verifierUid;
11472
11473        mHandler.sendMessage(msg);
11474    }
11475
11476    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11477            PackageParser.Package pkg) {
11478        int size = pkg.activities.size();
11479        if (size == 0) {
11480            Slog.d(TAG, "No activity, so no need to verify any IntentFilter!");
11481            return;
11482        }
11483
11484        final boolean hasDomainURLs = hasDomainURLs(pkg);
11485        if (!hasDomainURLs) {
11486            Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!");
11487            return;
11488        }
11489
11490        Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size
11491                + " Activities needs verification ...");
11492
11493        final int verificationId = mIntentFilterVerificationToken++;
11494        int count = 0;
11495        final String packageName = pkg.packageName;
11496        ArrayList<String> allHosts = new ArrayList<>();
11497
11498        synchronized (mPackages) {
11499            for (PackageParser.Activity a : pkg.activities) {
11500                for (ActivityIntentInfo filter : a.intents) {
11501                    boolean needsFilterVerification = filter.needsVerification();
11502                    if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11503                        Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString());
11504                        mIntentFilterVerifier.addOneIntentFilterVerification(
11505                                verifierUid, userId, verificationId, filter, packageName);
11506                        count++;
11507                    } else if (!needsFilterVerification) {
11508                        Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString());
11509                        if (hasValidDomains(filter)) {
11510                            ArrayList<String> hosts = filter.getHostsList();
11511                            if (hosts.size() > 0) {
11512                                allHosts.addAll(hosts);
11513                            } else {
11514                                if (allHosts.isEmpty()) {
11515                                    allHosts.add("*");
11516                                }
11517                            }
11518                        }
11519                    } else {
11520                        Slog.d(TAG, "Verification already done for IntentFilter:"
11521                                + filter.toString());
11522                    }
11523                }
11524            }
11525        }
11526
11527        if (count > 0) {
11528            mIntentFilterVerifier.startVerifications(userId);
11529            Slog.d(TAG, "Started " + count + " IntentFilter verification"
11530                    + (count > 1 ? "s" : "") +  " for userId:" + userId + "!");
11531        } else {
11532            Slog.d(TAG, "No need to start any IntentFilter verification!");
11533            if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw(
11534                    packageName, allHosts) != null) {
11535                scheduleWriteSettingsLocked();
11536            }
11537        }
11538    }
11539
11540    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11541        final ComponentName cn  = filter.activity.getComponentName();
11542        final String packageName = cn.getPackageName();
11543
11544        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11545                packageName);
11546        if (ivi == null) {
11547            return true;
11548        }
11549        int status = ivi.getStatus();
11550        switch (status) {
11551            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11552            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11553                return true;
11554
11555            default:
11556                // Nothing to do
11557                return false;
11558        }
11559    }
11560
11561    private static boolean isMultiArch(PackageSetting ps) {
11562        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11563    }
11564
11565    private static boolean isMultiArch(ApplicationInfo info) {
11566        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11567    }
11568
11569    private static boolean isExternal(PackageParser.Package pkg) {
11570        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11571    }
11572
11573    private static boolean isExternal(PackageSetting ps) {
11574        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11575    }
11576
11577    private static boolean isExternal(ApplicationInfo info) {
11578        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11579    }
11580
11581    private static boolean isSystemApp(PackageParser.Package pkg) {
11582        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11583    }
11584
11585    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11586        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11587    }
11588
11589    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11590        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11591    }
11592
11593    private static boolean isSystemApp(PackageSetting ps) {
11594        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11595    }
11596
11597    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11598        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11599    }
11600
11601    private int packageFlagsToInstallFlags(PackageSetting ps) {
11602        int installFlags = 0;
11603        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11604            // This existing package was an external ASEC install when we have
11605            // the external flag without a UUID
11606            installFlags |= PackageManager.INSTALL_EXTERNAL;
11607        }
11608        if (ps.isForwardLocked()) {
11609            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11610        }
11611        return installFlags;
11612    }
11613
11614    private void deleteTempPackageFiles() {
11615        final FilenameFilter filter = new FilenameFilter() {
11616            public boolean accept(File dir, String name) {
11617                return name.startsWith("vmdl") && name.endsWith(".tmp");
11618            }
11619        };
11620        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11621            file.delete();
11622        }
11623    }
11624
11625    @Override
11626    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11627            int flags) {
11628        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11629                flags);
11630    }
11631
11632    @Override
11633    public void deletePackage(final String packageName,
11634            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11635        mContext.enforceCallingOrSelfPermission(
11636                android.Manifest.permission.DELETE_PACKAGES, null);
11637        final int uid = Binder.getCallingUid();
11638        if (UserHandle.getUserId(uid) != userId) {
11639            mContext.enforceCallingPermission(
11640                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11641                    "deletePackage for user " + userId);
11642        }
11643        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11644            try {
11645                observer.onPackageDeleted(packageName,
11646                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11647            } catch (RemoteException re) {
11648            }
11649            return;
11650        }
11651
11652        boolean uninstallBlocked = false;
11653        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11654            int[] users = sUserManager.getUserIds();
11655            for (int i = 0; i < users.length; ++i) {
11656                if (getBlockUninstallForUser(packageName, users[i])) {
11657                    uninstallBlocked = true;
11658                    break;
11659                }
11660            }
11661        } else {
11662            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11663        }
11664        if (uninstallBlocked) {
11665            try {
11666                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11667                        null);
11668            } catch (RemoteException re) {
11669            }
11670            return;
11671        }
11672
11673        if (DEBUG_REMOVE) {
11674            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
11675        }
11676        // Queue up an async operation since the package deletion may take a little while.
11677        mHandler.post(new Runnable() {
11678            public void run() {
11679                mHandler.removeCallbacks(this);
11680                final int returnCode = deletePackageX(packageName, userId, flags);
11681                if (observer != null) {
11682                    try {
11683                        observer.onPackageDeleted(packageName, returnCode, null);
11684                    } catch (RemoteException e) {
11685                        Log.i(TAG, "Observer no longer exists.");
11686                    } //end catch
11687                } //end if
11688            } //end run
11689        });
11690    }
11691
11692    private boolean isPackageDeviceAdmin(String packageName, int userId) {
11693        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
11694                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
11695        try {
11696            if (dpm != null) {
11697                if (dpm.isDeviceOwner(packageName)) {
11698                    return true;
11699                }
11700                int[] users;
11701                if (userId == UserHandle.USER_ALL) {
11702                    users = sUserManager.getUserIds();
11703                } else {
11704                    users = new int[]{userId};
11705                }
11706                for (int i = 0; i < users.length; ++i) {
11707                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
11708                        return true;
11709                    }
11710                }
11711            }
11712        } catch (RemoteException e) {
11713        }
11714        return false;
11715    }
11716
11717    /**
11718     *  This method is an internal method that could be get invoked either
11719     *  to delete an installed package or to clean up a failed installation.
11720     *  After deleting an installed package, a broadcast is sent to notify any
11721     *  listeners that the package has been installed. For cleaning up a failed
11722     *  installation, the broadcast is not necessary since the package's
11723     *  installation wouldn't have sent the initial broadcast either
11724     *  The key steps in deleting a package are
11725     *  deleting the package information in internal structures like mPackages,
11726     *  deleting the packages base directories through installd
11727     *  updating mSettings to reflect current status
11728     *  persisting settings for later use
11729     *  sending a broadcast if necessary
11730     */
11731    private int deletePackageX(String packageName, int userId, int flags) {
11732        final PackageRemovedInfo info = new PackageRemovedInfo();
11733        final boolean res;
11734
11735        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
11736                ? UserHandle.ALL : new UserHandle(userId);
11737
11738        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
11739            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
11740            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
11741        }
11742
11743        boolean removedForAllUsers = false;
11744        boolean systemUpdate = false;
11745
11746        // for the uninstall-updates case and restricted profiles, remember the per-
11747        // userhandle installed state
11748        int[] allUsers;
11749        boolean[] perUserInstalled;
11750        synchronized (mPackages) {
11751            PackageSetting ps = mSettings.mPackages.get(packageName);
11752            allUsers = sUserManager.getUserIds();
11753            perUserInstalled = new boolean[allUsers.length];
11754            for (int i = 0; i < allUsers.length; i++) {
11755                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11756            }
11757        }
11758
11759        synchronized (mInstallLock) {
11760            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
11761            res = deletePackageLI(packageName, removeForUser,
11762                    true, allUsers, perUserInstalled,
11763                    flags | REMOVE_CHATTY, info, true);
11764            systemUpdate = info.isRemovedPackageSystemUpdate;
11765            if (res && !systemUpdate && mPackages.get(packageName) == null) {
11766                removedForAllUsers = true;
11767            }
11768            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
11769                    + " removedForAllUsers=" + removedForAllUsers);
11770        }
11771
11772        if (res) {
11773            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
11774
11775            // If the removed package was a system update, the old system package
11776            // was re-enabled; we need to broadcast this information
11777            if (systemUpdate) {
11778                Bundle extras = new Bundle(1);
11779                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
11780                        ? info.removedAppId : info.uid);
11781                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11782
11783                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
11784                        extras, null, null, null);
11785                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
11786                        extras, null, null, null);
11787                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
11788                        null, packageName, null, null);
11789            }
11790        }
11791        // Force a gc here.
11792        Runtime.getRuntime().gc();
11793        // Delete the resources here after sending the broadcast to let
11794        // other processes clean up before deleting resources.
11795        if (info.args != null) {
11796            synchronized (mInstallLock) {
11797                info.args.doPostDeleteLI(true);
11798            }
11799        }
11800
11801        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
11802    }
11803
11804    class PackageRemovedInfo {
11805        String removedPackage;
11806        int uid = -1;
11807        int removedAppId = -1;
11808        int[] removedUsers = null;
11809        boolean isRemovedPackageSystemUpdate = false;
11810        // Clean up resources deleted packages.
11811        InstallArgs args = null;
11812
11813        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
11814            Bundle extras = new Bundle(1);
11815            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
11816            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
11817            if (replacing) {
11818                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11819            }
11820            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
11821            if (removedPackage != null) {
11822                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
11823                        extras, null, null, removedUsers);
11824                if (fullRemove && !replacing) {
11825                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
11826                            extras, null, null, removedUsers);
11827                }
11828            }
11829            if (removedAppId >= 0) {
11830                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
11831                        removedUsers);
11832            }
11833        }
11834    }
11835
11836    /*
11837     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
11838     * flag is not set, the data directory is removed as well.
11839     * make sure this flag is set for partially installed apps. If not its meaningless to
11840     * delete a partially installed application.
11841     */
11842    private void removePackageDataLI(PackageSetting ps,
11843            int[] allUserHandles, boolean[] perUserInstalled,
11844            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
11845        String packageName = ps.name;
11846        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
11847        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
11848        // Retrieve object to delete permissions for shared user later on
11849        final PackageSetting deletedPs;
11850        // reader
11851        synchronized (mPackages) {
11852            deletedPs = mSettings.mPackages.get(packageName);
11853            if (outInfo != null) {
11854                outInfo.removedPackage = packageName;
11855                outInfo.removedUsers = deletedPs != null
11856                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
11857                        : null;
11858            }
11859        }
11860        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11861            removeDataDirsLI(ps.volumeUuid, packageName);
11862            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
11863        }
11864        // writer
11865        synchronized (mPackages) {
11866            if (deletedPs != null) {
11867                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11868                    if (outInfo != null) {
11869                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
11870                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
11871                    }
11872                    updatePermissionsLPw(deletedPs.name, null, 0);
11873                    if (deletedPs.sharedUser != null) {
11874                        // Remove permissions associated with package. Since runtime
11875                        // permissions are per user we have to kill the removed package
11876                        // or packages running under the shared user of the removed
11877                        // package if revoking the permissions requested only by the removed
11878                        // package is successful and this causes a change in gids.
11879                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11880                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
11881                                    userId);
11882                            if (userIdToKill == UserHandle.USER_ALL
11883                                    || userIdToKill >= UserHandle.USER_OWNER) {
11884                                // If gids changed for this user, kill all affected packages.
11885                                mHandler.post(new Runnable() {
11886                                    @Override
11887                                    public void run() {
11888                                        // This has to happen with no lock held.
11889                                        killSettingPackagesForUser(deletedPs, userIdToKill,
11890                                                KILL_APP_REASON_GIDS_CHANGED);
11891                                    }
11892                                });
11893                            break;
11894                            }
11895                        }
11896                    }
11897                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
11898                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
11899                }
11900                // make sure to preserve per-user disabled state if this removal was just
11901                // a downgrade of a system app to the factory package
11902                if (allUserHandles != null && perUserInstalled != null) {
11903                    if (DEBUG_REMOVE) {
11904                        Slog.d(TAG, "Propagating install state across downgrade");
11905                    }
11906                    for (int i = 0; i < allUserHandles.length; i++) {
11907                        if (DEBUG_REMOVE) {
11908                            Slog.d(TAG, "    user " + allUserHandles[i]
11909                                    + " => " + perUserInstalled[i]);
11910                        }
11911                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11912                    }
11913                }
11914            }
11915            // can downgrade to reader
11916            if (writeSettings) {
11917                // Save settings now
11918                mSettings.writeLPr();
11919            }
11920        }
11921        if (outInfo != null) {
11922            // A user ID was deleted here. Go through all users and remove it
11923            // from KeyStore.
11924            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
11925        }
11926    }
11927
11928    static boolean locationIsPrivileged(File path) {
11929        try {
11930            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
11931                    .getCanonicalPath();
11932            return path.getCanonicalPath().startsWith(privilegedAppDir);
11933        } catch (IOException e) {
11934            Slog.e(TAG, "Unable to access code path " + path);
11935        }
11936        return false;
11937    }
11938
11939    /*
11940     * Tries to delete system package.
11941     */
11942    private boolean deleteSystemPackageLI(PackageSetting newPs,
11943            int[] allUserHandles, boolean[] perUserInstalled,
11944            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
11945        final boolean applyUserRestrictions
11946                = (allUserHandles != null) && (perUserInstalled != null);
11947        PackageSetting disabledPs = null;
11948        // Confirm if the system package has been updated
11949        // An updated system app can be deleted. This will also have to restore
11950        // the system pkg from system partition
11951        // reader
11952        synchronized (mPackages) {
11953            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
11954        }
11955        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
11956                + " disabledPs=" + disabledPs);
11957        if (disabledPs == null) {
11958            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
11959            return false;
11960        } else if (DEBUG_REMOVE) {
11961            Slog.d(TAG, "Deleting system pkg from data partition");
11962        }
11963        if (DEBUG_REMOVE) {
11964            if (applyUserRestrictions) {
11965                Slog.d(TAG, "Remembering install states:");
11966                for (int i = 0; i < allUserHandles.length; i++) {
11967                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
11968                }
11969            }
11970        }
11971        // Delete the updated package
11972        outInfo.isRemovedPackageSystemUpdate = true;
11973        if (disabledPs.versionCode < newPs.versionCode) {
11974            // Delete data for downgrades
11975            flags &= ~PackageManager.DELETE_KEEP_DATA;
11976        } else {
11977            // Preserve data by setting flag
11978            flags |= PackageManager.DELETE_KEEP_DATA;
11979        }
11980        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
11981                allUserHandles, perUserInstalled, outInfo, writeSettings);
11982        if (!ret) {
11983            return false;
11984        }
11985        // writer
11986        synchronized (mPackages) {
11987            // Reinstate the old system package
11988            mSettings.enableSystemPackageLPw(newPs.name);
11989            // Remove any native libraries from the upgraded package.
11990            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
11991        }
11992        // Install the system package
11993        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
11994        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
11995        if (locationIsPrivileged(disabledPs.codePath)) {
11996            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11997        }
11998
11999        final PackageParser.Package newPkg;
12000        try {
12001            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12002        } catch (PackageManagerException e) {
12003            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12004            return false;
12005        }
12006
12007        // writer
12008        synchronized (mPackages) {
12009            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12010            updatePermissionsLPw(newPkg.packageName, newPkg,
12011                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12012            if (applyUserRestrictions) {
12013                if (DEBUG_REMOVE) {
12014                    Slog.d(TAG, "Propagating install state across reinstall");
12015                }
12016                for (int i = 0; i < allUserHandles.length; i++) {
12017                    if (DEBUG_REMOVE) {
12018                        Slog.d(TAG, "    user " + allUserHandles[i]
12019                                + " => " + perUserInstalled[i]);
12020                    }
12021                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12022                }
12023                // Regardless of writeSettings we need to ensure that this restriction
12024                // state propagation is persisted
12025                mSettings.writeAllUsersPackageRestrictionsLPr();
12026            }
12027            // can downgrade to reader here
12028            if (writeSettings) {
12029                mSettings.writeLPr();
12030            }
12031        }
12032        return true;
12033    }
12034
12035    private boolean deleteInstalledPackageLI(PackageSetting ps,
12036            boolean deleteCodeAndResources, int flags,
12037            int[] allUserHandles, boolean[] perUserInstalled,
12038            PackageRemovedInfo outInfo, boolean writeSettings) {
12039        if (outInfo != null) {
12040            outInfo.uid = ps.appId;
12041        }
12042
12043        // Delete package data from internal structures and also remove data if flag is set
12044        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12045
12046        // Delete application code and resources
12047        if (deleteCodeAndResources && (outInfo != null)) {
12048            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12049                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12050            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12051        }
12052        return true;
12053    }
12054
12055    @Override
12056    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12057            int userId) {
12058        mContext.enforceCallingOrSelfPermission(
12059                android.Manifest.permission.DELETE_PACKAGES, null);
12060        synchronized (mPackages) {
12061            PackageSetting ps = mSettings.mPackages.get(packageName);
12062            if (ps == null) {
12063                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12064                return false;
12065            }
12066            if (!ps.getInstalled(userId)) {
12067                // Can't block uninstall for an app that is not installed or enabled.
12068                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12069                return false;
12070            }
12071            ps.setBlockUninstall(blockUninstall, userId);
12072            mSettings.writePackageRestrictionsLPr(userId);
12073        }
12074        return true;
12075    }
12076
12077    @Override
12078    public boolean getBlockUninstallForUser(String packageName, int userId) {
12079        synchronized (mPackages) {
12080            PackageSetting ps = mSettings.mPackages.get(packageName);
12081            if (ps == null) {
12082                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12083                return false;
12084            }
12085            return ps.getBlockUninstall(userId);
12086        }
12087    }
12088
12089    /*
12090     * This method handles package deletion in general
12091     */
12092    private boolean deletePackageLI(String packageName, UserHandle user,
12093            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12094            int flags, PackageRemovedInfo outInfo,
12095            boolean writeSettings) {
12096        if (packageName == null) {
12097            Slog.w(TAG, "Attempt to delete null packageName.");
12098            return false;
12099        }
12100        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12101        PackageSetting ps;
12102        boolean dataOnly = false;
12103        int removeUser = -1;
12104        int appId = -1;
12105        synchronized (mPackages) {
12106            ps = mSettings.mPackages.get(packageName);
12107            if (ps == null) {
12108                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12109                return false;
12110            }
12111            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12112                    && user.getIdentifier() != UserHandle.USER_ALL) {
12113                // The caller is asking that the package only be deleted for a single
12114                // user.  To do this, we just mark its uninstalled state and delete
12115                // its data.  If this is a system app, we only allow this to happen if
12116                // they have set the special DELETE_SYSTEM_APP which requests different
12117                // semantics than normal for uninstalling system apps.
12118                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12119                ps.setUserState(user.getIdentifier(),
12120                        COMPONENT_ENABLED_STATE_DEFAULT,
12121                        false, //installed
12122                        true,  //stopped
12123                        true,  //notLaunched
12124                        false, //hidden
12125                        null, null, null,
12126                        false, // blockUninstall
12127                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12128                if (!isSystemApp(ps)) {
12129                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12130                        // Other user still have this package installed, so all
12131                        // we need to do is clear this user's data and save that
12132                        // it is uninstalled.
12133                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12134                        removeUser = user.getIdentifier();
12135                        appId = ps.appId;
12136                        scheduleWritePackageRestrictionsLocked(removeUser);
12137                    } else {
12138                        // We need to set it back to 'installed' so the uninstall
12139                        // broadcasts will be sent correctly.
12140                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12141                        ps.setInstalled(true, user.getIdentifier());
12142                    }
12143                } else {
12144                    // This is a system app, so we assume that the
12145                    // other users still have this package installed, so all
12146                    // we need to do is clear this user's data and save that
12147                    // it is uninstalled.
12148                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12149                    removeUser = user.getIdentifier();
12150                    appId = ps.appId;
12151                    scheduleWritePackageRestrictionsLocked(removeUser);
12152                }
12153            }
12154        }
12155
12156        if (removeUser >= 0) {
12157            // From above, we determined that we are deleting this only
12158            // for a single user.  Continue the work here.
12159            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12160            if (outInfo != null) {
12161                outInfo.removedPackage = packageName;
12162                outInfo.removedAppId = appId;
12163                outInfo.removedUsers = new int[] {removeUser};
12164            }
12165            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12166            removeKeystoreDataIfNeeded(removeUser, appId);
12167            schedulePackageCleaning(packageName, removeUser, false);
12168            synchronized (mPackages) {
12169                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12170                    scheduleWritePackageRestrictionsLocked(removeUser);
12171                }
12172            }
12173            return true;
12174        }
12175
12176        if (dataOnly) {
12177            // Delete application data first
12178            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12179            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12180            return true;
12181        }
12182
12183        boolean ret = false;
12184        if (isSystemApp(ps)) {
12185            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12186            // When an updated system application is deleted we delete the existing resources as well and
12187            // fall back to existing code in system partition
12188            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12189                    flags, outInfo, writeSettings);
12190        } else {
12191            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12192            // Kill application pre-emptively especially for apps on sd.
12193            killApplication(packageName, ps.appId, "uninstall pkg");
12194            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12195                    allUserHandles, perUserInstalled,
12196                    outInfo, writeSettings);
12197        }
12198
12199        return ret;
12200    }
12201
12202    private final class ClearStorageConnection implements ServiceConnection {
12203        IMediaContainerService mContainerService;
12204
12205        @Override
12206        public void onServiceConnected(ComponentName name, IBinder service) {
12207            synchronized (this) {
12208                mContainerService = IMediaContainerService.Stub.asInterface(service);
12209                notifyAll();
12210            }
12211        }
12212
12213        @Override
12214        public void onServiceDisconnected(ComponentName name) {
12215        }
12216    }
12217
12218    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12219        final boolean mounted;
12220        if (Environment.isExternalStorageEmulated()) {
12221            mounted = true;
12222        } else {
12223            final String status = Environment.getExternalStorageState();
12224
12225            mounted = status.equals(Environment.MEDIA_MOUNTED)
12226                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12227        }
12228
12229        if (!mounted) {
12230            return;
12231        }
12232
12233        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12234        int[] users;
12235        if (userId == UserHandle.USER_ALL) {
12236            users = sUserManager.getUserIds();
12237        } else {
12238            users = new int[] { userId };
12239        }
12240        final ClearStorageConnection conn = new ClearStorageConnection();
12241        if (mContext.bindServiceAsUser(
12242                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12243            try {
12244                for (int curUser : users) {
12245                    long timeout = SystemClock.uptimeMillis() + 5000;
12246                    synchronized (conn) {
12247                        long now = SystemClock.uptimeMillis();
12248                        while (conn.mContainerService == null && now < timeout) {
12249                            try {
12250                                conn.wait(timeout - now);
12251                            } catch (InterruptedException e) {
12252                            }
12253                        }
12254                    }
12255                    if (conn.mContainerService == null) {
12256                        return;
12257                    }
12258
12259                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12260                    clearDirectory(conn.mContainerService,
12261                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12262                    if (allData) {
12263                        clearDirectory(conn.mContainerService,
12264                                userEnv.buildExternalStorageAppDataDirs(packageName));
12265                        clearDirectory(conn.mContainerService,
12266                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12267                    }
12268                }
12269            } finally {
12270                mContext.unbindService(conn);
12271            }
12272        }
12273    }
12274
12275    @Override
12276    public void clearApplicationUserData(final String packageName,
12277            final IPackageDataObserver observer, final int userId) {
12278        mContext.enforceCallingOrSelfPermission(
12279                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12280        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12281        // Queue up an async operation since the package deletion may take a little while.
12282        mHandler.post(new Runnable() {
12283            public void run() {
12284                mHandler.removeCallbacks(this);
12285                final boolean succeeded;
12286                synchronized (mInstallLock) {
12287                    succeeded = clearApplicationUserDataLI(packageName, userId);
12288                }
12289                clearExternalStorageDataSync(packageName, userId, true);
12290                if (succeeded) {
12291                    // invoke DeviceStorageMonitor's update method to clear any notifications
12292                    DeviceStorageMonitorInternal
12293                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12294                    if (dsm != null) {
12295                        dsm.checkMemory();
12296                    }
12297                }
12298                if(observer != null) {
12299                    try {
12300                        observer.onRemoveCompleted(packageName, succeeded);
12301                    } catch (RemoteException e) {
12302                        Log.i(TAG, "Observer no longer exists.");
12303                    }
12304                } //end if observer
12305            } //end run
12306        });
12307    }
12308
12309    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12310        if (packageName == null) {
12311            Slog.w(TAG, "Attempt to delete null packageName.");
12312            return false;
12313        }
12314
12315        // Try finding details about the requested package
12316        PackageParser.Package pkg;
12317        synchronized (mPackages) {
12318            pkg = mPackages.get(packageName);
12319            if (pkg == null) {
12320                final PackageSetting ps = mSettings.mPackages.get(packageName);
12321                if (ps != null) {
12322                    pkg = ps.pkg;
12323                }
12324            }
12325        }
12326
12327        if (pkg == null) {
12328            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12329        }
12330
12331        // Always delete data directories for package, even if we found no other
12332        // record of app. This helps users recover from UID mismatches without
12333        // resorting to a full data wipe.
12334        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12335        if (retCode < 0) {
12336            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12337            return false;
12338        }
12339
12340        if (pkg == null) {
12341            return false;
12342        }
12343
12344        if (pkg != null && pkg.applicationInfo != null) {
12345            final int appId = pkg.applicationInfo.uid;
12346            removeKeystoreDataIfNeeded(userId, appId);
12347        }
12348
12349        // Create a native library symlink only if we have native libraries
12350        // and if the native libraries are 32 bit libraries. We do not provide
12351        // this symlink for 64 bit libraries.
12352        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
12353                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12354            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12355            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12356                    nativeLibPath, userId) < 0) {
12357                Slog.w(TAG, "Failed linking native library dir");
12358                return false;
12359            }
12360        }
12361
12362        return true;
12363    }
12364
12365    /**
12366     * Remove entries from the keystore daemon. Will only remove it if the
12367     * {@code appId} is valid.
12368     */
12369    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12370        if (appId < 0) {
12371            return;
12372        }
12373
12374        final KeyStore keyStore = KeyStore.getInstance();
12375        if (keyStore != null) {
12376            if (userId == UserHandle.USER_ALL) {
12377                for (final int individual : sUserManager.getUserIds()) {
12378                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12379                }
12380            } else {
12381                keyStore.clearUid(UserHandle.getUid(userId, appId));
12382            }
12383        } else {
12384            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12385        }
12386    }
12387
12388    @Override
12389    public void deleteApplicationCacheFiles(final String packageName,
12390            final IPackageDataObserver observer) {
12391        mContext.enforceCallingOrSelfPermission(
12392                android.Manifest.permission.DELETE_CACHE_FILES, null);
12393        // Queue up an async operation since the package deletion may take a little while.
12394        final int userId = UserHandle.getCallingUserId();
12395        mHandler.post(new Runnable() {
12396            public void run() {
12397                mHandler.removeCallbacks(this);
12398                final boolean succeded;
12399                synchronized (mInstallLock) {
12400                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12401                }
12402                clearExternalStorageDataSync(packageName, userId, false);
12403                if(observer != null) {
12404                    try {
12405                        observer.onRemoveCompleted(packageName, succeded);
12406                    } catch (RemoteException e) {
12407                        Log.i(TAG, "Observer no longer exists.");
12408                    }
12409                } //end if observer
12410            } //end run
12411        });
12412    }
12413
12414    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12415        if (packageName == null) {
12416            Slog.w(TAG, "Attempt to delete null packageName.");
12417            return false;
12418        }
12419        PackageParser.Package p;
12420        synchronized (mPackages) {
12421            p = mPackages.get(packageName);
12422        }
12423        if (p == null) {
12424            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12425            return false;
12426        }
12427        final ApplicationInfo applicationInfo = p.applicationInfo;
12428        if (applicationInfo == null) {
12429            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12430            return false;
12431        }
12432        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12433        if (retCode < 0) {
12434            Slog.w(TAG, "Couldn't remove cache files for package: "
12435                       + packageName + " u" + userId);
12436            return false;
12437        }
12438        return true;
12439    }
12440
12441    @Override
12442    public void getPackageSizeInfo(final String packageName, int userHandle,
12443            final IPackageStatsObserver observer) {
12444        mContext.enforceCallingOrSelfPermission(
12445                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12446        if (packageName == null) {
12447            throw new IllegalArgumentException("Attempt to get size of null packageName");
12448        }
12449
12450        PackageStats stats = new PackageStats(packageName, userHandle);
12451
12452        /*
12453         * Queue up an async operation since the package measurement may take a
12454         * little while.
12455         */
12456        Message msg = mHandler.obtainMessage(INIT_COPY);
12457        msg.obj = new MeasureParams(stats, observer);
12458        mHandler.sendMessage(msg);
12459    }
12460
12461    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12462            PackageStats pStats) {
12463        if (packageName == null) {
12464            Slog.w(TAG, "Attempt to get size of null packageName.");
12465            return false;
12466        }
12467        PackageParser.Package p;
12468        boolean dataOnly = false;
12469        String libDirRoot = null;
12470        String asecPath = null;
12471        PackageSetting ps = null;
12472        synchronized (mPackages) {
12473            p = mPackages.get(packageName);
12474            ps = mSettings.mPackages.get(packageName);
12475            if(p == null) {
12476                dataOnly = true;
12477                if((ps == null) || (ps.pkg == null)) {
12478                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12479                    return false;
12480                }
12481                p = ps.pkg;
12482            }
12483            if (ps != null) {
12484                libDirRoot = ps.legacyNativeLibraryPathString;
12485            }
12486            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12487                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12488                if (secureContainerId != null) {
12489                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12490                }
12491            }
12492        }
12493        String publicSrcDir = null;
12494        if(!dataOnly) {
12495            final ApplicationInfo applicationInfo = p.applicationInfo;
12496            if (applicationInfo == null) {
12497                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12498                return false;
12499            }
12500            if (p.isForwardLocked()) {
12501                publicSrcDir = applicationInfo.getBaseResourcePath();
12502            }
12503        }
12504        // TODO: extend to measure size of split APKs
12505        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12506        // not just the first level.
12507        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12508        // just the primary.
12509        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12510        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
12511                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12512        if (res < 0) {
12513            return false;
12514        }
12515
12516        // Fix-up for forward-locked applications in ASEC containers.
12517        if (!isExternal(p)) {
12518            pStats.codeSize += pStats.externalCodeSize;
12519            pStats.externalCodeSize = 0L;
12520        }
12521
12522        return true;
12523    }
12524
12525
12526    @Override
12527    public void addPackageToPreferred(String packageName) {
12528        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12529    }
12530
12531    @Override
12532    public void removePackageFromPreferred(String packageName) {
12533        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12534    }
12535
12536    @Override
12537    public List<PackageInfo> getPreferredPackages(int flags) {
12538        return new ArrayList<PackageInfo>();
12539    }
12540
12541    private int getUidTargetSdkVersionLockedLPr(int uid) {
12542        Object obj = mSettings.getUserIdLPr(uid);
12543        if (obj instanceof SharedUserSetting) {
12544            final SharedUserSetting sus = (SharedUserSetting) obj;
12545            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12546            final Iterator<PackageSetting> it = sus.packages.iterator();
12547            while (it.hasNext()) {
12548                final PackageSetting ps = it.next();
12549                if (ps.pkg != null) {
12550                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12551                    if (v < vers) vers = v;
12552                }
12553            }
12554            return vers;
12555        } else if (obj instanceof PackageSetting) {
12556            final PackageSetting ps = (PackageSetting) obj;
12557            if (ps.pkg != null) {
12558                return ps.pkg.applicationInfo.targetSdkVersion;
12559            }
12560        }
12561        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12562    }
12563
12564    @Override
12565    public void addPreferredActivity(IntentFilter filter, int match,
12566            ComponentName[] set, ComponentName activity, int userId) {
12567        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12568                "Adding preferred");
12569    }
12570
12571    private void addPreferredActivityInternal(IntentFilter filter, int match,
12572            ComponentName[] set, ComponentName activity, boolean always, int userId,
12573            String opname) {
12574        // writer
12575        int callingUid = Binder.getCallingUid();
12576        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12577        if (filter.countActions() == 0) {
12578            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12579            return;
12580        }
12581        synchronized (mPackages) {
12582            if (mContext.checkCallingOrSelfPermission(
12583                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12584                    != PackageManager.PERMISSION_GRANTED) {
12585                if (getUidTargetSdkVersionLockedLPr(callingUid)
12586                        < Build.VERSION_CODES.FROYO) {
12587                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12588                            + callingUid);
12589                    return;
12590                }
12591                mContext.enforceCallingOrSelfPermission(
12592                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12593            }
12594
12595            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12596            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12597                    + userId + ":");
12598            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12599            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12600            scheduleWritePackageRestrictionsLocked(userId);
12601        }
12602    }
12603
12604    @Override
12605    public void replacePreferredActivity(IntentFilter filter, int match,
12606            ComponentName[] set, ComponentName activity, int userId) {
12607        if (filter.countActions() != 1) {
12608            throw new IllegalArgumentException(
12609                    "replacePreferredActivity expects filter to have only 1 action.");
12610        }
12611        if (filter.countDataAuthorities() != 0
12612                || filter.countDataPaths() != 0
12613                || filter.countDataSchemes() > 1
12614                || filter.countDataTypes() != 0) {
12615            throw new IllegalArgumentException(
12616                    "replacePreferredActivity expects filter to have no data authorities, " +
12617                    "paths, or types; and at most one scheme.");
12618        }
12619
12620        final int callingUid = Binder.getCallingUid();
12621        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12622        synchronized (mPackages) {
12623            if (mContext.checkCallingOrSelfPermission(
12624                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12625                    != PackageManager.PERMISSION_GRANTED) {
12626                if (getUidTargetSdkVersionLockedLPr(callingUid)
12627                        < Build.VERSION_CODES.FROYO) {
12628                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12629                            + Binder.getCallingUid());
12630                    return;
12631                }
12632                mContext.enforceCallingOrSelfPermission(
12633                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12634            }
12635
12636            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12637            if (pir != null) {
12638                // Get all of the existing entries that exactly match this filter.
12639                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
12640                if (existing != null && existing.size() == 1) {
12641                    PreferredActivity cur = existing.get(0);
12642                    if (DEBUG_PREFERRED) {
12643                        Slog.i(TAG, "Checking replace of preferred:");
12644                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12645                        if (!cur.mPref.mAlways) {
12646                            Slog.i(TAG, "  -- CUR; not mAlways!");
12647                        } else {
12648                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
12649                            Slog.i(TAG, "  -- CUR: mSet="
12650                                    + Arrays.toString(cur.mPref.mSetComponents));
12651                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
12652                            Slog.i(TAG, "  -- NEW: mMatch="
12653                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
12654                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
12655                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
12656                        }
12657                    }
12658                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
12659                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
12660                            && cur.mPref.sameSet(set)) {
12661                        // Setting the preferred activity to what it happens to be already
12662                        if (DEBUG_PREFERRED) {
12663                            Slog.i(TAG, "Replacing with same preferred activity "
12664                                    + cur.mPref.mShortComponent + " for user "
12665                                    + userId + ":");
12666                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12667                        }
12668                        return;
12669                    }
12670                }
12671
12672                if (existing != null) {
12673                    if (DEBUG_PREFERRED) {
12674                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
12675                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12676                    }
12677                    for (int i = 0; i < existing.size(); i++) {
12678                        PreferredActivity pa = existing.get(i);
12679                        if (DEBUG_PREFERRED) {
12680                            Slog.i(TAG, "Removing existing preferred activity "
12681                                    + pa.mPref.mComponent + ":");
12682                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
12683                        }
12684                        pir.removeFilter(pa);
12685                    }
12686                }
12687            }
12688            addPreferredActivityInternal(filter, match, set, activity, true, userId,
12689                    "Replacing preferred");
12690        }
12691    }
12692
12693    @Override
12694    public void clearPackagePreferredActivities(String packageName) {
12695        final int uid = Binder.getCallingUid();
12696        // writer
12697        synchronized (mPackages) {
12698            PackageParser.Package pkg = mPackages.get(packageName);
12699            if (pkg == null || pkg.applicationInfo.uid != uid) {
12700                if (mContext.checkCallingOrSelfPermission(
12701                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12702                        != PackageManager.PERMISSION_GRANTED) {
12703                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
12704                            < Build.VERSION_CODES.FROYO) {
12705                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
12706                                + Binder.getCallingUid());
12707                        return;
12708                    }
12709                    mContext.enforceCallingOrSelfPermission(
12710                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12711                }
12712            }
12713
12714            int user = UserHandle.getCallingUserId();
12715            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
12716                scheduleWritePackageRestrictionsLocked(user);
12717            }
12718        }
12719    }
12720
12721    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12722    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
12723        ArrayList<PreferredActivity> removed = null;
12724        boolean changed = false;
12725        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12726            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
12727            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12728            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
12729                continue;
12730            }
12731            Iterator<PreferredActivity> it = pir.filterIterator();
12732            while (it.hasNext()) {
12733                PreferredActivity pa = it.next();
12734                // Mark entry for removal only if it matches the package name
12735                // and the entry is of type "always".
12736                if (packageName == null ||
12737                        (pa.mPref.mComponent.getPackageName().equals(packageName)
12738                                && pa.mPref.mAlways)) {
12739                    if (removed == null) {
12740                        removed = new ArrayList<PreferredActivity>();
12741                    }
12742                    removed.add(pa);
12743                }
12744            }
12745            if (removed != null) {
12746                for (int j=0; j<removed.size(); j++) {
12747                    PreferredActivity pa = removed.get(j);
12748                    pir.removeFilter(pa);
12749                }
12750                changed = true;
12751            }
12752        }
12753        return changed;
12754    }
12755
12756    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12757    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
12758        if (userId == UserHandle.USER_ALL) {
12759            mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds());
12760            for (int oneUserId : sUserManager.getUserIds()) {
12761                scheduleWritePackageRestrictionsLocked(oneUserId);
12762            }
12763        } else {
12764            mSettings.removeIntentFilterVerificationLPw(packageName, userId);
12765            scheduleWritePackageRestrictionsLocked(userId);
12766        }
12767    }
12768
12769    @Override
12770    public void resetPreferredActivities(int userId) {
12771        /* TODO: Actually use userId. Why is it being passed in? */
12772        mContext.enforceCallingOrSelfPermission(
12773                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12774        // writer
12775        synchronized (mPackages) {
12776            int user = UserHandle.getCallingUserId();
12777            clearPackagePreferredActivitiesLPw(null, user);
12778            mSettings.readDefaultPreferredAppsLPw(this, user);
12779            scheduleWritePackageRestrictionsLocked(user);
12780        }
12781    }
12782
12783    @Override
12784    public int getPreferredActivities(List<IntentFilter> outFilters,
12785            List<ComponentName> outActivities, String packageName) {
12786
12787        int num = 0;
12788        final int userId = UserHandle.getCallingUserId();
12789        // reader
12790        synchronized (mPackages) {
12791            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12792            if (pir != null) {
12793                final Iterator<PreferredActivity> it = pir.filterIterator();
12794                while (it.hasNext()) {
12795                    final PreferredActivity pa = it.next();
12796                    if (packageName == null
12797                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
12798                                    && pa.mPref.mAlways)) {
12799                        if (outFilters != null) {
12800                            outFilters.add(new IntentFilter(pa));
12801                        }
12802                        if (outActivities != null) {
12803                            outActivities.add(pa.mPref.mComponent);
12804                        }
12805                    }
12806                }
12807            }
12808        }
12809
12810        return num;
12811    }
12812
12813    @Override
12814    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
12815            int userId) {
12816        int callingUid = Binder.getCallingUid();
12817        if (callingUid != Process.SYSTEM_UID) {
12818            throw new SecurityException(
12819                    "addPersistentPreferredActivity can only be run by the system");
12820        }
12821        if (filter.countActions() == 0) {
12822            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12823            return;
12824        }
12825        synchronized (mPackages) {
12826            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
12827                    " :");
12828            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12829            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
12830                    new PersistentPreferredActivity(filter, activity));
12831            scheduleWritePackageRestrictionsLocked(userId);
12832        }
12833    }
12834
12835    @Override
12836    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
12837        int callingUid = Binder.getCallingUid();
12838        if (callingUid != Process.SYSTEM_UID) {
12839            throw new SecurityException(
12840                    "clearPackagePersistentPreferredActivities can only be run by the system");
12841        }
12842        ArrayList<PersistentPreferredActivity> removed = null;
12843        boolean changed = false;
12844        synchronized (mPackages) {
12845            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
12846                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
12847                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
12848                        .valueAt(i);
12849                if (userId != thisUserId) {
12850                    continue;
12851                }
12852                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
12853                while (it.hasNext()) {
12854                    PersistentPreferredActivity ppa = it.next();
12855                    // Mark entry for removal only if it matches the package name.
12856                    if (ppa.mComponent.getPackageName().equals(packageName)) {
12857                        if (removed == null) {
12858                            removed = new ArrayList<PersistentPreferredActivity>();
12859                        }
12860                        removed.add(ppa);
12861                    }
12862                }
12863                if (removed != null) {
12864                    for (int j=0; j<removed.size(); j++) {
12865                        PersistentPreferredActivity ppa = removed.get(j);
12866                        ppir.removeFilter(ppa);
12867                    }
12868                    changed = true;
12869                }
12870            }
12871
12872            if (changed) {
12873                scheduleWritePackageRestrictionsLocked(userId);
12874            }
12875        }
12876    }
12877
12878    /**
12879     * Non-Binder method, support for the backup/restore mechanism: write the
12880     * full set of preferred activities in its canonical XML format.  Returns true
12881     * on success; false otherwise.
12882     */
12883    @Override
12884    public byte[] getPreferredActivityBackup(int userId) {
12885        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
12886            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
12887        }
12888
12889        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
12890        try {
12891            final XmlSerializer serializer = new FastXmlSerializer();
12892            serializer.setOutput(dataStream, "utf-8");
12893            serializer.startDocument(null, true);
12894            serializer.startTag(null, TAG_PREFERRED_BACKUP);
12895
12896            synchronized (mPackages) {
12897                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
12898            }
12899
12900            serializer.endTag(null, TAG_PREFERRED_BACKUP);
12901            serializer.endDocument();
12902            serializer.flush();
12903        } catch (Exception e) {
12904            if (DEBUG_BACKUP) {
12905                Slog.e(TAG, "Unable to write preferred activities for backup", e);
12906            }
12907            return null;
12908        }
12909
12910        return dataStream.toByteArray();
12911    }
12912
12913    @Override
12914    public void restorePreferredActivities(byte[] backup, int userId) {
12915        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
12916            throw new SecurityException("Only the system may call restorePreferredActivities()");
12917        }
12918
12919        try {
12920            final XmlPullParser parser = Xml.newPullParser();
12921            parser.setInput(new ByteArrayInputStream(backup), null);
12922
12923            int type;
12924            while ((type = parser.next()) != XmlPullParser.START_TAG
12925                    && type != XmlPullParser.END_DOCUMENT) {
12926            }
12927            if (type != XmlPullParser.START_TAG) {
12928                // oops didn't find a start tag?!
12929                if (DEBUG_BACKUP) {
12930                    Slog.e(TAG, "Didn't find start tag during restore");
12931                }
12932                return;
12933            }
12934
12935            // this is supposed to be TAG_PREFERRED_BACKUP
12936            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
12937                if (DEBUG_BACKUP) {
12938                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
12939                }
12940                return;
12941            }
12942
12943            // skip interfering stuff, then we're aligned with the backing implementation
12944            while ((type = parser.next()) == XmlPullParser.TEXT) { }
12945            synchronized (mPackages) {
12946                mSettings.readPreferredActivitiesLPw(parser, userId);
12947            }
12948        } catch (Exception e) {
12949            if (DEBUG_BACKUP) {
12950                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
12951            }
12952        }
12953    }
12954
12955    @Override
12956    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
12957            int sourceUserId, int targetUserId, int flags) {
12958        mContext.enforceCallingOrSelfPermission(
12959                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12960        int callingUid = Binder.getCallingUid();
12961        enforceOwnerRights(ownerPackage, callingUid);
12962        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12963        if (intentFilter.countActions() == 0) {
12964            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
12965            return;
12966        }
12967        synchronized (mPackages) {
12968            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
12969                    ownerPackage, targetUserId, flags);
12970            CrossProfileIntentResolver resolver =
12971                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12972            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
12973            // We have all those whose filter is equal. Now checking if the rest is equal as well.
12974            if (existing != null) {
12975                int size = existing.size();
12976                for (int i = 0; i < size; i++) {
12977                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
12978                        return;
12979                    }
12980                }
12981            }
12982            resolver.addFilter(newFilter);
12983            scheduleWritePackageRestrictionsLocked(sourceUserId);
12984        }
12985    }
12986
12987    @Override
12988    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
12989        mContext.enforceCallingOrSelfPermission(
12990                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12991        int callingUid = Binder.getCallingUid();
12992        enforceOwnerRights(ownerPackage, callingUid);
12993        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12994        synchronized (mPackages) {
12995            CrossProfileIntentResolver resolver =
12996                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12997            ArraySet<CrossProfileIntentFilter> set =
12998                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
12999            for (CrossProfileIntentFilter filter : set) {
13000                if (filter.getOwnerPackage().equals(ownerPackage)) {
13001                    resolver.removeFilter(filter);
13002                }
13003            }
13004            scheduleWritePackageRestrictionsLocked(sourceUserId);
13005        }
13006    }
13007
13008    // Enforcing that callingUid is owning pkg on userId
13009    private void enforceOwnerRights(String pkg, int callingUid) {
13010        // The system owns everything.
13011        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13012            return;
13013        }
13014        int callingUserId = UserHandle.getUserId(callingUid);
13015        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13016        if (pi == null) {
13017            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13018                    + callingUserId);
13019        }
13020        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13021            throw new SecurityException("Calling uid " + callingUid
13022                    + " does not own package " + pkg);
13023        }
13024    }
13025
13026    @Override
13027    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13028        Intent intent = new Intent(Intent.ACTION_MAIN);
13029        intent.addCategory(Intent.CATEGORY_HOME);
13030
13031        final int callingUserId = UserHandle.getCallingUserId();
13032        List<ResolveInfo> list = queryIntentActivities(intent, null,
13033                PackageManager.GET_META_DATA, callingUserId);
13034        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13035                true, false, false, callingUserId);
13036
13037        allHomeCandidates.clear();
13038        if (list != null) {
13039            for (ResolveInfo ri : list) {
13040                allHomeCandidates.add(ri);
13041            }
13042        }
13043        return (preferred == null || preferred.activityInfo == null)
13044                ? null
13045                : new ComponentName(preferred.activityInfo.packageName,
13046                        preferred.activityInfo.name);
13047    }
13048
13049    @Override
13050    public void setApplicationEnabledSetting(String appPackageName,
13051            int newState, int flags, int userId, String callingPackage) {
13052        if (!sUserManager.exists(userId)) return;
13053        if (callingPackage == null) {
13054            callingPackage = Integer.toString(Binder.getCallingUid());
13055        }
13056        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13057    }
13058
13059    @Override
13060    public void setComponentEnabledSetting(ComponentName componentName,
13061            int newState, int flags, int userId) {
13062        if (!sUserManager.exists(userId)) return;
13063        setEnabledSetting(componentName.getPackageName(),
13064                componentName.getClassName(), newState, flags, userId, null);
13065    }
13066
13067    private void setEnabledSetting(final String packageName, String className, int newState,
13068            final int flags, int userId, String callingPackage) {
13069        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13070              || newState == COMPONENT_ENABLED_STATE_ENABLED
13071              || newState == COMPONENT_ENABLED_STATE_DISABLED
13072              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13073              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13074            throw new IllegalArgumentException("Invalid new component state: "
13075                    + newState);
13076        }
13077        PackageSetting pkgSetting;
13078        final int uid = Binder.getCallingUid();
13079        final int permission = mContext.checkCallingOrSelfPermission(
13080                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13081        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13082        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13083        boolean sendNow = false;
13084        boolean isApp = (className == null);
13085        String componentName = isApp ? packageName : className;
13086        int packageUid = -1;
13087        ArrayList<String> components;
13088
13089        // writer
13090        synchronized (mPackages) {
13091            pkgSetting = mSettings.mPackages.get(packageName);
13092            if (pkgSetting == null) {
13093                if (className == null) {
13094                    throw new IllegalArgumentException(
13095                            "Unknown package: " + packageName);
13096                }
13097                throw new IllegalArgumentException(
13098                        "Unknown component: " + packageName
13099                        + "/" + className);
13100            }
13101            // Allow root and verify that userId is not being specified by a different user
13102            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13103                throw new SecurityException(
13104                        "Permission Denial: attempt to change component state from pid="
13105                        + Binder.getCallingPid()
13106                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13107            }
13108            if (className == null) {
13109                // We're dealing with an application/package level state change
13110                if (pkgSetting.getEnabled(userId) == newState) {
13111                    // Nothing to do
13112                    return;
13113                }
13114                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13115                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13116                    // Don't care about who enables an app.
13117                    callingPackage = null;
13118                }
13119                pkgSetting.setEnabled(newState, userId, callingPackage);
13120                // pkgSetting.pkg.mSetEnabled = newState;
13121            } else {
13122                // We're dealing with a component level state change
13123                // First, verify that this is a valid class name.
13124                PackageParser.Package pkg = pkgSetting.pkg;
13125                if (pkg == null || !pkg.hasComponentClassName(className)) {
13126                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13127                        throw new IllegalArgumentException("Component class " + className
13128                                + " does not exist in " + packageName);
13129                    } else {
13130                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13131                                + className + " does not exist in " + packageName);
13132                    }
13133                }
13134                switch (newState) {
13135                case COMPONENT_ENABLED_STATE_ENABLED:
13136                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13137                        return;
13138                    }
13139                    break;
13140                case COMPONENT_ENABLED_STATE_DISABLED:
13141                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13142                        return;
13143                    }
13144                    break;
13145                case COMPONENT_ENABLED_STATE_DEFAULT:
13146                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13147                        return;
13148                    }
13149                    break;
13150                default:
13151                    Slog.e(TAG, "Invalid new component state: " + newState);
13152                    return;
13153                }
13154            }
13155            scheduleWritePackageRestrictionsLocked(userId);
13156            components = mPendingBroadcasts.get(userId, packageName);
13157            final boolean newPackage = components == null;
13158            if (newPackage) {
13159                components = new ArrayList<String>();
13160            }
13161            if (!components.contains(componentName)) {
13162                components.add(componentName);
13163            }
13164            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13165                sendNow = true;
13166                // Purge entry from pending broadcast list if another one exists already
13167                // since we are sending one right away.
13168                mPendingBroadcasts.remove(userId, packageName);
13169            } else {
13170                if (newPackage) {
13171                    mPendingBroadcasts.put(userId, packageName, components);
13172                }
13173                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13174                    // Schedule a message
13175                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13176                }
13177            }
13178        }
13179
13180        long callingId = Binder.clearCallingIdentity();
13181        try {
13182            if (sendNow) {
13183                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13184                sendPackageChangedBroadcast(packageName,
13185                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13186            }
13187        } finally {
13188            Binder.restoreCallingIdentity(callingId);
13189        }
13190    }
13191
13192    private void sendPackageChangedBroadcast(String packageName,
13193            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13194        if (DEBUG_INSTALL)
13195            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13196                    + componentNames);
13197        Bundle extras = new Bundle(4);
13198        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13199        String nameList[] = new String[componentNames.size()];
13200        componentNames.toArray(nameList);
13201        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13202        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13203        extras.putInt(Intent.EXTRA_UID, packageUid);
13204        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13205                new int[] {UserHandle.getUserId(packageUid)});
13206    }
13207
13208    @Override
13209    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13210        if (!sUserManager.exists(userId)) return;
13211        final int uid = Binder.getCallingUid();
13212        final int permission = mContext.checkCallingOrSelfPermission(
13213                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13214        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13215        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13216        // writer
13217        synchronized (mPackages) {
13218            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13219                    allowedByPermission, uid, userId)) {
13220                scheduleWritePackageRestrictionsLocked(userId);
13221            }
13222        }
13223    }
13224
13225    @Override
13226    public String getInstallerPackageName(String packageName) {
13227        // reader
13228        synchronized (mPackages) {
13229            return mSettings.getInstallerPackageNameLPr(packageName);
13230        }
13231    }
13232
13233    @Override
13234    public int getApplicationEnabledSetting(String packageName, int userId) {
13235        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13236        int uid = Binder.getCallingUid();
13237        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13238        // reader
13239        synchronized (mPackages) {
13240            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13241        }
13242    }
13243
13244    @Override
13245    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13246        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13247        int uid = Binder.getCallingUid();
13248        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13249        // reader
13250        synchronized (mPackages) {
13251            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13252        }
13253    }
13254
13255    @Override
13256    public void enterSafeMode() {
13257        enforceSystemOrRoot("Only the system can request entering safe mode");
13258
13259        if (!mSystemReady) {
13260            mSafeMode = true;
13261        }
13262    }
13263
13264    @Override
13265    public void systemReady() {
13266        mSystemReady = true;
13267
13268        // Read the compatibilty setting when the system is ready.
13269        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13270                mContext.getContentResolver(),
13271                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13272        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13273        if (DEBUG_SETTINGS) {
13274            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13275        }
13276
13277        synchronized (mPackages) {
13278            // Verify that all of the preferred activity components actually
13279            // exist.  It is possible for applications to be updated and at
13280            // that point remove a previously declared activity component that
13281            // had been set as a preferred activity.  We try to clean this up
13282            // the next time we encounter that preferred activity, but it is
13283            // possible for the user flow to never be able to return to that
13284            // situation so here we do a sanity check to make sure we haven't
13285            // left any junk around.
13286            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13287            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13288                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13289                removed.clear();
13290                for (PreferredActivity pa : pir.filterSet()) {
13291                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13292                        removed.add(pa);
13293                    }
13294                }
13295                if (removed.size() > 0) {
13296                    for (int r=0; r<removed.size(); r++) {
13297                        PreferredActivity pa = removed.get(r);
13298                        Slog.w(TAG, "Removing dangling preferred activity: "
13299                                + pa.mPref.mComponent);
13300                        pir.removeFilter(pa);
13301                    }
13302                    mSettings.writePackageRestrictionsLPr(
13303                            mSettings.mPreferredActivities.keyAt(i));
13304                }
13305            }
13306        }
13307        sUserManager.systemReady();
13308
13309        // Kick off any messages waiting for system ready
13310        if (mPostSystemReadyMessages != null) {
13311            for (Message msg : mPostSystemReadyMessages) {
13312                msg.sendToTarget();
13313            }
13314            mPostSystemReadyMessages = null;
13315        }
13316
13317        // Watch for external volumes that come and go over time
13318        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13319        storage.registerListener(mStorageListener);
13320
13321        mInstallerService.systemReady();
13322    }
13323
13324    @Override
13325    public boolean isSafeMode() {
13326        return mSafeMode;
13327    }
13328
13329    @Override
13330    public boolean hasSystemUidErrors() {
13331        return mHasSystemUidErrors;
13332    }
13333
13334    static String arrayToString(int[] array) {
13335        StringBuffer buf = new StringBuffer(128);
13336        buf.append('[');
13337        if (array != null) {
13338            for (int i=0; i<array.length; i++) {
13339                if (i > 0) buf.append(", ");
13340                buf.append(array[i]);
13341            }
13342        }
13343        buf.append(']');
13344        return buf.toString();
13345    }
13346
13347    static class DumpState {
13348        public static final int DUMP_LIBS = 1 << 0;
13349        public static final int DUMP_FEATURES = 1 << 1;
13350        public static final int DUMP_RESOLVERS = 1 << 2;
13351        public static final int DUMP_PERMISSIONS = 1 << 3;
13352        public static final int DUMP_PACKAGES = 1 << 4;
13353        public static final int DUMP_SHARED_USERS = 1 << 5;
13354        public static final int DUMP_MESSAGES = 1 << 6;
13355        public static final int DUMP_PROVIDERS = 1 << 7;
13356        public static final int DUMP_VERIFIERS = 1 << 8;
13357        public static final int DUMP_PREFERRED = 1 << 9;
13358        public static final int DUMP_PREFERRED_XML = 1 << 10;
13359        public static final int DUMP_KEYSETS = 1 << 11;
13360        public static final int DUMP_VERSION = 1 << 12;
13361        public static final int DUMP_INSTALLS = 1 << 13;
13362        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13363        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13364
13365        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13366
13367        private int mTypes;
13368
13369        private int mOptions;
13370
13371        private boolean mTitlePrinted;
13372
13373        private SharedUserSetting mSharedUser;
13374
13375        public boolean isDumping(int type) {
13376            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13377                return true;
13378            }
13379
13380            return (mTypes & type) != 0;
13381        }
13382
13383        public void setDump(int type) {
13384            mTypes |= type;
13385        }
13386
13387        public boolean isOptionEnabled(int option) {
13388            return (mOptions & option) != 0;
13389        }
13390
13391        public void setOptionEnabled(int option) {
13392            mOptions |= option;
13393        }
13394
13395        public boolean onTitlePrinted() {
13396            final boolean printed = mTitlePrinted;
13397            mTitlePrinted = true;
13398            return printed;
13399        }
13400
13401        public boolean getTitlePrinted() {
13402            return mTitlePrinted;
13403        }
13404
13405        public void setTitlePrinted(boolean enabled) {
13406            mTitlePrinted = enabled;
13407        }
13408
13409        public SharedUserSetting getSharedUser() {
13410            return mSharedUser;
13411        }
13412
13413        public void setSharedUser(SharedUserSetting user) {
13414            mSharedUser = user;
13415        }
13416    }
13417
13418    @Override
13419    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13420        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13421                != PackageManager.PERMISSION_GRANTED) {
13422            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13423                    + Binder.getCallingPid()
13424                    + ", uid=" + Binder.getCallingUid()
13425                    + " without permission "
13426                    + android.Manifest.permission.DUMP);
13427            return;
13428        }
13429
13430        DumpState dumpState = new DumpState();
13431        boolean fullPreferred = false;
13432        boolean checkin = false;
13433
13434        String packageName = null;
13435
13436        int opti = 0;
13437        while (opti < args.length) {
13438            String opt = args[opti];
13439            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13440                break;
13441            }
13442            opti++;
13443
13444            if ("-a".equals(opt)) {
13445                // Right now we only know how to print all.
13446            } else if ("-h".equals(opt)) {
13447                pw.println("Package manager dump options:");
13448                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13449                pw.println("    --checkin: dump for a checkin");
13450                pw.println("    -f: print details of intent filters");
13451                pw.println("    -h: print this help");
13452                pw.println("  cmd may be one of:");
13453                pw.println("    l[ibraries]: list known shared libraries");
13454                pw.println("    f[ibraries]: list device features");
13455                pw.println("    k[eysets]: print known keysets");
13456                pw.println("    r[esolvers]: dump intent resolvers");
13457                pw.println("    perm[issions]: dump permissions");
13458                pw.println("    pref[erred]: print preferred package settings");
13459                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13460                pw.println("    prov[iders]: dump content providers");
13461                pw.println("    p[ackages]: dump installed packages");
13462                pw.println("    s[hared-users]: dump shared user IDs");
13463                pw.println("    m[essages]: print collected runtime messages");
13464                pw.println("    v[erifiers]: print package verifier info");
13465                pw.println("    version: print database version info");
13466                pw.println("    write: write current settings now");
13467                pw.println("    <package.name>: info about given package");
13468                pw.println("    installs: details about install sessions");
13469                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13470                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13471                return;
13472            } else if ("--checkin".equals(opt)) {
13473                checkin = true;
13474            } else if ("-f".equals(opt)) {
13475                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13476            } else {
13477                pw.println("Unknown argument: " + opt + "; use -h for help");
13478            }
13479        }
13480
13481        // Is the caller requesting to dump a particular piece of data?
13482        if (opti < args.length) {
13483            String cmd = args[opti];
13484            opti++;
13485            // Is this a package name?
13486            if ("android".equals(cmd) || cmd.contains(".")) {
13487                packageName = cmd;
13488                // When dumping a single package, we always dump all of its
13489                // filter information since the amount of data will be reasonable.
13490                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13491            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13492                dumpState.setDump(DumpState.DUMP_LIBS);
13493            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13494                dumpState.setDump(DumpState.DUMP_FEATURES);
13495            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13496                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13497            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13498                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13499            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13500                dumpState.setDump(DumpState.DUMP_PREFERRED);
13501            } else if ("preferred-xml".equals(cmd)) {
13502                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13503                if (opti < args.length && "--full".equals(args[opti])) {
13504                    fullPreferred = true;
13505                    opti++;
13506                }
13507            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13508                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13509            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13510                dumpState.setDump(DumpState.DUMP_PACKAGES);
13511            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13512                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13513            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13514                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13515            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13516                dumpState.setDump(DumpState.DUMP_MESSAGES);
13517            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13518                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13519            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13520                    || "intent-filter-verifiers".equals(cmd)) {
13521                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13522            } else if ("version".equals(cmd)) {
13523                dumpState.setDump(DumpState.DUMP_VERSION);
13524            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13525                dumpState.setDump(DumpState.DUMP_KEYSETS);
13526            } else if ("installs".equals(cmd)) {
13527                dumpState.setDump(DumpState.DUMP_INSTALLS);
13528            } else if ("write".equals(cmd)) {
13529                synchronized (mPackages) {
13530                    mSettings.writeLPr();
13531                    pw.println("Settings written.");
13532                    return;
13533                }
13534            }
13535        }
13536
13537        if (checkin) {
13538            pw.println("vers,1");
13539        }
13540
13541        // reader
13542        synchronized (mPackages) {
13543            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13544                if (!checkin) {
13545                    if (dumpState.onTitlePrinted())
13546                        pw.println();
13547                    pw.println("Database versions:");
13548                    pw.print("  SDK Version:");
13549                    pw.print(" internal=");
13550                    pw.print(mSettings.mInternalSdkPlatform);
13551                    pw.print(" external=");
13552                    pw.println(mSettings.mExternalSdkPlatform);
13553                    pw.print("  DB Version:");
13554                    pw.print(" internal=");
13555                    pw.print(mSettings.mInternalDatabaseVersion);
13556                    pw.print(" external=");
13557                    pw.println(mSettings.mExternalDatabaseVersion);
13558                }
13559            }
13560
13561            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13562                if (!checkin) {
13563                    if (dumpState.onTitlePrinted())
13564                        pw.println();
13565                    pw.println("Verifiers:");
13566                    pw.print("  Required: ");
13567                    pw.print(mRequiredVerifierPackage);
13568                    pw.print(" (uid=");
13569                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13570                    pw.println(")");
13571                } else if (mRequiredVerifierPackage != null) {
13572                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13573                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13574                }
13575            }
13576
13577            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13578                    packageName == null) {
13579                if (mIntentFilterVerifierComponent != null) {
13580                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13581                    if (!checkin) {
13582                        if (dumpState.onTitlePrinted())
13583                            pw.println();
13584                        pw.println("Intent Filter Verifier:");
13585                        pw.print("  Using: ");
13586                        pw.print(verifierPackageName);
13587                        pw.print(" (uid=");
13588                        pw.print(getPackageUid(verifierPackageName, 0));
13589                        pw.println(")");
13590                    } else if (verifierPackageName != null) {
13591                        pw.print("ifv,"); pw.print(verifierPackageName);
13592                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13593                    }
13594                } else {
13595                    pw.println();
13596                    pw.println("No Intent Filter Verifier available!");
13597                }
13598            }
13599
13600            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13601                boolean printedHeader = false;
13602                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13603                while (it.hasNext()) {
13604                    String name = it.next();
13605                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13606                    if (!checkin) {
13607                        if (!printedHeader) {
13608                            if (dumpState.onTitlePrinted())
13609                                pw.println();
13610                            pw.println("Libraries:");
13611                            printedHeader = true;
13612                        }
13613                        pw.print("  ");
13614                    } else {
13615                        pw.print("lib,");
13616                    }
13617                    pw.print(name);
13618                    if (!checkin) {
13619                        pw.print(" -> ");
13620                    }
13621                    if (ent.path != null) {
13622                        if (!checkin) {
13623                            pw.print("(jar) ");
13624                            pw.print(ent.path);
13625                        } else {
13626                            pw.print(",jar,");
13627                            pw.print(ent.path);
13628                        }
13629                    } else {
13630                        if (!checkin) {
13631                            pw.print("(apk) ");
13632                            pw.print(ent.apk);
13633                        } else {
13634                            pw.print(",apk,");
13635                            pw.print(ent.apk);
13636                        }
13637                    }
13638                    pw.println();
13639                }
13640            }
13641
13642            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
13643                if (dumpState.onTitlePrinted())
13644                    pw.println();
13645                if (!checkin) {
13646                    pw.println("Features:");
13647                }
13648                Iterator<String> it = mAvailableFeatures.keySet().iterator();
13649                while (it.hasNext()) {
13650                    String name = it.next();
13651                    if (!checkin) {
13652                        pw.print("  ");
13653                    } else {
13654                        pw.print("feat,");
13655                    }
13656                    pw.println(name);
13657                }
13658            }
13659
13660            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
13661                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
13662                        : "Activity Resolver Table:", "  ", packageName,
13663                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13664                    dumpState.setTitlePrinted(true);
13665                }
13666                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
13667                        : "Receiver Resolver Table:", "  ", packageName,
13668                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13669                    dumpState.setTitlePrinted(true);
13670                }
13671                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
13672                        : "Service Resolver Table:", "  ", packageName,
13673                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13674                    dumpState.setTitlePrinted(true);
13675                }
13676                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
13677                        : "Provider Resolver Table:", "  ", packageName,
13678                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13679                    dumpState.setTitlePrinted(true);
13680                }
13681            }
13682
13683            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
13684                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13685                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13686                    int user = mSettings.mPreferredActivities.keyAt(i);
13687                    if (pir.dump(pw,
13688                            dumpState.getTitlePrinted()
13689                                ? "\nPreferred Activities User " + user + ":"
13690                                : "Preferred Activities User " + user + ":", "  ",
13691                            packageName, true, false)) {
13692                        dumpState.setTitlePrinted(true);
13693                    }
13694                }
13695            }
13696
13697            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
13698                pw.flush();
13699                FileOutputStream fout = new FileOutputStream(fd);
13700                BufferedOutputStream str = new BufferedOutputStream(fout);
13701                XmlSerializer serializer = new FastXmlSerializer();
13702                try {
13703                    serializer.setOutput(str, "utf-8");
13704                    serializer.startDocument(null, true);
13705                    serializer.setFeature(
13706                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
13707                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
13708                    serializer.endDocument();
13709                    serializer.flush();
13710                } catch (IllegalArgumentException e) {
13711                    pw.println("Failed writing: " + e);
13712                } catch (IllegalStateException e) {
13713                    pw.println("Failed writing: " + e);
13714                } catch (IOException e) {
13715                    pw.println("Failed writing: " + e);
13716                }
13717            }
13718
13719            if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) {
13720                pw.println();
13721                int count = mSettings.mPackages.size();
13722                if (count == 0) {
13723                    pw.println("No domain preferred apps!");
13724                    pw.println();
13725                } else {
13726                    final String prefix = "  ";
13727                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
13728                    if (allPackageSettings.size() == 0) {
13729                        pw.println("No domain preferred apps!");
13730                        pw.println();
13731                    } else {
13732                        pw.println("Domain preferred apps status:");
13733                        pw.println();
13734                        count = 0;
13735                        for (PackageSetting ps : allPackageSettings) {
13736                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13737                            if (ivi == null || ivi.getPackageName() == null) continue;
13738                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
13739                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
13740                            pw.println(prefix + "Status: " + ivi.getStatusString());
13741                            pw.println();
13742                            count++;
13743                        }
13744                        if (count == 0) {
13745                            pw.println(prefix + "No domain preferred app status!");
13746                            pw.println();
13747                        }
13748                        for (int userId : sUserManager.getUserIds()) {
13749                            pw.println("Domain preferred apps for User " + userId + ":");
13750                            pw.println();
13751                            count = 0;
13752                            for (PackageSetting ps : allPackageSettings) {
13753                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13754                                if (ivi == null || ivi.getPackageName() == null) {
13755                                    continue;
13756                                }
13757                                final int status = ps.getDomainVerificationStatusForUser(userId);
13758                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
13759                                    continue;
13760                                }
13761                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
13762                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
13763                                String statusStr = IntentFilterVerificationInfo.
13764                                        getStatusStringFromValue(status);
13765                                pw.println(prefix + "Status: " + statusStr);
13766                                pw.println();
13767                                count++;
13768                            }
13769                            if (count == 0) {
13770                                pw.println(prefix + "No domain preferred apps!");
13771                                pw.println();
13772                            }
13773                        }
13774                    }
13775                }
13776            }
13777
13778            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
13779                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
13780                if (packageName == null) {
13781                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
13782                        if (iperm == 0) {
13783                            if (dumpState.onTitlePrinted())
13784                                pw.println();
13785                            pw.println("AppOp Permissions:");
13786                        }
13787                        pw.print("  AppOp Permission ");
13788                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
13789                        pw.println(":");
13790                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
13791                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
13792                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
13793                        }
13794                    }
13795                }
13796            }
13797
13798            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
13799                boolean printedSomething = false;
13800                for (PackageParser.Provider p : mProviders.mProviders.values()) {
13801                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13802                        continue;
13803                    }
13804                    if (!printedSomething) {
13805                        if (dumpState.onTitlePrinted())
13806                            pw.println();
13807                        pw.println("Registered ContentProviders:");
13808                        printedSomething = true;
13809                    }
13810                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
13811                    pw.print("    "); pw.println(p.toString());
13812                }
13813                printedSomething = false;
13814                for (Map.Entry<String, PackageParser.Provider> entry :
13815                        mProvidersByAuthority.entrySet()) {
13816                    PackageParser.Provider p = entry.getValue();
13817                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13818                        continue;
13819                    }
13820                    if (!printedSomething) {
13821                        if (dumpState.onTitlePrinted())
13822                            pw.println();
13823                        pw.println("ContentProvider Authorities:");
13824                        printedSomething = true;
13825                    }
13826                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
13827                    pw.print("    "); pw.println(p.toString());
13828                    if (p.info != null && p.info.applicationInfo != null) {
13829                        final String appInfo = p.info.applicationInfo.toString();
13830                        pw.print("      applicationInfo="); pw.println(appInfo);
13831                    }
13832                }
13833            }
13834
13835            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
13836                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
13837            }
13838
13839            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
13840                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
13841            }
13842
13843            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
13844                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
13845            }
13846
13847            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
13848                // XXX should handle packageName != null by dumping only install data that
13849                // the given package is involved with.
13850                if (dumpState.onTitlePrinted()) pw.println();
13851                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
13852            }
13853
13854            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
13855                if (dumpState.onTitlePrinted()) pw.println();
13856                mSettings.dumpReadMessagesLPr(pw, dumpState);
13857
13858                pw.println();
13859                pw.println("Package warning messages:");
13860                BufferedReader in = null;
13861                String line = null;
13862                try {
13863                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
13864                    while ((line = in.readLine()) != null) {
13865                        if (line.contains("ignored: updated version")) continue;
13866                        pw.println(line);
13867                    }
13868                } catch (IOException ignored) {
13869                } finally {
13870                    IoUtils.closeQuietly(in);
13871                }
13872            }
13873
13874            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
13875                BufferedReader in = null;
13876                String line = null;
13877                try {
13878                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
13879                    while ((line = in.readLine()) != null) {
13880                        if (line.contains("ignored: updated version")) continue;
13881                        pw.print("msg,");
13882                        pw.println(line);
13883                    }
13884                } catch (IOException ignored) {
13885                } finally {
13886                    IoUtils.closeQuietly(in);
13887                }
13888            }
13889        }
13890    }
13891
13892    // ------- apps on sdcard specific code -------
13893    static final boolean DEBUG_SD_INSTALL = false;
13894
13895    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
13896
13897    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
13898
13899    private boolean mMediaMounted = false;
13900
13901    static String getEncryptKey() {
13902        try {
13903            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
13904                    SD_ENCRYPTION_KEYSTORE_NAME);
13905            if (sdEncKey == null) {
13906                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
13907                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
13908                if (sdEncKey == null) {
13909                    Slog.e(TAG, "Failed to create encryption keys");
13910                    return null;
13911                }
13912            }
13913            return sdEncKey;
13914        } catch (NoSuchAlgorithmException nsae) {
13915            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
13916            return null;
13917        } catch (IOException ioe) {
13918            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
13919            return null;
13920        }
13921    }
13922
13923    /*
13924     * Update media status on PackageManager.
13925     */
13926    @Override
13927    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
13928        int callingUid = Binder.getCallingUid();
13929        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
13930            throw new SecurityException("Media status can only be updated by the system");
13931        }
13932        // reader; this apparently protects mMediaMounted, but should probably
13933        // be a different lock in that case.
13934        synchronized (mPackages) {
13935            Log.i(TAG, "Updating external media status from "
13936                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
13937                    + (mediaStatus ? "mounted" : "unmounted"));
13938            if (DEBUG_SD_INSTALL)
13939                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
13940                        + ", mMediaMounted=" + mMediaMounted);
13941            if (mediaStatus == mMediaMounted) {
13942                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
13943                        : 0, -1);
13944                mHandler.sendMessage(msg);
13945                return;
13946            }
13947            mMediaMounted = mediaStatus;
13948        }
13949        // Queue up an async operation since the package installation may take a
13950        // little while.
13951        mHandler.post(new Runnable() {
13952            public void run() {
13953                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
13954            }
13955        });
13956    }
13957
13958    /**
13959     * Called by MountService when the initial ASECs to scan are available.
13960     * Should block until all the ASEC containers are finished being scanned.
13961     */
13962    public void scanAvailableAsecs() {
13963        updateExternalMediaStatusInner(true, false, false);
13964        if (mShouldRestoreconData) {
13965            SELinuxMMAC.setRestoreconDone();
13966            mShouldRestoreconData = false;
13967        }
13968    }
13969
13970    /*
13971     * Collect information of applications on external media, map them against
13972     * existing containers and update information based on current mount status.
13973     * Please note that we always have to report status if reportStatus has been
13974     * set to true especially when unloading packages.
13975     */
13976    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
13977            boolean externalStorage) {
13978        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
13979        int[] uidArr = EmptyArray.INT;
13980
13981        final String[] list = PackageHelper.getSecureContainerList();
13982        if (ArrayUtils.isEmpty(list)) {
13983            Log.i(TAG, "No secure containers found");
13984        } else {
13985            // Process list of secure containers and categorize them
13986            // as active or stale based on their package internal state.
13987
13988            // reader
13989            synchronized (mPackages) {
13990                for (String cid : list) {
13991                    // Leave stages untouched for now; installer service owns them
13992                    if (PackageInstallerService.isStageName(cid)) continue;
13993
13994                    if (DEBUG_SD_INSTALL)
13995                        Log.i(TAG, "Processing container " + cid);
13996                    String pkgName = getAsecPackageName(cid);
13997                    if (pkgName == null) {
13998                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
13999                        continue;
14000                    }
14001                    if (DEBUG_SD_INSTALL)
14002                        Log.i(TAG, "Looking for pkg : " + pkgName);
14003
14004                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14005                    if (ps == null) {
14006                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14007                        continue;
14008                    }
14009
14010                    /*
14011                     * Skip packages that are not external if we're unmounting
14012                     * external storage.
14013                     */
14014                    if (externalStorage && !isMounted && !isExternal(ps)) {
14015                        continue;
14016                    }
14017
14018                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14019                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14020                    // The package status is changed only if the code path
14021                    // matches between settings and the container id.
14022                    if (ps.codePathString != null
14023                            && ps.codePathString.startsWith(args.getCodePath())) {
14024                        if (DEBUG_SD_INSTALL) {
14025                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14026                                    + " at code path: " + ps.codePathString);
14027                        }
14028
14029                        // We do have a valid package installed on sdcard
14030                        processCids.put(args, ps.codePathString);
14031                        final int uid = ps.appId;
14032                        if (uid != -1) {
14033                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14034                        }
14035                    } else {
14036                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14037                                + ps.codePathString);
14038                    }
14039                }
14040            }
14041
14042            Arrays.sort(uidArr);
14043        }
14044
14045        // Process packages with valid entries.
14046        if (isMounted) {
14047            if (DEBUG_SD_INSTALL)
14048                Log.i(TAG, "Loading packages");
14049            loadMediaPackages(processCids, uidArr);
14050            startCleaningPackages();
14051            mInstallerService.onSecureContainersAvailable();
14052        } else {
14053            if (DEBUG_SD_INSTALL)
14054                Log.i(TAG, "Unloading packages");
14055            unloadMediaPackages(processCids, uidArr, reportStatus);
14056        }
14057    }
14058
14059    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14060            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14061        final int size = infos.size();
14062        final String[] packageNames = new String[size];
14063        final int[] packageUids = new int[size];
14064        for (int i = 0; i < size; i++) {
14065            final ApplicationInfo info = infos.get(i);
14066            packageNames[i] = info.packageName;
14067            packageUids[i] = info.uid;
14068        }
14069        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14070                finishedReceiver);
14071    }
14072
14073    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14074            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14075        sendResourcesChangedBroadcast(mediaStatus, replacing,
14076                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14077    }
14078
14079    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14080            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14081        int size = pkgList.length;
14082        if (size > 0) {
14083            // Send broadcasts here
14084            Bundle extras = new Bundle();
14085            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14086            if (uidArr != null) {
14087                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14088            }
14089            if (replacing) {
14090                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14091            }
14092            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14093                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14094            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14095        }
14096    }
14097
14098   /*
14099     * Look at potentially valid container ids from processCids If package
14100     * information doesn't match the one on record or package scanning fails,
14101     * the cid is added to list of removeCids. We currently don't delete stale
14102     * containers.
14103     */
14104    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14105        ArrayList<String> pkgList = new ArrayList<String>();
14106        Set<AsecInstallArgs> keys = processCids.keySet();
14107
14108        for (AsecInstallArgs args : keys) {
14109            String codePath = processCids.get(args);
14110            if (DEBUG_SD_INSTALL)
14111                Log.i(TAG, "Loading container : " + args.cid);
14112            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14113            try {
14114                // Make sure there are no container errors first.
14115                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14116                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14117                            + " when installing from sdcard");
14118                    continue;
14119                }
14120                // Check code path here.
14121                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14122                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14123                            + " does not match one in settings " + codePath);
14124                    continue;
14125                }
14126                // Parse package
14127                int parseFlags = mDefParseFlags;
14128                if (args.isExternalAsec()) {
14129                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14130                }
14131                if (args.isFwdLocked()) {
14132                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14133                }
14134
14135                synchronized (mInstallLock) {
14136                    PackageParser.Package pkg = null;
14137                    try {
14138                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14139                    } catch (PackageManagerException e) {
14140                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14141                    }
14142                    // Scan the package
14143                    if (pkg != null) {
14144                        /*
14145                         * TODO why is the lock being held? doPostInstall is
14146                         * called in other places without the lock. This needs
14147                         * to be straightened out.
14148                         */
14149                        // writer
14150                        synchronized (mPackages) {
14151                            retCode = PackageManager.INSTALL_SUCCEEDED;
14152                            pkgList.add(pkg.packageName);
14153                            // Post process args
14154                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14155                                    pkg.applicationInfo.uid);
14156                        }
14157                    } else {
14158                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14159                    }
14160                }
14161
14162            } finally {
14163                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14164                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14165                }
14166            }
14167        }
14168        // writer
14169        synchronized (mPackages) {
14170            // If the platform SDK has changed since the last time we booted,
14171            // we need to re-grant app permission to catch any new ones that
14172            // appear. This is really a hack, and means that apps can in some
14173            // cases get permissions that the user didn't initially explicitly
14174            // allow... it would be nice to have some better way to handle
14175            // this situation.
14176            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14177            if (regrantPermissions)
14178                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14179                        + mSdkVersion + "; regranting permissions for external storage");
14180            mSettings.mExternalSdkPlatform = mSdkVersion;
14181
14182            // Make sure group IDs have been assigned, and any permission
14183            // changes in other apps are accounted for
14184            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14185                    | (regrantPermissions
14186                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14187                            : 0));
14188
14189            mSettings.updateExternalDatabaseVersion();
14190
14191            // can downgrade to reader
14192            // Persist settings
14193            mSettings.writeLPr();
14194        }
14195        // Send a broadcast to let everyone know we are done processing
14196        if (pkgList.size() > 0) {
14197            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14198        }
14199    }
14200
14201   /*
14202     * Utility method to unload a list of specified containers
14203     */
14204    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14205        // Just unmount all valid containers.
14206        for (AsecInstallArgs arg : cidArgs) {
14207            synchronized (mInstallLock) {
14208                arg.doPostDeleteLI(false);
14209           }
14210       }
14211   }
14212
14213    /*
14214     * Unload packages mounted on external media. This involves deleting package
14215     * data from internal structures, sending broadcasts about diabled packages,
14216     * gc'ing to free up references, unmounting all secure containers
14217     * corresponding to packages on external media, and posting a
14218     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14219     * that we always have to post this message if status has been requested no
14220     * matter what.
14221     */
14222    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14223            final boolean reportStatus) {
14224        if (DEBUG_SD_INSTALL)
14225            Log.i(TAG, "unloading media packages");
14226        ArrayList<String> pkgList = new ArrayList<String>();
14227        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14228        final Set<AsecInstallArgs> keys = processCids.keySet();
14229        for (AsecInstallArgs args : keys) {
14230            String pkgName = args.getPackageName();
14231            if (DEBUG_SD_INSTALL)
14232                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14233            // Delete package internally
14234            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14235            synchronized (mInstallLock) {
14236                boolean res = deletePackageLI(pkgName, null, false, null, null,
14237                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14238                if (res) {
14239                    pkgList.add(pkgName);
14240                } else {
14241                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14242                    failedList.add(args);
14243                }
14244            }
14245        }
14246
14247        // reader
14248        synchronized (mPackages) {
14249            // We didn't update the settings after removing each package;
14250            // write them now for all packages.
14251            mSettings.writeLPr();
14252        }
14253
14254        // We have to absolutely send UPDATED_MEDIA_STATUS only
14255        // after confirming that all the receivers processed the ordered
14256        // broadcast when packages get disabled, force a gc to clean things up.
14257        // and unload all the containers.
14258        if (pkgList.size() > 0) {
14259            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14260                    new IIntentReceiver.Stub() {
14261                public void performReceive(Intent intent, int resultCode, String data,
14262                        Bundle extras, boolean ordered, boolean sticky,
14263                        int sendingUser) throws RemoteException {
14264                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14265                            reportStatus ? 1 : 0, 1, keys);
14266                    mHandler.sendMessage(msg);
14267                }
14268            });
14269        } else {
14270            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14271                    keys);
14272            mHandler.sendMessage(msg);
14273        }
14274    }
14275
14276    private void loadPrivatePackages(VolumeInfo vol) {
14277        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14278        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14279        synchronized (mInstallLock) {
14280        synchronized (mPackages) {
14281            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14282            for (PackageSetting ps : packages) {
14283                final PackageParser.Package pkg;
14284                try {
14285                    pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14286                    loaded.add(pkg.applicationInfo);
14287                } catch (PackageManagerException e) {
14288                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14289                }
14290            }
14291
14292            // TODO: regrant any permissions that changed based since original install
14293
14294            mSettings.writeLPr();
14295        }
14296        }
14297
14298        Slog.d(TAG, "Loaded packages " + loaded);
14299        sendResourcesChangedBroadcast(true, false, loaded, null);
14300    }
14301
14302    private void unloadPrivatePackages(VolumeInfo vol) {
14303        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14304        synchronized (mInstallLock) {
14305        synchronized (mPackages) {
14306            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14307            for (PackageSetting ps : packages) {
14308                if (ps.pkg == null) continue;
14309
14310                final ApplicationInfo info = ps.pkg.applicationInfo;
14311                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14312                if (deletePackageLI(ps.name, null, false, null, null,
14313                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14314                    unloaded.add(info);
14315                } else {
14316                    Slog.w(TAG, "Failed to unload " + ps.codePath);
14317                }
14318            }
14319
14320            mSettings.writeLPr();
14321        }
14322        }
14323
14324        Slog.d(TAG, "Unloaded packages " + unloaded);
14325        sendResourcesChangedBroadcast(false, false, unloaded, null);
14326    }
14327
14328    private void unfreezePackage(String packageName) {
14329        synchronized (mPackages) {
14330            final PackageSetting ps = mSettings.mPackages.get(packageName);
14331            if (ps != null) {
14332                ps.frozen = false;
14333            }
14334        }
14335    }
14336
14337    @Override
14338    public int movePackage(final String packageName, final String volumeUuid) {
14339        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14340
14341        final int moveId = mNextMoveId.getAndIncrement();
14342        try {
14343            movePackageInternal(packageName, volumeUuid, moveId);
14344        } catch (PackageManagerException e) {
14345            Slog.d(TAG, "Failed to move " + packageName, e);
14346            mMoveCallbacks.notifyStatusChanged(moveId,
14347                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14348        }
14349        return moveId;
14350    }
14351
14352    private void movePackageInternal(final String packageName, final String volumeUuid,
14353            final int moveId) throws PackageManagerException {
14354        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14355        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14356        final PackageManager pm = mContext.getPackageManager();
14357
14358        final boolean currentAsec;
14359        final String currentVolumeUuid;
14360        final File codeFile;
14361        final String installerPackageName;
14362        final String packageAbiOverride;
14363        final int appId;
14364        final String seinfo;
14365        final String label;
14366
14367        // reader
14368        synchronized (mPackages) {
14369            final PackageParser.Package pkg = mPackages.get(packageName);
14370            final PackageSetting ps = mSettings.mPackages.get(packageName);
14371            if (pkg == null || ps == null) {
14372                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14373            }
14374
14375            if (pkg.applicationInfo.isSystemApp()) {
14376                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14377                        "Cannot move system application");
14378            }
14379
14380            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
14381                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14382                        "Package already moved to " + volumeUuid);
14383            }
14384
14385            final File probe = new File(pkg.codePath);
14386            final File probeOat = new File(probe, "oat");
14387            if (!probe.isDirectory() || !probeOat.isDirectory()) {
14388                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14389                        "Move only supported for modern cluster style installs");
14390            }
14391
14392            if (ps.frozen) {
14393                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14394                        "Failed to move already frozen package");
14395            }
14396            ps.frozen = true;
14397
14398            currentAsec = pkg.applicationInfo.isForwardLocked()
14399                    || pkg.applicationInfo.isExternalAsec();
14400            currentVolumeUuid = ps.volumeUuid;
14401            codeFile = new File(pkg.codePath);
14402            installerPackageName = ps.installerPackageName;
14403            packageAbiOverride = ps.cpuAbiOverrideString;
14404            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14405            seinfo = pkg.applicationInfo.seinfo;
14406            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
14407        }
14408
14409        // Now that we're guarded by frozen state, kill app during move
14410        killApplication(packageName, appId, "move pkg");
14411
14412        final Bundle extras = new Bundle();
14413        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
14414        extras.putString(Intent.EXTRA_TITLE, label);
14415        mMoveCallbacks.notifyCreated(moveId, extras);
14416
14417        int installFlags;
14418        final boolean moveCompleteApp;
14419        final File measurePath;
14420
14421        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
14422            installFlags = INSTALL_INTERNAL;
14423            moveCompleteApp = !currentAsec;
14424            measurePath = Environment.getDataAppDirectory(volumeUuid);
14425        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
14426            installFlags = INSTALL_EXTERNAL;
14427            moveCompleteApp = false;
14428            measurePath = storage.getPrimaryPhysicalVolume().getPath();
14429        } else {
14430            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
14431            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
14432                    || !volume.isMountedWritable()) {
14433                unfreezePackage(packageName);
14434                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14435                        "Move location not mounted private volume");
14436            }
14437
14438            Preconditions.checkState(!currentAsec);
14439
14440            installFlags = INSTALL_INTERNAL;
14441            moveCompleteApp = true;
14442            measurePath = Environment.getDataAppDirectory(volumeUuid);
14443        }
14444
14445        final PackageStats stats = new PackageStats(null, -1);
14446        synchronized (mInstaller) {
14447            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
14448                unfreezePackage(packageName);
14449                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14450                        "Failed to measure package size");
14451            }
14452        }
14453
14454        Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " + stats.dataSize);
14455
14456        final long startFreeBytes = measurePath.getFreeSpace();
14457        final long sizeBytes;
14458        if (moveCompleteApp) {
14459            sizeBytes = stats.codeSize + stats.dataSize;
14460        } else {
14461            sizeBytes = stats.codeSize;
14462        }
14463
14464        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
14465            unfreezePackage(packageName);
14466            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14467                    "Not enough free space to move");
14468        }
14469
14470        mMoveCallbacks.notifyStatusChanged(moveId, 10);
14471
14472        final CountDownLatch installedLatch = new CountDownLatch(1);
14473        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14474            @Override
14475            public void onUserActionRequired(Intent intent) throws RemoteException {
14476                throw new IllegalStateException();
14477            }
14478
14479            @Override
14480            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14481                    Bundle extras) throws RemoteException {
14482                Slog.d(TAG, "Install result for move: "
14483                        + PackageManager.installStatusToString(returnCode, msg));
14484
14485                installedLatch.countDown();
14486
14487                // Regardless of success or failure of the move operation,
14488                // always unfreeze the package
14489                unfreezePackage(packageName);
14490
14491                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14492                switch (status) {
14493                    case PackageInstaller.STATUS_SUCCESS:
14494                        mMoveCallbacks.notifyStatusChanged(moveId,
14495                                PackageManager.MOVE_SUCCEEDED);
14496                        break;
14497                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14498                        mMoveCallbacks.notifyStatusChanged(moveId,
14499                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14500                        break;
14501                    default:
14502                        mMoveCallbacks.notifyStatusChanged(moveId,
14503                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14504                        break;
14505                }
14506            }
14507        };
14508
14509        final MoveInfo move;
14510        if (moveCompleteApp) {
14511            // Kick off a thread to report progress estimates
14512            new Thread() {
14513                @Override
14514                public void run() {
14515                    while (true) {
14516                        try {
14517                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
14518                                break;
14519                            }
14520                        } catch (InterruptedException ignored) {
14521                        }
14522
14523                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
14524                        final int progress = 10 + (int) MathUtils.constrain(
14525                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
14526                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
14527                    }
14528                }
14529            }.start();
14530
14531            final String dataAppName = codeFile.getName();
14532            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
14533                    dataAppName, appId, seinfo);
14534        } else {
14535            move = null;
14536        }
14537
14538        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14539
14540        final Message msg = mHandler.obtainMessage(INIT_COPY);
14541        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14542        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
14543                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14544        mHandler.sendMessage(msg);
14545    }
14546
14547    @Override
14548    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
14549        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14550
14551        final int realMoveId = mNextMoveId.getAndIncrement();
14552        final Bundle extras = new Bundle();
14553        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
14554        mMoveCallbacks.notifyCreated(realMoveId, extras);
14555
14556        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
14557            @Override
14558            public void onCreated(int moveId, Bundle extras) {
14559                // Ignored
14560            }
14561
14562            @Override
14563            public void onStatusChanged(int moveId, int status, long estMillis) {
14564                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
14565            }
14566        };
14567
14568        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14569        storage.setPrimaryStorageUuid(volumeUuid, callback);
14570        return realMoveId;
14571    }
14572
14573    @Override
14574    public int getMoveStatus(int moveId) {
14575        mContext.enforceCallingOrSelfPermission(
14576                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14577        return mMoveCallbacks.mLastStatus.get(moveId);
14578    }
14579
14580    @Override
14581    public void registerMoveCallback(IPackageMoveObserver callback) {
14582        mContext.enforceCallingOrSelfPermission(
14583                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14584        mMoveCallbacks.register(callback);
14585    }
14586
14587    @Override
14588    public void unregisterMoveCallback(IPackageMoveObserver callback) {
14589        mContext.enforceCallingOrSelfPermission(
14590                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14591        mMoveCallbacks.unregister(callback);
14592    }
14593
14594    @Override
14595    public boolean setInstallLocation(int loc) {
14596        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14597                null);
14598        if (getInstallLocation() == loc) {
14599            return true;
14600        }
14601        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14602                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14603            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14604                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14605            return true;
14606        }
14607        return false;
14608   }
14609
14610    @Override
14611    public int getInstallLocation() {
14612        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14613                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14614                PackageHelper.APP_INSTALL_AUTO);
14615    }
14616
14617    /** Called by UserManagerService */
14618    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14619        mDirtyUsers.remove(userHandle);
14620        mSettings.removeUserLPw(userHandle);
14621        mPendingBroadcasts.remove(userHandle);
14622        if (mInstaller != null) {
14623            // Technically, we shouldn't be doing this with the package lock
14624            // held.  However, this is very rare, and there is already so much
14625            // other disk I/O going on, that we'll let it slide for now.
14626            final StorageManager storage = StorageManager.from(mContext);
14627            final List<VolumeInfo> vols = storage.getVolumes();
14628            for (VolumeInfo vol : vols) {
14629                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
14630                    final String volumeUuid = vol.getFsUuid();
14631                    Slog.d(TAG, "Removing user data on volume " + volumeUuid);
14632                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
14633                }
14634            }
14635        }
14636        mUserNeedsBadging.delete(userHandle);
14637        removeUnusedPackagesLILPw(userManager, userHandle);
14638    }
14639
14640    /**
14641     * We're removing userHandle and would like to remove any downloaded packages
14642     * that are no longer in use by any other user.
14643     * @param userHandle the user being removed
14644     */
14645    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
14646        final boolean DEBUG_CLEAN_APKS = false;
14647        int [] users = userManager.getUserIdsLPr();
14648        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
14649        while (psit.hasNext()) {
14650            PackageSetting ps = psit.next();
14651            if (ps.pkg == null) {
14652                continue;
14653            }
14654            final String packageName = ps.pkg.packageName;
14655            // Skip over if system app
14656            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14657                continue;
14658            }
14659            if (DEBUG_CLEAN_APKS) {
14660                Slog.i(TAG, "Checking package " + packageName);
14661            }
14662            boolean keep = false;
14663            for (int i = 0; i < users.length; i++) {
14664                if (users[i] != userHandle && ps.getInstalled(users[i])) {
14665                    keep = true;
14666                    if (DEBUG_CLEAN_APKS) {
14667                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
14668                                + users[i]);
14669                    }
14670                    break;
14671                }
14672            }
14673            if (!keep) {
14674                if (DEBUG_CLEAN_APKS) {
14675                    Slog.i(TAG, "  Removing package " + packageName);
14676                }
14677                mHandler.post(new Runnable() {
14678                    public void run() {
14679                        deletePackageX(packageName, userHandle, 0);
14680                    } //end run
14681                });
14682            }
14683        }
14684    }
14685
14686    /** Called by UserManagerService */
14687    void createNewUserLILPw(int userHandle, File path) {
14688        if (mInstaller != null) {
14689            mInstaller.createUserConfig(userHandle);
14690            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
14691        }
14692    }
14693
14694    void newUserCreatedLILPw(int userHandle) {
14695        // Adding a user requires updating runtime permissions for system apps.
14696        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
14697    }
14698
14699    @Override
14700    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
14701        mContext.enforceCallingOrSelfPermission(
14702                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14703                "Only package verification agents can read the verifier device identity");
14704
14705        synchronized (mPackages) {
14706            return mSettings.getVerifierDeviceIdentityLPw();
14707        }
14708    }
14709
14710    @Override
14711    public void setPermissionEnforced(String permission, boolean enforced) {
14712        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
14713        if (READ_EXTERNAL_STORAGE.equals(permission)) {
14714            synchronized (mPackages) {
14715                if (mSettings.mReadExternalStorageEnforced == null
14716                        || mSettings.mReadExternalStorageEnforced != enforced) {
14717                    mSettings.mReadExternalStorageEnforced = enforced;
14718                    mSettings.writeLPr();
14719                }
14720            }
14721            // kill any non-foreground processes so we restart them and
14722            // grant/revoke the GID.
14723            final IActivityManager am = ActivityManagerNative.getDefault();
14724            if (am != null) {
14725                final long token = Binder.clearCallingIdentity();
14726                try {
14727                    am.killProcessesBelowForeground("setPermissionEnforcement");
14728                } catch (RemoteException e) {
14729                } finally {
14730                    Binder.restoreCallingIdentity(token);
14731                }
14732            }
14733        } else {
14734            throw new IllegalArgumentException("No selective enforcement for " + permission);
14735        }
14736    }
14737
14738    @Override
14739    @Deprecated
14740    public boolean isPermissionEnforced(String permission) {
14741        return true;
14742    }
14743
14744    @Override
14745    public boolean isStorageLow() {
14746        final long token = Binder.clearCallingIdentity();
14747        try {
14748            final DeviceStorageMonitorInternal
14749                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14750            if (dsm != null) {
14751                return dsm.isMemoryLow();
14752            } else {
14753                return false;
14754            }
14755        } finally {
14756            Binder.restoreCallingIdentity(token);
14757        }
14758    }
14759
14760    @Override
14761    public IPackageInstaller getPackageInstaller() {
14762        return mInstallerService;
14763    }
14764
14765    private boolean userNeedsBadging(int userId) {
14766        int index = mUserNeedsBadging.indexOfKey(userId);
14767        if (index < 0) {
14768            final UserInfo userInfo;
14769            final long token = Binder.clearCallingIdentity();
14770            try {
14771                userInfo = sUserManager.getUserInfo(userId);
14772            } finally {
14773                Binder.restoreCallingIdentity(token);
14774            }
14775            final boolean b;
14776            if (userInfo != null && userInfo.isManagedProfile()) {
14777                b = true;
14778            } else {
14779                b = false;
14780            }
14781            mUserNeedsBadging.put(userId, b);
14782            return b;
14783        }
14784        return mUserNeedsBadging.valueAt(index);
14785    }
14786
14787    @Override
14788    public KeySet getKeySetByAlias(String packageName, String alias) {
14789        if (packageName == null || alias == null) {
14790            return null;
14791        }
14792        synchronized(mPackages) {
14793            final PackageParser.Package pkg = mPackages.get(packageName);
14794            if (pkg == null) {
14795                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14796                throw new IllegalArgumentException("Unknown package: " + packageName);
14797            }
14798            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14799            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
14800        }
14801    }
14802
14803    @Override
14804    public KeySet getSigningKeySet(String packageName) {
14805        if (packageName == null) {
14806            return null;
14807        }
14808        synchronized(mPackages) {
14809            final PackageParser.Package pkg = mPackages.get(packageName);
14810            if (pkg == null) {
14811                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14812                throw new IllegalArgumentException("Unknown package: " + packageName);
14813            }
14814            if (pkg.applicationInfo.uid != Binder.getCallingUid()
14815                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
14816                throw new SecurityException("May not access signing KeySet of other apps.");
14817            }
14818            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14819            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
14820        }
14821    }
14822
14823    @Override
14824    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
14825        if (packageName == null || ks == null) {
14826            return false;
14827        }
14828        synchronized(mPackages) {
14829            final PackageParser.Package pkg = mPackages.get(packageName);
14830            if (pkg == null) {
14831                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14832                throw new IllegalArgumentException("Unknown package: " + packageName);
14833            }
14834            IBinder ksh = ks.getToken();
14835            if (ksh instanceof KeySetHandle) {
14836                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14837                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
14838            }
14839            return false;
14840        }
14841    }
14842
14843    @Override
14844    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
14845        if (packageName == null || ks == null) {
14846            return false;
14847        }
14848        synchronized(mPackages) {
14849            final PackageParser.Package pkg = mPackages.get(packageName);
14850            if (pkg == null) {
14851                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14852                throw new IllegalArgumentException("Unknown package: " + packageName);
14853            }
14854            IBinder ksh = ks.getToken();
14855            if (ksh instanceof KeySetHandle) {
14856                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14857                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
14858            }
14859            return false;
14860        }
14861    }
14862
14863    public void getUsageStatsIfNoPackageUsageInfo() {
14864        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
14865            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
14866            if (usm == null) {
14867                throw new IllegalStateException("UsageStatsManager must be initialized");
14868            }
14869            long now = System.currentTimeMillis();
14870            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
14871            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
14872                String packageName = entry.getKey();
14873                PackageParser.Package pkg = mPackages.get(packageName);
14874                if (pkg == null) {
14875                    continue;
14876                }
14877                UsageStats usage = entry.getValue();
14878                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
14879                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
14880            }
14881        }
14882    }
14883
14884    /**
14885     * Check and throw if the given before/after packages would be considered a
14886     * downgrade.
14887     */
14888    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
14889            throws PackageManagerException {
14890        if (after.versionCode < before.mVersionCode) {
14891            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14892                    "Update version code " + after.versionCode + " is older than current "
14893                    + before.mVersionCode);
14894        } else if (after.versionCode == before.mVersionCode) {
14895            if (after.baseRevisionCode < before.baseRevisionCode) {
14896                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14897                        "Update base revision code " + after.baseRevisionCode
14898                        + " is older than current " + before.baseRevisionCode);
14899            }
14900
14901            if (!ArrayUtils.isEmpty(after.splitNames)) {
14902                for (int i = 0; i < after.splitNames.length; i++) {
14903                    final String splitName = after.splitNames[i];
14904                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
14905                    if (j != -1) {
14906                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
14907                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14908                                    "Update split " + splitName + " revision code "
14909                                    + after.splitRevisionCodes[i] + " is older than current "
14910                                    + before.splitRevisionCodes[j]);
14911                        }
14912                    }
14913                }
14914            }
14915        }
14916    }
14917
14918    private static class MoveCallbacks extends Handler {
14919        private static final int MSG_CREATED = 1;
14920        private static final int MSG_STATUS_CHANGED = 2;
14921
14922        private final RemoteCallbackList<IPackageMoveObserver>
14923                mCallbacks = new RemoteCallbackList<>();
14924
14925        private final SparseIntArray mLastStatus = new SparseIntArray();
14926
14927        public MoveCallbacks(Looper looper) {
14928            super(looper);
14929        }
14930
14931        public void register(IPackageMoveObserver callback) {
14932            mCallbacks.register(callback);
14933        }
14934
14935        public void unregister(IPackageMoveObserver callback) {
14936            mCallbacks.unregister(callback);
14937        }
14938
14939        @Override
14940        public void handleMessage(Message msg) {
14941            final SomeArgs args = (SomeArgs) msg.obj;
14942            final int n = mCallbacks.beginBroadcast();
14943            for (int i = 0; i < n; i++) {
14944                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
14945                try {
14946                    invokeCallback(callback, msg.what, args);
14947                } catch (RemoteException ignored) {
14948                }
14949            }
14950            mCallbacks.finishBroadcast();
14951            args.recycle();
14952        }
14953
14954        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
14955                throws RemoteException {
14956            switch (what) {
14957                case MSG_CREATED: {
14958                    callback.onCreated(args.argi1, (Bundle) args.arg2);
14959                    break;
14960                }
14961                case MSG_STATUS_CHANGED: {
14962                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
14963                    break;
14964                }
14965            }
14966        }
14967
14968        private void notifyCreated(int moveId, Bundle extras) {
14969            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
14970
14971            final SomeArgs args = SomeArgs.obtain();
14972            args.argi1 = moveId;
14973            args.arg2 = extras;
14974            obtainMessage(MSG_CREATED, args).sendToTarget();
14975        }
14976
14977        private void notifyStatusChanged(int moveId, int status) {
14978            notifyStatusChanged(moveId, status, -1);
14979        }
14980
14981        private void notifyStatusChanged(int moveId, int status, long estMillis) {
14982            Slog.v(TAG, "Move " + moveId + " status " + status);
14983
14984            final SomeArgs args = SomeArgs.obtain();
14985            args.argi1 = moveId;
14986            args.argi2 = status;
14987            args.arg3 = estMillis;
14988            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
14989
14990            synchronized (mLastStatus) {
14991                mLastStatus.put(moveId, status);
14992            }
14993        }
14994    }
14995}
14996