PackageManagerService.java revision 50a05454795c93ac483f5cb6819e74cb17be1b5b
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.PrintStreamPrinter;
175import android.util.Slog;
176import android.util.SparseArray;
177import android.util.SparseBooleanArray;
178import android.util.SparseIntArray;
179import android.util.Xml;
180import android.view.Display;
181
182import dalvik.system.DexFile;
183import dalvik.system.VMRuntime;
184
185import libcore.io.IoUtils;
186import libcore.util.EmptyArray;
187
188import com.android.internal.R;
189import com.android.internal.app.IMediaContainerService;
190import com.android.internal.app.ResolverActivity;
191import com.android.internal.content.NativeLibraryHelper;
192import com.android.internal.content.PackageHelper;
193import com.android.internal.os.IParcelFileDescriptorFactory;
194import com.android.internal.os.SomeArgs;
195import com.android.internal.util.ArrayUtils;
196import com.android.internal.util.FastPrintWriter;
197import com.android.internal.util.FastXmlSerializer;
198import com.android.internal.util.IndentingPrintWriter;
199import com.android.internal.util.Preconditions;
200import com.android.server.EventLogTags;
201import com.android.server.FgThread;
202import com.android.server.IntentResolver;
203import com.android.server.LocalServices;
204import com.android.server.ServiceThread;
205import com.android.server.SystemConfig;
206import com.android.server.Watchdog;
207import com.android.server.pm.Settings.DatabaseVersion;
208import com.android.server.storage.DeviceStorageMonitorInternal;
209
210import org.xmlpull.v1.XmlPullParser;
211import org.xmlpull.v1.XmlSerializer;
212
213import java.io.BufferedInputStream;
214import java.io.BufferedOutputStream;
215import java.io.BufferedReader;
216import java.io.ByteArrayInputStream;
217import java.io.ByteArrayOutputStream;
218import java.io.File;
219import java.io.FileDescriptor;
220import java.io.FileNotFoundException;
221import java.io.FileOutputStream;
222import java.io.FileReader;
223import java.io.FilenameFilter;
224import java.io.IOException;
225import java.io.InputStream;
226import java.io.PrintWriter;
227import java.nio.charset.StandardCharsets;
228import java.security.NoSuchAlgorithmException;
229import java.security.PublicKey;
230import java.security.cert.CertificateEncodingException;
231import java.security.cert.CertificateException;
232import java.text.SimpleDateFormat;
233import java.util.ArrayList;
234import java.util.Arrays;
235import java.util.Collection;
236import java.util.Collections;
237import java.util.Comparator;
238import java.util.Date;
239import java.util.Iterator;
240import java.util.List;
241import java.util.Map;
242import java.util.Objects;
243import java.util.Set;
244import java.util.concurrent.atomic.AtomicBoolean;
245import java.util.concurrent.atomic.AtomicInteger;
246import java.util.concurrent.atomic.AtomicLong;
247
248/**
249 * Keep track of all those .apks everywhere.
250 *
251 * This is very central to the platform's security; please run the unit
252 * tests whenever making modifications here:
253 *
254mmm frameworks/base/tests/AndroidTests
255adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
256adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
257 *
258 * {@hide}
259 */
260public class PackageManagerService extends IPackageManager.Stub {
261    static final String TAG = "PackageManager";
262    static final boolean DEBUG_SETTINGS = false;
263    static final boolean DEBUG_PREFERRED = false;
264    static final boolean DEBUG_UPGRADE = false;
265    private static final boolean DEBUG_BACKUP = true;
266    private static final boolean DEBUG_INSTALL = false;
267    private static final boolean DEBUG_REMOVE = false;
268    private static final boolean DEBUG_BROADCASTS = false;
269    private static final boolean DEBUG_SHOW_INFO = false;
270    private static final boolean DEBUG_PACKAGE_INFO = false;
271    private static final boolean DEBUG_INTENT_MATCHING = false;
272    private static final boolean DEBUG_PACKAGE_SCANNING = false;
273    private static final boolean DEBUG_VERIFY = false;
274    private static final boolean DEBUG_DEXOPT = false;
275    private static final boolean DEBUG_ABI_SELECTION = false;
276
277    static final boolean RUNTIME_PERMISSIONS_ENABLED = true;
278
279    private static final int RADIO_UID = Process.PHONE_UID;
280    private static final int LOG_UID = Process.LOG_UID;
281    private static final int NFC_UID = Process.NFC_UID;
282    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
283    private static final int SHELL_UID = Process.SHELL_UID;
284
285    // Cap the size of permission trees that 3rd party apps can define
286    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
287
288    // Suffix used during package installation when copying/moving
289    // package apks to install directory.
290    private static final String INSTALL_PACKAGE_SUFFIX = "-";
291
292    static final int SCAN_NO_DEX = 1<<1;
293    static final int SCAN_FORCE_DEX = 1<<2;
294    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
295    static final int SCAN_NEW_INSTALL = 1<<4;
296    static final int SCAN_NO_PATHS = 1<<5;
297    static final int SCAN_UPDATE_TIME = 1<<6;
298    static final int SCAN_DEFER_DEX = 1<<7;
299    static final int SCAN_BOOTING = 1<<8;
300    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
301    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
302    static final int SCAN_REPLACING = 1<<11;
303    static final int SCAN_REQUIRE_KNOWN = 1<<12;
304
305    static final int REMOVE_CHATTY = 1<<16;
306
307    /**
308     * Timeout (in milliseconds) after which the watchdog should declare that
309     * our handler thread is wedged.  The usual default for such things is one
310     * minute but we sometimes do very lengthy I/O operations on this thread,
311     * such as installing multi-gigabyte applications, so ours needs to be longer.
312     */
313    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
314
315    /**
316     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
317     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
318     * settings entry if available, otherwise we use the hardcoded default.  If it's been
319     * more than this long since the last fstrim, we force one during the boot sequence.
320     *
321     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
322     * one gets run at the next available charging+idle time.  This final mandatory
323     * no-fstrim check kicks in only of the other scheduling criteria is never met.
324     */
325    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
326
327    /**
328     * Whether verification is enabled by default.
329     */
330    private static final boolean DEFAULT_VERIFY_ENABLE = true;
331
332    /**
333     * The default maximum time to wait for the verification agent to return in
334     * milliseconds.
335     */
336    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
337
338    /**
339     * The default response for package verification timeout.
340     *
341     * This can be either PackageManager.VERIFICATION_ALLOW or
342     * PackageManager.VERIFICATION_REJECT.
343     */
344    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
345
346    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
347
348    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
349            DEFAULT_CONTAINER_PACKAGE,
350            "com.android.defcontainer.DefaultContainerService");
351
352    private static final String KILL_APP_REASON_GIDS_CHANGED =
353            "permission grant or revoke changed gids";
354
355    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
356            "permissions revoked";
357
358    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
359
360    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
361
362    /** Permission grant: not grant the permission. */
363    private static final int GRANT_DENIED = 1;
364
365    /** Permission grant: grant the permission as an install permission. */
366    private static final int GRANT_INSTALL = 2;
367
368    /** Permission grant: grant the permission as a runtime one. */
369    private static final int GRANT_RUNTIME = 3;
370
371    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
372    private static final int GRANT_UPGRADE = 4;
373
374    final ServiceThread mHandlerThread;
375
376    final PackageHandler mHandler;
377
378    /**
379     * Messages for {@link #mHandler} that need to wait for system ready before
380     * being dispatched.
381     */
382    private ArrayList<Message> mPostSystemReadyMessages;
383
384    final int mSdkVersion = Build.VERSION.SDK_INT;
385
386    final Context mContext;
387    final boolean mFactoryTest;
388    final boolean mOnlyCore;
389    final boolean mLazyDexOpt;
390    final long mDexOptLRUThresholdInMills;
391    final DisplayMetrics mMetrics;
392    final int mDefParseFlags;
393    final String[] mSeparateProcesses;
394    final boolean mIsUpgrade;
395
396    // This is where all application persistent data goes.
397    final File mAppDataDir;
398
399    // This is where all application persistent data goes for secondary users.
400    final File mUserAppDataDir;
401
402    /** The location for ASEC container files on internal storage. */
403    final String mAsecInternalPath;
404
405    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
406    // LOCK HELD.  Can be called with mInstallLock held.
407    final Installer mInstaller;
408
409    /** Directory where installed third-party apps stored */
410    final File mAppInstallDir;
411
412    /**
413     * Directory to which applications installed internally have their
414     * 32 bit native libraries copied.
415     */
416    private File mAppLib32InstallDir;
417
418    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
419    // apps.
420    final File mDrmAppPrivateInstallDir;
421
422    // ----------------------------------------------------------------
423
424    // Lock for state used when installing and doing other long running
425    // operations.  Methods that must be called with this lock held have
426    // the suffix "LI".
427    final Object mInstallLock = new Object();
428
429    // ----------------------------------------------------------------
430
431    // Keys are String (package name), values are Package.  This also serves
432    // as the lock for the global state.  Methods that must be called with
433    // this lock held have the prefix "LP".
434    final ArrayMap<String, PackageParser.Package> mPackages =
435            new ArrayMap<String, PackageParser.Package>();
436
437    // Tracks available target package names -> overlay package paths.
438    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
439        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
440
441    final Settings mSettings;
442    boolean mRestoredSettings;
443
444    // System configuration read by SystemConfig.
445    final int[] mGlobalGids;
446    final SparseArray<ArraySet<String>> mSystemPermissions;
447    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
448
449    // If mac_permissions.xml was found for seinfo labeling.
450    boolean mFoundPolicyFile;
451
452    // If a recursive restorecon of /data/data/<pkg> is needed.
453    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
454
455    public static final class SharedLibraryEntry {
456        public final String path;
457        public final String apk;
458
459        SharedLibraryEntry(String _path, String _apk) {
460            path = _path;
461            apk = _apk;
462        }
463    }
464
465    // Currently known shared libraries.
466    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
467            new ArrayMap<String, SharedLibraryEntry>();
468
469    // All available activities, for your resolving pleasure.
470    final ActivityIntentResolver mActivities =
471            new ActivityIntentResolver();
472
473    // All available receivers, for your resolving pleasure.
474    final ActivityIntentResolver mReceivers =
475            new ActivityIntentResolver();
476
477    // All available services, for your resolving pleasure.
478    final ServiceIntentResolver mServices = new ServiceIntentResolver();
479
480    // All available providers, for your resolving pleasure.
481    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
482
483    // Mapping from provider base names (first directory in content URI codePath)
484    // to the provider information.
485    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
486            new ArrayMap<String, PackageParser.Provider>();
487
488    // Mapping from instrumentation class names to info about them.
489    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
490            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
491
492    // Mapping from permission names to info about them.
493    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
494            new ArrayMap<String, PackageParser.PermissionGroup>();
495
496    // Packages whose data we have transfered into another package, thus
497    // should no longer exist.
498    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
499
500    // Broadcast actions that are only available to the system.
501    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
502
503    /** List of packages waiting for verification. */
504    final SparseArray<PackageVerificationState> mPendingVerification
505            = new SparseArray<PackageVerificationState>();
506
507    /** Set of packages associated with each app op permission. */
508    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
509
510    final PackageInstallerService mInstallerService;
511
512    private final PackageDexOptimizer mPackageDexOptimizer;
513
514    private AtomicInteger mNextMoveId = new AtomicInteger();
515    private final MoveCallbacks mMoveCallbacks;
516
517    // Cache of users who need badging.
518    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
519
520    /** Token for keys in mPendingVerification. */
521    private int mPendingVerificationToken = 0;
522
523    volatile boolean mSystemReady;
524    volatile boolean mSafeMode;
525    volatile boolean mHasSystemUidErrors;
526
527    ApplicationInfo mAndroidApplication;
528    final ActivityInfo mResolveActivity = new ActivityInfo();
529    final ResolveInfo mResolveInfo = new ResolveInfo();
530    ComponentName mResolveComponentName;
531    PackageParser.Package mPlatformPackage;
532    ComponentName mCustomResolverComponentName;
533
534    boolean mResolverReplaced = false;
535
536    private final ComponentName mIntentFilterVerifierComponent;
537    private int mIntentFilterVerificationToken = 0;
538
539    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
540            = new SparseArray<IntentFilterVerificationState>();
541
542    private interface IntentFilterVerifier<T extends IntentFilter> {
543        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
544                                               T filter, String packageName);
545        void startVerifications(int userId);
546        void receiveVerificationResponse(int verificationId);
547    }
548
549    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
550        private Context mContext;
551        private ComponentName mIntentFilterVerifierComponent;
552        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
553
554        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
555            mContext = context;
556            mIntentFilterVerifierComponent = verifierComponent;
557        }
558
559        private String getDefaultScheme() {
560            // TODO: replace SCHEME_HTTP with SCHEME_HTTPS
561            return IntentFilter.SCHEME_HTTP;
562        }
563
564        @Override
565        public void startVerifications(int userId) {
566            // Launch verifications requests
567            int count = mCurrentIntentFilterVerifications.size();
568            for (int n=0; n<count; n++) {
569                int verificationId = mCurrentIntentFilterVerifications.get(n);
570                final IntentFilterVerificationState ivs =
571                        mIntentFilterVerificationStates.get(verificationId);
572
573                String packageName = ivs.getPackageName();
574
575                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
576                final int filterCount = filters.size();
577                ArraySet<String> domainsSet = new ArraySet<>();
578                for (int m=0; m<filterCount; m++) {
579                    PackageParser.ActivityIntentInfo filter = filters.get(m);
580                    domainsSet.addAll(filter.getHostsList());
581                }
582                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
583                synchronized (mPackages) {
584                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
585                            packageName, domainsList) != null) {
586                        scheduleWriteSettingsLocked();
587                    }
588                }
589                sendVerificationRequest(userId, verificationId, ivs);
590            }
591            mCurrentIntentFilterVerifications.clear();
592        }
593
594        private void sendVerificationRequest(int userId, int verificationId,
595                IntentFilterVerificationState ivs) {
596
597            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
598            verificationIntent.putExtra(
599                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
600                    verificationId);
601            verificationIntent.putExtra(
602                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
603                    getDefaultScheme());
604            verificationIntent.putExtra(
605                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
606                    ivs.getHostsString());
607            verificationIntent.putExtra(
608                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
609                    ivs.getPackageName());
610            verificationIntent.setComponent(mIntentFilterVerifierComponent);
611            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
612
613            UserHandle user = new UserHandle(userId);
614            mContext.sendBroadcastAsUser(verificationIntent, user);
615            Slog.d(TAG, "Sending IntenFilter verification broadcast");
616        }
617
618        public void receiveVerificationResponse(int verificationId) {
619            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
620
621            final boolean verified = ivs.isVerified();
622
623            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
624            final int count = filters.size();
625            for (int n=0; n<count; n++) {
626                PackageParser.ActivityIntentInfo filter = filters.get(n);
627                filter.setVerified(verified);
628
629                Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:"
630                        + verified + " and hosts:" + ivs.getHostsString());
631            }
632
633            mIntentFilterVerificationStates.remove(verificationId);
634
635            final String packageName = ivs.getPackageName();
636            IntentFilterVerificationInfo ivi = null;
637
638            synchronized (mPackages) {
639                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
640            }
641            if (ivi == null) {
642                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
643                        + verificationId + " packageName:" + packageName);
644                return;
645            }
646            Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:"
647                    + verificationId);
648
649            synchronized (mPackages) {
650                if (verified) {
651                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
652                } else {
653                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
654                }
655                scheduleWriteSettingsLocked();
656
657                final int userId = ivs.getUserId();
658                if (userId != UserHandle.USER_ALL) {
659                    final int userStatus =
660                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
661
662                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
663                    boolean needUpdate = false;
664
665                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
666                    // already been set by the User thru the Disambiguation dialog
667                    switch (userStatus) {
668                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
669                            if (verified) {
670                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
671                            } else {
672                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
673                            }
674                            needUpdate = true;
675                            break;
676
677                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
678                            if (verified) {
679                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
680                                needUpdate = true;
681                            }
682                            break;
683
684                        default:
685                            // Nothing to do
686                    }
687
688                    if (needUpdate) {
689                        mSettings.updateIntentFilterVerificationStatusLPw(
690                                packageName, updatedStatus, userId);
691                        scheduleWritePackageRestrictionsLocked(userId);
692                    }
693                }
694            }
695        }
696
697        @Override
698        public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
699                    ActivityIntentInfo filter, String packageName) {
700            if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
701                    filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
702                Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme");
703                return false;
704            }
705            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
706            if (ivs == null) {
707                ivs = createDomainVerificationState(verifierId, userId, verificationId,
708                        packageName);
709            }
710            if (!hasValidDomains(filter)) {
711                return false;
712            }
713            ivs.addFilter(filter);
714            return true;
715        }
716
717        private IntentFilterVerificationState createDomainVerificationState(int verifierId,
718                int userId, int verificationId, String packageName) {
719            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
720                    verifierId, userId, packageName);
721            ivs.setPendingState();
722            synchronized (mPackages) {
723                mIntentFilterVerificationStates.append(verificationId, ivs);
724                mCurrentIntentFilterVerifications.add(verificationId);
725            }
726            return ivs;
727        }
728    }
729
730    private static boolean hasValidDomains(ActivityIntentInfo filter) {
731        return hasValidDomains(filter, true);
732    }
733
734    private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) {
735        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
736                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
737        if (!hasHTTPorHTTPS) {
738            if (logging) {
739                Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme");
740            }
741            return false;
742        }
743        return true;
744    }
745
746    private IntentFilterVerifier mIntentFilterVerifier;
747
748    // Set of pending broadcasts for aggregating enable/disable of components.
749    static class PendingPackageBroadcasts {
750        // for each user id, a map of <package name -> components within that package>
751        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
752
753        public PendingPackageBroadcasts() {
754            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
755        }
756
757        public ArrayList<String> get(int userId, String packageName) {
758            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
759            return packages.get(packageName);
760        }
761
762        public void put(int userId, String packageName, ArrayList<String> components) {
763            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
764            packages.put(packageName, components);
765        }
766
767        public void remove(int userId, String packageName) {
768            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
769            if (packages != null) {
770                packages.remove(packageName);
771            }
772        }
773
774        public void remove(int userId) {
775            mUidMap.remove(userId);
776        }
777
778        public int userIdCount() {
779            return mUidMap.size();
780        }
781
782        public int userIdAt(int n) {
783            return mUidMap.keyAt(n);
784        }
785
786        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
787            return mUidMap.get(userId);
788        }
789
790        public int size() {
791            // total number of pending broadcast entries across all userIds
792            int num = 0;
793            for (int i = 0; i< mUidMap.size(); i++) {
794                num += mUidMap.valueAt(i).size();
795            }
796            return num;
797        }
798
799        public void clear() {
800            mUidMap.clear();
801        }
802
803        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
804            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
805            if (map == null) {
806                map = new ArrayMap<String, ArrayList<String>>();
807                mUidMap.put(userId, map);
808            }
809            return map;
810        }
811    }
812    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
813
814    // Service Connection to remote media container service to copy
815    // package uri's from external media onto secure containers
816    // or internal storage.
817    private IMediaContainerService mContainerService = null;
818
819    static final int SEND_PENDING_BROADCAST = 1;
820    static final int MCS_BOUND = 3;
821    static final int END_COPY = 4;
822    static final int INIT_COPY = 5;
823    static final int MCS_UNBIND = 6;
824    static final int START_CLEANING_PACKAGE = 7;
825    static final int FIND_INSTALL_LOC = 8;
826    static final int POST_INSTALL = 9;
827    static final int MCS_RECONNECT = 10;
828    static final int MCS_GIVE_UP = 11;
829    static final int UPDATED_MEDIA_STATUS = 12;
830    static final int WRITE_SETTINGS = 13;
831    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
832    static final int PACKAGE_VERIFIED = 15;
833    static final int CHECK_PENDING_VERIFICATION = 16;
834    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
835    static final int INTENT_FILTER_VERIFIED = 18;
836
837    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
838
839    // Delay time in millisecs
840    static final int BROADCAST_DELAY = 10 * 1000;
841
842    static UserManagerService sUserManager;
843
844    // Stores a list of users whose package restrictions file needs to be updated
845    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
846
847    final private DefaultContainerConnection mDefContainerConn =
848            new DefaultContainerConnection();
849    class DefaultContainerConnection implements ServiceConnection {
850        public void onServiceConnected(ComponentName name, IBinder service) {
851            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
852            IMediaContainerService imcs =
853                IMediaContainerService.Stub.asInterface(service);
854            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
855        }
856
857        public void onServiceDisconnected(ComponentName name) {
858            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
859        }
860    };
861
862    // Recordkeeping of restore-after-install operations that are currently in flight
863    // between the Package Manager and the Backup Manager
864    class PostInstallData {
865        public InstallArgs args;
866        public PackageInstalledInfo res;
867
868        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
869            args = _a;
870            res = _r;
871        }
872    };
873    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
874    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
875
876    // backup/restore of preferred activity state
877    private static final String TAG_PREFERRED_BACKUP = "pa";
878
879    private final String mRequiredVerifierPackage;
880
881    private final PackageUsage mPackageUsage = new PackageUsage();
882
883    private class PackageUsage {
884        private static final int WRITE_INTERVAL
885            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
886
887        private final Object mFileLock = new Object();
888        private final AtomicLong mLastWritten = new AtomicLong(0);
889        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
890
891        private boolean mIsHistoricalPackageUsageAvailable = true;
892
893        boolean isHistoricalPackageUsageAvailable() {
894            return mIsHistoricalPackageUsageAvailable;
895        }
896
897        void write(boolean force) {
898            if (force) {
899                writeInternal();
900                return;
901            }
902            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
903                && !DEBUG_DEXOPT) {
904                return;
905            }
906            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
907                new Thread("PackageUsage_DiskWriter") {
908                    @Override
909                    public void run() {
910                        try {
911                            writeInternal();
912                        } finally {
913                            mBackgroundWriteRunning.set(false);
914                        }
915                    }
916                }.start();
917            }
918        }
919
920        private void writeInternal() {
921            synchronized (mPackages) {
922                synchronized (mFileLock) {
923                    AtomicFile file = getFile();
924                    FileOutputStream f = null;
925                    try {
926                        f = file.startWrite();
927                        BufferedOutputStream out = new BufferedOutputStream(f);
928                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
929                        StringBuilder sb = new StringBuilder();
930                        for (PackageParser.Package pkg : mPackages.values()) {
931                            if (pkg.mLastPackageUsageTimeInMills == 0) {
932                                continue;
933                            }
934                            sb.setLength(0);
935                            sb.append(pkg.packageName);
936                            sb.append(' ');
937                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
938                            sb.append('\n');
939                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
940                        }
941                        out.flush();
942                        file.finishWrite(f);
943                    } catch (IOException e) {
944                        if (f != null) {
945                            file.failWrite(f);
946                        }
947                        Log.e(TAG, "Failed to write package usage times", e);
948                    }
949                }
950            }
951            mLastWritten.set(SystemClock.elapsedRealtime());
952        }
953
954        void readLP() {
955            synchronized (mFileLock) {
956                AtomicFile file = getFile();
957                BufferedInputStream in = null;
958                try {
959                    in = new BufferedInputStream(file.openRead());
960                    StringBuffer sb = new StringBuffer();
961                    while (true) {
962                        String packageName = readToken(in, sb, ' ');
963                        if (packageName == null) {
964                            break;
965                        }
966                        String timeInMillisString = readToken(in, sb, '\n');
967                        if (timeInMillisString == null) {
968                            throw new IOException("Failed to find last usage time for package "
969                                                  + packageName);
970                        }
971                        PackageParser.Package pkg = mPackages.get(packageName);
972                        if (pkg == null) {
973                            continue;
974                        }
975                        long timeInMillis;
976                        try {
977                            timeInMillis = Long.parseLong(timeInMillisString.toString());
978                        } catch (NumberFormatException e) {
979                            throw new IOException("Failed to parse " + timeInMillisString
980                                                  + " as a long.", e);
981                        }
982                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
983                    }
984                } catch (FileNotFoundException expected) {
985                    mIsHistoricalPackageUsageAvailable = false;
986                } catch (IOException e) {
987                    Log.w(TAG, "Failed to read package usage times", e);
988                } finally {
989                    IoUtils.closeQuietly(in);
990                }
991            }
992            mLastWritten.set(SystemClock.elapsedRealtime());
993        }
994
995        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
996                throws IOException {
997            sb.setLength(0);
998            while (true) {
999                int ch = in.read();
1000                if (ch == -1) {
1001                    if (sb.length() == 0) {
1002                        return null;
1003                    }
1004                    throw new IOException("Unexpected EOF");
1005                }
1006                if (ch == endOfToken) {
1007                    return sb.toString();
1008                }
1009                sb.append((char)ch);
1010            }
1011        }
1012
1013        private AtomicFile getFile() {
1014            File dataDir = Environment.getDataDirectory();
1015            File systemDir = new File(dataDir, "system");
1016            File fname = new File(systemDir, "package-usage.list");
1017            return new AtomicFile(fname);
1018        }
1019    }
1020
1021    class PackageHandler extends Handler {
1022        private boolean mBound = false;
1023        final ArrayList<HandlerParams> mPendingInstalls =
1024            new ArrayList<HandlerParams>();
1025
1026        private boolean connectToService() {
1027            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1028                    " DefaultContainerService");
1029            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1030            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1031            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1032                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1033                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1034                mBound = true;
1035                return true;
1036            }
1037            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1038            return false;
1039        }
1040
1041        private void disconnectService() {
1042            mContainerService = null;
1043            mBound = false;
1044            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1045            mContext.unbindService(mDefContainerConn);
1046            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1047        }
1048
1049        PackageHandler(Looper looper) {
1050            super(looper);
1051        }
1052
1053        public void handleMessage(Message msg) {
1054            try {
1055                doHandleMessage(msg);
1056            } finally {
1057                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1058            }
1059        }
1060
1061        void doHandleMessage(Message msg) {
1062            switch (msg.what) {
1063                case INIT_COPY: {
1064                    HandlerParams params = (HandlerParams) msg.obj;
1065                    int idx = mPendingInstalls.size();
1066                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1067                    // If a bind was already initiated we dont really
1068                    // need to do anything. The pending install
1069                    // will be processed later on.
1070                    if (!mBound) {
1071                        // If this is the only one pending we might
1072                        // have to bind to the service again.
1073                        if (!connectToService()) {
1074                            Slog.e(TAG, "Failed to bind to media container service");
1075                            params.serviceError();
1076                            return;
1077                        } else {
1078                            // Once we bind to the service, the first
1079                            // pending request will be processed.
1080                            mPendingInstalls.add(idx, params);
1081                        }
1082                    } else {
1083                        mPendingInstalls.add(idx, params);
1084                        // Already bound to the service. Just make
1085                        // sure we trigger off processing the first request.
1086                        if (idx == 0) {
1087                            mHandler.sendEmptyMessage(MCS_BOUND);
1088                        }
1089                    }
1090                    break;
1091                }
1092                case MCS_BOUND: {
1093                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1094                    if (msg.obj != null) {
1095                        mContainerService = (IMediaContainerService) msg.obj;
1096                    }
1097                    if (mContainerService == null) {
1098                        // Something seriously wrong. Bail out
1099                        Slog.e(TAG, "Cannot bind to media container service");
1100                        for (HandlerParams params : mPendingInstalls) {
1101                            // Indicate service bind error
1102                            params.serviceError();
1103                        }
1104                        mPendingInstalls.clear();
1105                    } else if (mPendingInstalls.size() > 0) {
1106                        HandlerParams params = mPendingInstalls.get(0);
1107                        if (params != null) {
1108                            if (params.startCopy()) {
1109                                // We are done...  look for more work or to
1110                                // go idle.
1111                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1112                                        "Checking for more work or unbind...");
1113                                // Delete pending install
1114                                if (mPendingInstalls.size() > 0) {
1115                                    mPendingInstalls.remove(0);
1116                                }
1117                                if (mPendingInstalls.size() == 0) {
1118                                    if (mBound) {
1119                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1120                                                "Posting delayed MCS_UNBIND");
1121                                        removeMessages(MCS_UNBIND);
1122                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1123                                        // Unbind after a little delay, to avoid
1124                                        // continual thrashing.
1125                                        sendMessageDelayed(ubmsg, 10000);
1126                                    }
1127                                } else {
1128                                    // There are more pending requests in queue.
1129                                    // Just post MCS_BOUND message to trigger processing
1130                                    // of next pending install.
1131                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1132                                            "Posting MCS_BOUND for next work");
1133                                    mHandler.sendEmptyMessage(MCS_BOUND);
1134                                }
1135                            }
1136                        }
1137                    } else {
1138                        // Should never happen ideally.
1139                        Slog.w(TAG, "Empty queue");
1140                    }
1141                    break;
1142                }
1143                case MCS_RECONNECT: {
1144                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1145                    if (mPendingInstalls.size() > 0) {
1146                        if (mBound) {
1147                            disconnectService();
1148                        }
1149                        if (!connectToService()) {
1150                            Slog.e(TAG, "Failed to bind to media container service");
1151                            for (HandlerParams params : mPendingInstalls) {
1152                                // Indicate service bind error
1153                                params.serviceError();
1154                            }
1155                            mPendingInstalls.clear();
1156                        }
1157                    }
1158                    break;
1159                }
1160                case MCS_UNBIND: {
1161                    // If there is no actual work left, then time to unbind.
1162                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1163
1164                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1165                        if (mBound) {
1166                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1167
1168                            disconnectService();
1169                        }
1170                    } else if (mPendingInstalls.size() > 0) {
1171                        // There are more pending requests in queue.
1172                        // Just post MCS_BOUND message to trigger processing
1173                        // of next pending install.
1174                        mHandler.sendEmptyMessage(MCS_BOUND);
1175                    }
1176
1177                    break;
1178                }
1179                case MCS_GIVE_UP: {
1180                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1181                    mPendingInstalls.remove(0);
1182                    break;
1183                }
1184                case SEND_PENDING_BROADCAST: {
1185                    String packages[];
1186                    ArrayList<String> components[];
1187                    int size = 0;
1188                    int uids[];
1189                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1190                    synchronized (mPackages) {
1191                        if (mPendingBroadcasts == null) {
1192                            return;
1193                        }
1194                        size = mPendingBroadcasts.size();
1195                        if (size <= 0) {
1196                            // Nothing to be done. Just return
1197                            return;
1198                        }
1199                        packages = new String[size];
1200                        components = new ArrayList[size];
1201                        uids = new int[size];
1202                        int i = 0;  // filling out the above arrays
1203
1204                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1205                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1206                            Iterator<Map.Entry<String, ArrayList<String>>> it
1207                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1208                                            .entrySet().iterator();
1209                            while (it.hasNext() && i < size) {
1210                                Map.Entry<String, ArrayList<String>> ent = it.next();
1211                                packages[i] = ent.getKey();
1212                                components[i] = ent.getValue();
1213                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1214                                uids[i] = (ps != null)
1215                                        ? UserHandle.getUid(packageUserId, ps.appId)
1216                                        : -1;
1217                                i++;
1218                            }
1219                        }
1220                        size = i;
1221                        mPendingBroadcasts.clear();
1222                    }
1223                    // Send broadcasts
1224                    for (int i = 0; i < size; i++) {
1225                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1226                    }
1227                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1228                    break;
1229                }
1230                case START_CLEANING_PACKAGE: {
1231                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1232                    final String packageName = (String)msg.obj;
1233                    final int userId = msg.arg1;
1234                    final boolean andCode = msg.arg2 != 0;
1235                    synchronized (mPackages) {
1236                        if (userId == UserHandle.USER_ALL) {
1237                            int[] users = sUserManager.getUserIds();
1238                            for (int user : users) {
1239                                mSettings.addPackageToCleanLPw(
1240                                        new PackageCleanItem(user, packageName, andCode));
1241                            }
1242                        } else {
1243                            mSettings.addPackageToCleanLPw(
1244                                    new PackageCleanItem(userId, packageName, andCode));
1245                        }
1246                    }
1247                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1248                    startCleaningPackages();
1249                } break;
1250                case POST_INSTALL: {
1251                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1252                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1253                    mRunningInstalls.delete(msg.arg1);
1254                    boolean deleteOld = false;
1255
1256                    if (data != null) {
1257                        InstallArgs args = data.args;
1258                        PackageInstalledInfo res = data.res;
1259
1260                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1261                            res.removedInfo.sendBroadcast(false, true, false);
1262                            Bundle extras = new Bundle(1);
1263                            extras.putInt(Intent.EXTRA_UID, res.uid);
1264
1265                            // Now that we successfully installed the package, grant runtime
1266                            // permissions if requested before broadcasting the install.
1267                            if ((args.installFlags
1268                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1269                                grantRequestedRuntimePermissions(res.pkg,
1270                                        args.user.getIdentifier());
1271                            }
1272
1273                            // Determine the set of users who are adding this
1274                            // package for the first time vs. those who are seeing
1275                            // an update.
1276                            int[] firstUsers;
1277                            int[] updateUsers = new int[0];
1278                            if (res.origUsers == null || res.origUsers.length == 0) {
1279                                firstUsers = res.newUsers;
1280                            } else {
1281                                firstUsers = new int[0];
1282                                for (int i=0; i<res.newUsers.length; i++) {
1283                                    int user = res.newUsers[i];
1284                                    boolean isNew = true;
1285                                    for (int j=0; j<res.origUsers.length; j++) {
1286                                        if (res.origUsers[j] == user) {
1287                                            isNew = false;
1288                                            break;
1289                                        }
1290                                    }
1291                                    if (isNew) {
1292                                        int[] newFirst = new int[firstUsers.length+1];
1293                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1294                                                firstUsers.length);
1295                                        newFirst[firstUsers.length] = user;
1296                                        firstUsers = newFirst;
1297                                    } else {
1298                                        int[] newUpdate = new int[updateUsers.length+1];
1299                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1300                                                updateUsers.length);
1301                                        newUpdate[updateUsers.length] = user;
1302                                        updateUsers = newUpdate;
1303                                    }
1304                                }
1305                            }
1306                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1307                                    res.pkg.applicationInfo.packageName,
1308                                    extras, null, null, firstUsers);
1309                            final boolean update = res.removedInfo.removedPackage != null;
1310                            if (update) {
1311                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1312                            }
1313                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1314                                    res.pkg.applicationInfo.packageName,
1315                                    extras, null, null, updateUsers);
1316                            if (update) {
1317                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1318                                        res.pkg.applicationInfo.packageName,
1319                                        extras, null, null, updateUsers);
1320                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1321                                        null, null,
1322                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1323
1324                                // treat asec-hosted packages like removable media on upgrade
1325                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1326                                    if (DEBUG_INSTALL) {
1327                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1328                                                + " is ASEC-hosted -> AVAILABLE");
1329                                    }
1330                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1331                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1332                                    pkgList.add(res.pkg.applicationInfo.packageName);
1333                                    sendResourcesChangedBroadcast(true, true,
1334                                            pkgList,uidArray, null);
1335                                }
1336                            }
1337                            if (res.removedInfo.args != null) {
1338                                // Remove the replaced package's older resources safely now
1339                                deleteOld = true;
1340                            }
1341
1342                            // Log current value of "unknown sources" setting
1343                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1344                                getUnknownSourcesSettings());
1345                        }
1346                        // Force a gc to clear up things
1347                        Runtime.getRuntime().gc();
1348                        // We delete after a gc for applications  on sdcard.
1349                        if (deleteOld) {
1350                            synchronized (mInstallLock) {
1351                                res.removedInfo.args.doPostDeleteLI(true);
1352                            }
1353                        }
1354                        if (args.observer != null) {
1355                            try {
1356                                Bundle extras = extrasForInstallResult(res);
1357                                args.observer.onPackageInstalled(res.name, res.returnCode,
1358                                        res.returnMsg, extras);
1359                            } catch (RemoteException e) {
1360                                Slog.i(TAG, "Observer no longer exists.");
1361                            }
1362                        }
1363                    } else {
1364                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1365                    }
1366                } break;
1367                case UPDATED_MEDIA_STATUS: {
1368                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1369                    boolean reportStatus = msg.arg1 == 1;
1370                    boolean doGc = msg.arg2 == 1;
1371                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1372                    if (doGc) {
1373                        // Force a gc to clear up stale containers.
1374                        Runtime.getRuntime().gc();
1375                    }
1376                    if (msg.obj != null) {
1377                        @SuppressWarnings("unchecked")
1378                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1379                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1380                        // Unload containers
1381                        unloadAllContainers(args);
1382                    }
1383                    if (reportStatus) {
1384                        try {
1385                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1386                            PackageHelper.getMountService().finishMediaUpdate();
1387                        } catch (RemoteException e) {
1388                            Log.e(TAG, "MountService not running?");
1389                        }
1390                    }
1391                } break;
1392                case WRITE_SETTINGS: {
1393                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1394                    synchronized (mPackages) {
1395                        removeMessages(WRITE_SETTINGS);
1396                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1397                        mSettings.writeLPr();
1398                        mDirtyUsers.clear();
1399                    }
1400                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1401                } break;
1402                case WRITE_PACKAGE_RESTRICTIONS: {
1403                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1404                    synchronized (mPackages) {
1405                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1406                        for (int userId : mDirtyUsers) {
1407                            mSettings.writePackageRestrictionsLPr(userId);
1408                        }
1409                        mDirtyUsers.clear();
1410                    }
1411                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1412                } break;
1413                case CHECK_PENDING_VERIFICATION: {
1414                    final int verificationId = msg.arg1;
1415                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1416
1417                    if ((state != null) && !state.timeoutExtended()) {
1418                        final InstallArgs args = state.getInstallArgs();
1419                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1420
1421                        Slog.i(TAG, "Verification timed out for " + originUri);
1422                        mPendingVerification.remove(verificationId);
1423
1424                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1425
1426                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1427                            Slog.i(TAG, "Continuing with installation of " + originUri);
1428                            state.setVerifierResponse(Binder.getCallingUid(),
1429                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1430                            broadcastPackageVerified(verificationId, originUri,
1431                                    PackageManager.VERIFICATION_ALLOW,
1432                                    state.getInstallArgs().getUser());
1433                            try {
1434                                ret = args.copyApk(mContainerService, true);
1435                            } catch (RemoteException e) {
1436                                Slog.e(TAG, "Could not contact the ContainerService");
1437                            }
1438                        } else {
1439                            broadcastPackageVerified(verificationId, originUri,
1440                                    PackageManager.VERIFICATION_REJECT,
1441                                    state.getInstallArgs().getUser());
1442                        }
1443
1444                        processPendingInstall(args, ret);
1445                        mHandler.sendEmptyMessage(MCS_UNBIND);
1446                    }
1447                    break;
1448                }
1449                case PACKAGE_VERIFIED: {
1450                    final int verificationId = msg.arg1;
1451
1452                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1453                    if (state == null) {
1454                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1455                        break;
1456                    }
1457
1458                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1459
1460                    state.setVerifierResponse(response.callerUid, response.code);
1461
1462                    if (state.isVerificationComplete()) {
1463                        mPendingVerification.remove(verificationId);
1464
1465                        final InstallArgs args = state.getInstallArgs();
1466                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1467
1468                        int ret;
1469                        if (state.isInstallAllowed()) {
1470                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1471                            broadcastPackageVerified(verificationId, originUri,
1472                                    response.code, state.getInstallArgs().getUser());
1473                            try {
1474                                ret = args.copyApk(mContainerService, true);
1475                            } catch (RemoteException e) {
1476                                Slog.e(TAG, "Could not contact the ContainerService");
1477                            }
1478                        } else {
1479                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1480                        }
1481
1482                        processPendingInstall(args, ret);
1483
1484                        mHandler.sendEmptyMessage(MCS_UNBIND);
1485                    }
1486
1487                    break;
1488                }
1489                case START_INTENT_FILTER_VERIFICATIONS: {
1490                    int userId = msg.arg1;
1491                    int verifierUid = msg.arg2;
1492                    PackageParser.Package pkg = (PackageParser.Package)msg.obj;
1493
1494                    verifyIntentFiltersIfNeeded(userId, verifierUid, pkg);
1495                    break;
1496                }
1497                case INTENT_FILTER_VERIFIED: {
1498                    final int verificationId = msg.arg1;
1499
1500                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1501                            verificationId);
1502                    if (state == null) {
1503                        Slog.w(TAG, "Invalid IntentFilter verification token "
1504                                + verificationId + " received");
1505                        break;
1506                    }
1507
1508                    final int userId = state.getUserId();
1509
1510                    Slog.d(TAG, "Processing IntentFilter verification with token:"
1511                            + verificationId + " and userId:" + userId);
1512
1513                    final IntentFilterVerificationResponse response =
1514                            (IntentFilterVerificationResponse) msg.obj;
1515
1516                    state.setVerifierResponse(response.callerUid, response.code);
1517
1518                    Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1519                            + " and userId:" + userId
1520                            + " is settings verifier response with response code:"
1521                            + response.code);
1522
1523                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1524                        Slog.d(TAG, "Domains failing verification: "
1525                                + response.getFailedDomainsString());
1526                    }
1527
1528                    if (state.isVerificationComplete()) {
1529                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1530                    } else {
1531                        Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1532                                + " was not said to be complete");
1533                    }
1534
1535                    break;
1536                }
1537            }
1538        }
1539    }
1540
1541    private StorageEventListener mStorageListener = new StorageEventListener() {
1542        @Override
1543        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1544            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1545                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1546                    // TODO: ensure that private directories exist for all active users
1547                    // TODO: remove user data whose serial number doesn't match
1548                    loadPrivatePackages(vol);
1549                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1550                    unloadPrivatePackages(vol);
1551                }
1552            }
1553
1554            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1555                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1556                    updateExternalMediaStatus(true, false);
1557                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1558                    updateExternalMediaStatus(false, false);
1559                }
1560            }
1561        }
1562
1563        @Override
1564        public void onVolumeForgotten(String fsUuid) {
1565            // TODO: remove all packages hosted on this uuid
1566        }
1567    };
1568
1569    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1570        if (userId >= UserHandle.USER_OWNER) {
1571            grantRequestedRuntimePermissionsForUser(pkg, userId);
1572        } else if (userId == UserHandle.USER_ALL) {
1573            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1574                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1575            }
1576        }
1577    }
1578
1579    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1580        SettingBase sb = (SettingBase) pkg.mExtras;
1581        if (sb == null) {
1582            return;
1583        }
1584
1585        PermissionsState permissionsState = sb.getPermissionsState();
1586
1587        for (String permission : pkg.requestedPermissions) {
1588            BasePermission bp = mSettings.mPermissions.get(permission);
1589            if (bp != null && bp.isRuntime()) {
1590                permissionsState.grantRuntimePermission(bp, userId);
1591            }
1592        }
1593    }
1594
1595    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1596        Bundle extras = null;
1597        switch (res.returnCode) {
1598            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1599                extras = new Bundle();
1600                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1601                        res.origPermission);
1602                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1603                        res.origPackage);
1604                break;
1605            }
1606        }
1607        return extras;
1608    }
1609
1610    void scheduleWriteSettingsLocked() {
1611        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1612            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1613        }
1614    }
1615
1616    void scheduleWritePackageRestrictionsLocked(int userId) {
1617        if (!sUserManager.exists(userId)) return;
1618        mDirtyUsers.add(userId);
1619        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1620            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1621        }
1622    }
1623
1624    public static PackageManagerService main(Context context, Installer installer,
1625            boolean factoryTest, boolean onlyCore) {
1626        PackageManagerService m = new PackageManagerService(context, installer,
1627                factoryTest, onlyCore);
1628        ServiceManager.addService("package", m);
1629        return m;
1630    }
1631
1632    static String[] splitString(String str, char sep) {
1633        int count = 1;
1634        int i = 0;
1635        while ((i=str.indexOf(sep, i)) >= 0) {
1636            count++;
1637            i++;
1638        }
1639
1640        String[] res = new String[count];
1641        i=0;
1642        count = 0;
1643        int lastI=0;
1644        while ((i=str.indexOf(sep, i)) >= 0) {
1645            res[count] = str.substring(lastI, i);
1646            count++;
1647            i++;
1648            lastI = i;
1649        }
1650        res[count] = str.substring(lastI, str.length());
1651        return res;
1652    }
1653
1654    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1655        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1656                Context.DISPLAY_SERVICE);
1657        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1658    }
1659
1660    public PackageManagerService(Context context, Installer installer,
1661            boolean factoryTest, boolean onlyCore) {
1662        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1663                SystemClock.uptimeMillis());
1664
1665        if (mSdkVersion <= 0) {
1666            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1667        }
1668
1669        mContext = context;
1670        mFactoryTest = factoryTest;
1671        mOnlyCore = onlyCore;
1672        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1673        mMetrics = new DisplayMetrics();
1674        mSettings = new Settings(mPackages);
1675        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1676                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1677        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1678                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1679        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1680                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1681        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1682                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1683        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1684                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1685        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1686                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1687
1688        // TODO: add a property to control this?
1689        long dexOptLRUThresholdInMinutes;
1690        if (mLazyDexOpt) {
1691            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1692        } else {
1693            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1694        }
1695        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1696
1697        String separateProcesses = SystemProperties.get("debug.separate_processes");
1698        if (separateProcesses != null && separateProcesses.length() > 0) {
1699            if ("*".equals(separateProcesses)) {
1700                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1701                mSeparateProcesses = null;
1702                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1703            } else {
1704                mDefParseFlags = 0;
1705                mSeparateProcesses = separateProcesses.split(",");
1706                Slog.w(TAG, "Running with debug.separate_processes: "
1707                        + separateProcesses);
1708            }
1709        } else {
1710            mDefParseFlags = 0;
1711            mSeparateProcesses = null;
1712        }
1713
1714        mInstaller = installer;
1715        mPackageDexOptimizer = new PackageDexOptimizer(this);
1716        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1717
1718        getDefaultDisplayMetrics(context, mMetrics);
1719
1720        SystemConfig systemConfig = SystemConfig.getInstance();
1721        mGlobalGids = systemConfig.getGlobalGids();
1722        mSystemPermissions = systemConfig.getSystemPermissions();
1723        mAvailableFeatures = systemConfig.getAvailableFeatures();
1724
1725        synchronized (mInstallLock) {
1726        // writer
1727        synchronized (mPackages) {
1728            mHandlerThread = new ServiceThread(TAG,
1729                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1730            mHandlerThread.start();
1731            mHandler = new PackageHandler(mHandlerThread.getLooper());
1732            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1733
1734            File dataDir = Environment.getDataDirectory();
1735            mAppDataDir = new File(dataDir, "data");
1736            mAppInstallDir = new File(dataDir, "app");
1737            mAppLib32InstallDir = new File(dataDir, "app-lib");
1738            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1739            mUserAppDataDir = new File(dataDir, "user");
1740            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1741
1742            sUserManager = new UserManagerService(context, this,
1743                    mInstallLock, mPackages);
1744
1745            // Propagate permission configuration in to package manager.
1746            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1747                    = systemConfig.getPermissions();
1748            for (int i=0; i<permConfig.size(); i++) {
1749                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1750                BasePermission bp = mSettings.mPermissions.get(perm.name);
1751                if (bp == null) {
1752                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1753                    mSettings.mPermissions.put(perm.name, bp);
1754                }
1755                if (perm.gids != null) {
1756                    bp.setGids(perm.gids, perm.perUser);
1757                }
1758            }
1759
1760            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1761            for (int i=0; i<libConfig.size(); i++) {
1762                mSharedLibraries.put(libConfig.keyAt(i),
1763                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1764            }
1765
1766            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1767
1768            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1769                    mSdkVersion, mOnlyCore);
1770
1771            String customResolverActivity = Resources.getSystem().getString(
1772                    R.string.config_customResolverActivity);
1773            if (TextUtils.isEmpty(customResolverActivity)) {
1774                customResolverActivity = null;
1775            } else {
1776                mCustomResolverComponentName = ComponentName.unflattenFromString(
1777                        customResolverActivity);
1778            }
1779
1780            long startTime = SystemClock.uptimeMillis();
1781
1782            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1783                    startTime);
1784
1785            // Set flag to monitor and not change apk file paths when
1786            // scanning install directories.
1787            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1788
1789            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1790
1791            /**
1792             * Add everything in the in the boot class path to the
1793             * list of process files because dexopt will have been run
1794             * if necessary during zygote startup.
1795             */
1796            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1797            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1798
1799            if (bootClassPath != null) {
1800                String[] bootClassPathElements = splitString(bootClassPath, ':');
1801                for (String element : bootClassPathElements) {
1802                    alreadyDexOpted.add(element);
1803                }
1804            } else {
1805                Slog.w(TAG, "No BOOTCLASSPATH found!");
1806            }
1807
1808            if (systemServerClassPath != null) {
1809                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1810                for (String element : systemServerClassPathElements) {
1811                    alreadyDexOpted.add(element);
1812                }
1813            } else {
1814                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1815            }
1816
1817            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1818            final String[] dexCodeInstructionSets =
1819                    getDexCodeInstructionSets(
1820                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1821
1822            /**
1823             * Ensure all external libraries have had dexopt run on them.
1824             */
1825            if (mSharedLibraries.size() > 0) {
1826                // NOTE: For now, we're compiling these system "shared libraries"
1827                // (and framework jars) into all available architectures. It's possible
1828                // to compile them only when we come across an app that uses them (there's
1829                // already logic for that in scanPackageLI) but that adds some complexity.
1830                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1831                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1832                        final String lib = libEntry.path;
1833                        if (lib == null) {
1834                            continue;
1835                        }
1836
1837                        try {
1838                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1839                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1840                                alreadyDexOpted.add(lib);
1841                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1842                            }
1843                        } catch (FileNotFoundException e) {
1844                            Slog.w(TAG, "Library not found: " + lib);
1845                        } catch (IOException e) {
1846                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1847                                    + e.getMessage());
1848                        }
1849                    }
1850                }
1851            }
1852
1853            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1854
1855            // Gross hack for now: we know this file doesn't contain any
1856            // code, so don't dexopt it to avoid the resulting log spew.
1857            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1858
1859            // Gross hack for now: we know this file is only part of
1860            // the boot class path for art, so don't dexopt it to
1861            // avoid the resulting log spew.
1862            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1863
1864            /**
1865             * And there are a number of commands implemented in Java, which
1866             * we currently need to do the dexopt on so that they can be
1867             * run from a non-root shell.
1868             */
1869            String[] frameworkFiles = frameworkDir.list();
1870            if (frameworkFiles != null) {
1871                // TODO: We could compile these only for the most preferred ABI. We should
1872                // first double check that the dex files for these commands are not referenced
1873                // by other system apps.
1874                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1875                    for (int i=0; i<frameworkFiles.length; i++) {
1876                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1877                        String path = libPath.getPath();
1878                        // Skip the file if we already did it.
1879                        if (alreadyDexOpted.contains(path)) {
1880                            continue;
1881                        }
1882                        // Skip the file if it is not a type we want to dexopt.
1883                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1884                            continue;
1885                        }
1886                        try {
1887                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1888                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1889                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1890                            }
1891                        } catch (FileNotFoundException e) {
1892                            Slog.w(TAG, "Jar not found: " + path);
1893                        } catch (IOException e) {
1894                            Slog.w(TAG, "Exception reading jar: " + path, e);
1895                        }
1896                    }
1897                }
1898            }
1899
1900            // Collect vendor overlay packages.
1901            // (Do this before scanning any apps.)
1902            // For security and version matching reason, only consider
1903            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1904            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1905            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1906                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1907
1908            // Find base frameworks (resource packages without code).
1909            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1910                    | PackageParser.PARSE_IS_SYSTEM_DIR
1911                    | PackageParser.PARSE_IS_PRIVILEGED,
1912                    scanFlags | SCAN_NO_DEX, 0);
1913
1914            // Collected privileged system packages.
1915            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1916            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1917                    | PackageParser.PARSE_IS_SYSTEM_DIR
1918                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1919
1920            // Collect ordinary system packages.
1921            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1922            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1923                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1924
1925            // Collect all vendor packages.
1926            File vendorAppDir = new File("/vendor/app");
1927            try {
1928                vendorAppDir = vendorAppDir.getCanonicalFile();
1929            } catch (IOException e) {
1930                // failed to look up canonical path, continue with original one
1931            }
1932            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1933                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1934
1935            // Collect all OEM packages.
1936            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1937            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1938                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1939
1940            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1941            mInstaller.moveFiles();
1942
1943            // Prune any system packages that no longer exist.
1944            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1945            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1946            if (!mOnlyCore) {
1947                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1948                while (psit.hasNext()) {
1949                    PackageSetting ps = psit.next();
1950
1951                    /*
1952                     * If this is not a system app, it can't be a
1953                     * disable system app.
1954                     */
1955                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1956                        continue;
1957                    }
1958
1959                    /*
1960                     * If the package is scanned, it's not erased.
1961                     */
1962                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1963                    if (scannedPkg != null) {
1964                        /*
1965                         * If the system app is both scanned and in the
1966                         * disabled packages list, then it must have been
1967                         * added via OTA. Remove it from the currently
1968                         * scanned package so the previously user-installed
1969                         * application can be scanned.
1970                         */
1971                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1972                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1973                                    + ps.name + "; removing system app.  Last known codePath="
1974                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1975                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1976                                    + scannedPkg.mVersionCode);
1977                            removePackageLI(ps, true);
1978                            expectingBetter.put(ps.name, ps.codePath);
1979                        }
1980
1981                        continue;
1982                    }
1983
1984                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1985                        psit.remove();
1986                        logCriticalInfo(Log.WARN, "System package " + ps.name
1987                                + " no longer exists; wiping its data");
1988                        removeDataDirsLI(null, ps.name);
1989                    } else {
1990                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1991                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1992                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1993                        }
1994                    }
1995                }
1996            }
1997
1998            //look for any incomplete package installations
1999            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2000            //clean up list
2001            for(int i = 0; i < deletePkgsList.size(); i++) {
2002                //clean up here
2003                cleanupInstallFailedPackage(deletePkgsList.get(i));
2004            }
2005            //delete tmp files
2006            deleteTempPackageFiles();
2007
2008            // Remove any shared userIDs that have no associated packages
2009            mSettings.pruneSharedUsersLPw();
2010
2011            if (!mOnlyCore) {
2012                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2013                        SystemClock.uptimeMillis());
2014                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2015
2016                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2017                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2018
2019                /**
2020                 * Remove disable package settings for any updated system
2021                 * apps that were removed via an OTA. If they're not a
2022                 * previously-updated app, remove them completely.
2023                 * Otherwise, just revoke their system-level permissions.
2024                 */
2025                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2026                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2027                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2028
2029                    String msg;
2030                    if (deletedPkg == null) {
2031                        msg = "Updated system package " + deletedAppName
2032                                + " no longer exists; wiping its data";
2033                        removeDataDirsLI(null, deletedAppName);
2034                    } else {
2035                        msg = "Updated system app + " + deletedAppName
2036                                + " no longer present; removing system privileges for "
2037                                + deletedAppName;
2038
2039                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2040
2041                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2042                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2043                    }
2044                    logCriticalInfo(Log.WARN, msg);
2045                }
2046
2047                /**
2048                 * Make sure all system apps that we expected to appear on
2049                 * the userdata partition actually showed up. If they never
2050                 * appeared, crawl back and revive the system version.
2051                 */
2052                for (int i = 0; i < expectingBetter.size(); i++) {
2053                    final String packageName = expectingBetter.keyAt(i);
2054                    if (!mPackages.containsKey(packageName)) {
2055                        final File scanFile = expectingBetter.valueAt(i);
2056
2057                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2058                                + " but never showed up; reverting to system");
2059
2060                        final int reparseFlags;
2061                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2062                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2063                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2064                                    | PackageParser.PARSE_IS_PRIVILEGED;
2065                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2066                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2067                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2068                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2069                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2070                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2071                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2072                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2073                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2074                        } else {
2075                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2076                            continue;
2077                        }
2078
2079                        mSettings.enableSystemPackageLPw(packageName);
2080
2081                        try {
2082                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2083                        } catch (PackageManagerException e) {
2084                            Slog.e(TAG, "Failed to parse original system package: "
2085                                    + e.getMessage());
2086                        }
2087                    }
2088                }
2089            }
2090
2091            // Now that we know all of the shared libraries, update all clients to have
2092            // the correct library paths.
2093            updateAllSharedLibrariesLPw();
2094
2095            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2096                // NOTE: We ignore potential failures here during a system scan (like
2097                // the rest of the commands above) because there's precious little we
2098                // can do about it. A settings error is reported, though.
2099                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2100                        false /* force dexopt */, false /* defer dexopt */);
2101            }
2102
2103            // Now that we know all the packages we are keeping,
2104            // read and update their last usage times.
2105            mPackageUsage.readLP();
2106
2107            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2108                    SystemClock.uptimeMillis());
2109            Slog.i(TAG, "Time to scan packages: "
2110                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2111                    + " seconds");
2112
2113            // If the platform SDK has changed since the last time we booted,
2114            // we need to re-grant app permission to catch any new ones that
2115            // appear.  This is really a hack, and means that apps can in some
2116            // cases get permissions that the user didn't initially explicitly
2117            // allow...  it would be nice to have some better way to handle
2118            // this situation.
2119            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2120                    != mSdkVersion;
2121            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2122                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2123                    + "; regranting permissions for internal storage");
2124            mSettings.mInternalSdkPlatform = mSdkVersion;
2125
2126            // For now runtime permissions are toggled via a system property.
2127            if (!RUNTIME_PERMISSIONS_ENABLED) {
2128                // Remove the runtime permissions state if the feature
2129                // was disabled by flipping the system property.
2130                mSettings.deleteRuntimePermissionsFiles();
2131            }
2132
2133            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2134                    | (regrantPermissions
2135                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2136                            : 0));
2137
2138            // If this is the first boot, and it is a normal boot, then
2139            // we need to initialize the default preferred apps.
2140            if (!mRestoredSettings && !onlyCore) {
2141                mSettings.readDefaultPreferredAppsLPw(this, 0);
2142            }
2143
2144            // If this is first boot after an OTA, and a normal boot, then
2145            // we need to clear code cache directories.
2146            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2147            if (mIsUpgrade && !onlyCore) {
2148                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2149                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2150                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2151                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2152                }
2153                mSettings.mFingerprint = Build.FINGERPRINT;
2154            }
2155
2156            // All the changes are done during package scanning.
2157            mSettings.updateInternalDatabaseVersion();
2158
2159            // can downgrade to reader
2160            mSettings.writeLPr();
2161
2162            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2163                    SystemClock.uptimeMillis());
2164
2165            mRequiredVerifierPackage = getRequiredVerifierLPr();
2166
2167            mInstallerService = new PackageInstallerService(context, this);
2168
2169            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2170            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2171                    mIntentFilterVerifierComponent);
2172
2173            primeDomainVerificationsLPw(false);
2174
2175        } // synchronized (mPackages)
2176        } // synchronized (mInstallLock)
2177
2178        // Now after opening every single application zip, make sure they
2179        // are all flushed.  Not really needed, but keeps things nice and
2180        // tidy.
2181        Runtime.getRuntime().gc();
2182    }
2183
2184    @Override
2185    public boolean isFirstBoot() {
2186        return !mRestoredSettings;
2187    }
2188
2189    @Override
2190    public boolean isOnlyCoreApps() {
2191        return mOnlyCore;
2192    }
2193
2194    @Override
2195    public boolean isUpgrade() {
2196        return mIsUpgrade;
2197    }
2198
2199    private String getRequiredVerifierLPr() {
2200        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2201        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2202                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2203
2204        String requiredVerifier = null;
2205
2206        final int N = receivers.size();
2207        for (int i = 0; i < N; i++) {
2208            final ResolveInfo info = receivers.get(i);
2209
2210            if (info.activityInfo == null) {
2211                continue;
2212            }
2213
2214            final String packageName = info.activityInfo.packageName;
2215
2216            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2217                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2218                continue;
2219            }
2220
2221            if (requiredVerifier != null) {
2222                throw new RuntimeException("There can be only one required verifier");
2223            }
2224
2225            requiredVerifier = packageName;
2226        }
2227
2228        return requiredVerifier;
2229    }
2230
2231    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2232        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2233        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2234                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2235
2236        ComponentName verifierComponentName = null;
2237
2238        int priority = -1000;
2239        final int N = receivers.size();
2240        for (int i = 0; i < N; i++) {
2241            final ResolveInfo info = receivers.get(i);
2242
2243            if (info.activityInfo == null) {
2244                continue;
2245            }
2246
2247            final String packageName = info.activityInfo.packageName;
2248
2249            final PackageSetting ps = mSettings.mPackages.get(packageName);
2250            if (ps == null) {
2251                continue;
2252            }
2253
2254            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2255                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2256                continue;
2257            }
2258
2259            // Select the IntentFilterVerifier with the highest priority
2260            if (priority < info.priority) {
2261                priority = info.priority;
2262                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2263                Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName +
2264                        " with priority: " + info.priority);
2265            }
2266        }
2267
2268        return verifierComponentName;
2269    }
2270
2271    private void primeDomainVerificationsLPw(boolean logging) {
2272        Slog.d(TAG, "Start priming domain verification");
2273        boolean updated = false;
2274        ArrayList<String> allHosts = new ArrayList<>();
2275        for (PackageParser.Package pkg : mPackages.values()) {
2276            final String packageName = pkg.packageName;
2277            if (!hasDomainURLs(pkg)) {
2278                if (logging) {
2279                    Slog.d(TAG, "No priming domain verifications for " +
2280                            "package with no domain URLs: " + packageName);
2281                }
2282                continue;
2283            }
2284            if (!pkg.isSystemApp()) {
2285                if (logging) {
2286                    Slog.d(TAG, "No priming domain verifications for a non system package : " +
2287                            packageName);
2288                }
2289                continue;
2290            }
2291            for (PackageParser.Activity a : pkg.activities) {
2292                for (ActivityIntentInfo filter : a.intents) {
2293                    if (hasValidDomains(filter, false)) {
2294                        allHosts.addAll(filter.getHostsList());
2295                    }
2296                }
2297            }
2298            if (allHosts.size() == 0) {
2299                allHosts.add("*");
2300            }
2301            IntentFilterVerificationInfo ivi =
2302                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHosts);
2303            if (ivi != null) {
2304                // We will always log this
2305                Slog.d(TAG, "Priming domain verifications for package: " + packageName);
2306                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2307                updated = true;
2308            }
2309            else {
2310                if (logging) {
2311                    Slog.d(TAG, "No priming domain verifications for package: " + packageName);
2312                }
2313            }
2314            allHosts.clear();
2315        }
2316        if (updated) {
2317            scheduleWriteSettingsLocked();
2318        }
2319        Slog.d(TAG, "End priming domain verification");
2320    }
2321
2322    @Override
2323    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2324            throws RemoteException {
2325        try {
2326            return super.onTransact(code, data, reply, flags);
2327        } catch (RuntimeException e) {
2328            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2329                Slog.wtf(TAG, "Package Manager Crash", e);
2330            }
2331            throw e;
2332        }
2333    }
2334
2335    void cleanupInstallFailedPackage(PackageSetting ps) {
2336        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2337
2338        removeDataDirsLI(ps.volumeUuid, ps.name);
2339        if (ps.codePath != null) {
2340            if (ps.codePath.isDirectory()) {
2341                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2342            } else {
2343                ps.codePath.delete();
2344            }
2345        }
2346        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2347            if (ps.resourcePath.isDirectory()) {
2348                FileUtils.deleteContents(ps.resourcePath);
2349            }
2350            ps.resourcePath.delete();
2351        }
2352        mSettings.removePackageLPw(ps.name);
2353    }
2354
2355    static int[] appendInts(int[] cur, int[] add) {
2356        if (add == null) return cur;
2357        if (cur == null) return add;
2358        final int N = add.length;
2359        for (int i=0; i<N; i++) {
2360            cur = appendInt(cur, add[i]);
2361        }
2362        return cur;
2363    }
2364
2365    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2366        if (!sUserManager.exists(userId)) return null;
2367        final PackageSetting ps = (PackageSetting) p.mExtras;
2368        if (ps == null) {
2369            return null;
2370        }
2371
2372        final PermissionsState permissionsState = ps.getPermissionsState();
2373
2374        final int[] gids = permissionsState.computeGids(userId);
2375        final Set<String> permissions = permissionsState.getPermissions(userId);
2376        final PackageUserState state = ps.readUserState(userId);
2377
2378        return PackageParser.generatePackageInfo(p, gids, flags,
2379                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2380    }
2381
2382    @Override
2383    public boolean isPackageAvailable(String packageName, int userId) {
2384        if (!sUserManager.exists(userId)) return false;
2385        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2386        synchronized (mPackages) {
2387            PackageParser.Package p = mPackages.get(packageName);
2388            if (p != null) {
2389                final PackageSetting ps = (PackageSetting) p.mExtras;
2390                if (ps != null) {
2391                    final PackageUserState state = ps.readUserState(userId);
2392                    if (state != null) {
2393                        return PackageParser.isAvailable(state);
2394                    }
2395                }
2396            }
2397        }
2398        return false;
2399    }
2400
2401    @Override
2402    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2403        if (!sUserManager.exists(userId)) return null;
2404        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2405        // reader
2406        synchronized (mPackages) {
2407            PackageParser.Package p = mPackages.get(packageName);
2408            if (DEBUG_PACKAGE_INFO)
2409                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2410            if (p != null) {
2411                return generatePackageInfo(p, flags, userId);
2412            }
2413            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2414                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2415            }
2416        }
2417        return null;
2418    }
2419
2420    @Override
2421    public String[] currentToCanonicalPackageNames(String[] names) {
2422        String[] out = new String[names.length];
2423        // reader
2424        synchronized (mPackages) {
2425            for (int i=names.length-1; i>=0; i--) {
2426                PackageSetting ps = mSettings.mPackages.get(names[i]);
2427                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2428            }
2429        }
2430        return out;
2431    }
2432
2433    @Override
2434    public String[] canonicalToCurrentPackageNames(String[] names) {
2435        String[] out = new String[names.length];
2436        // reader
2437        synchronized (mPackages) {
2438            for (int i=names.length-1; i>=0; i--) {
2439                String cur = mSettings.mRenamedPackages.get(names[i]);
2440                out[i] = cur != null ? cur : names[i];
2441            }
2442        }
2443        return out;
2444    }
2445
2446    @Override
2447    public int getPackageUid(String packageName, int userId) {
2448        if (!sUserManager.exists(userId)) return -1;
2449        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2450
2451        // reader
2452        synchronized (mPackages) {
2453            PackageParser.Package p = mPackages.get(packageName);
2454            if(p != null) {
2455                return UserHandle.getUid(userId, p.applicationInfo.uid);
2456            }
2457            PackageSetting ps = mSettings.mPackages.get(packageName);
2458            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2459                return -1;
2460            }
2461            p = ps.pkg;
2462            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2463        }
2464    }
2465
2466    @Override
2467    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2468        if (!sUserManager.exists(userId)) {
2469            return null;
2470        }
2471
2472        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2473                "getPackageGids");
2474
2475        // reader
2476        synchronized (mPackages) {
2477            PackageParser.Package p = mPackages.get(packageName);
2478            if (DEBUG_PACKAGE_INFO) {
2479                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2480            }
2481            if (p != null) {
2482                PackageSetting ps = (PackageSetting) p.mExtras;
2483                return ps.getPermissionsState().computeGids(userId);
2484            }
2485        }
2486
2487        return null;
2488    }
2489
2490    static PermissionInfo generatePermissionInfo(
2491            BasePermission bp, int flags) {
2492        if (bp.perm != null) {
2493            return PackageParser.generatePermissionInfo(bp.perm, flags);
2494        }
2495        PermissionInfo pi = new PermissionInfo();
2496        pi.name = bp.name;
2497        pi.packageName = bp.sourcePackage;
2498        pi.nonLocalizedLabel = bp.name;
2499        pi.protectionLevel = bp.protectionLevel;
2500        return pi;
2501    }
2502
2503    @Override
2504    public PermissionInfo getPermissionInfo(String name, int flags) {
2505        // reader
2506        synchronized (mPackages) {
2507            final BasePermission p = mSettings.mPermissions.get(name);
2508            if (p != null) {
2509                return generatePermissionInfo(p, flags);
2510            }
2511            return null;
2512        }
2513    }
2514
2515    @Override
2516    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2517        // reader
2518        synchronized (mPackages) {
2519            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2520            for (BasePermission p : mSettings.mPermissions.values()) {
2521                if (group == null) {
2522                    if (p.perm == null || p.perm.info.group == null) {
2523                        out.add(generatePermissionInfo(p, flags));
2524                    }
2525                } else {
2526                    if (p.perm != null && group.equals(p.perm.info.group)) {
2527                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2528                    }
2529                }
2530            }
2531
2532            if (out.size() > 0) {
2533                return out;
2534            }
2535            return mPermissionGroups.containsKey(group) ? out : null;
2536        }
2537    }
2538
2539    @Override
2540    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2541        // reader
2542        synchronized (mPackages) {
2543            return PackageParser.generatePermissionGroupInfo(
2544                    mPermissionGroups.get(name), flags);
2545        }
2546    }
2547
2548    @Override
2549    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2550        // reader
2551        synchronized (mPackages) {
2552            final int N = mPermissionGroups.size();
2553            ArrayList<PermissionGroupInfo> out
2554                    = new ArrayList<PermissionGroupInfo>(N);
2555            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2556                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2557            }
2558            return out;
2559        }
2560    }
2561
2562    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2563            int userId) {
2564        if (!sUserManager.exists(userId)) return null;
2565        PackageSetting ps = mSettings.mPackages.get(packageName);
2566        if (ps != null) {
2567            if (ps.pkg == null) {
2568                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2569                        flags, userId);
2570                if (pInfo != null) {
2571                    return pInfo.applicationInfo;
2572                }
2573                return null;
2574            }
2575            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2576                    ps.readUserState(userId), userId);
2577        }
2578        return null;
2579    }
2580
2581    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2582            int userId) {
2583        if (!sUserManager.exists(userId)) return null;
2584        PackageSetting ps = mSettings.mPackages.get(packageName);
2585        if (ps != null) {
2586            PackageParser.Package pkg = ps.pkg;
2587            if (pkg == null) {
2588                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2589                    return null;
2590                }
2591                // Only data remains, so we aren't worried about code paths
2592                pkg = new PackageParser.Package(packageName);
2593                pkg.applicationInfo.packageName = packageName;
2594                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2595                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2596                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2597                        packageName, userId).getAbsolutePath();
2598                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2599                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2600            }
2601            return generatePackageInfo(pkg, flags, userId);
2602        }
2603        return null;
2604    }
2605
2606    @Override
2607    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2608        if (!sUserManager.exists(userId)) return null;
2609        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2610        // writer
2611        synchronized (mPackages) {
2612            PackageParser.Package p = mPackages.get(packageName);
2613            if (DEBUG_PACKAGE_INFO) Log.v(
2614                    TAG, "getApplicationInfo " + packageName
2615                    + ": " + p);
2616            if (p != null) {
2617                PackageSetting ps = mSettings.mPackages.get(packageName);
2618                if (ps == null) return null;
2619                // Note: isEnabledLP() does not apply here - always return info
2620                return PackageParser.generateApplicationInfo(
2621                        p, flags, ps.readUserState(userId), userId);
2622            }
2623            if ("android".equals(packageName)||"system".equals(packageName)) {
2624                return mAndroidApplication;
2625            }
2626            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2627                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2628            }
2629        }
2630        return null;
2631    }
2632
2633    @Override
2634    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2635            final IPackageDataObserver observer) {
2636        mContext.enforceCallingOrSelfPermission(
2637                android.Manifest.permission.CLEAR_APP_CACHE, null);
2638        // Queue up an async operation since clearing cache may take a little while.
2639        mHandler.post(new Runnable() {
2640            public void run() {
2641                mHandler.removeCallbacks(this);
2642                int retCode = -1;
2643                synchronized (mInstallLock) {
2644                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2645                    if (retCode < 0) {
2646                        Slog.w(TAG, "Couldn't clear application caches");
2647                    }
2648                }
2649                if (observer != null) {
2650                    try {
2651                        observer.onRemoveCompleted(null, (retCode >= 0));
2652                    } catch (RemoteException e) {
2653                        Slog.w(TAG, "RemoveException when invoking call back");
2654                    }
2655                }
2656            }
2657        });
2658    }
2659
2660    @Override
2661    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2662            final IntentSender pi) {
2663        mContext.enforceCallingOrSelfPermission(
2664                android.Manifest.permission.CLEAR_APP_CACHE, null);
2665        // Queue up an async operation since clearing cache may take a little while.
2666        mHandler.post(new Runnable() {
2667            public void run() {
2668                mHandler.removeCallbacks(this);
2669                int retCode = -1;
2670                synchronized (mInstallLock) {
2671                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2672                    if (retCode < 0) {
2673                        Slog.w(TAG, "Couldn't clear application caches");
2674                    }
2675                }
2676                if(pi != null) {
2677                    try {
2678                        // Callback via pending intent
2679                        int code = (retCode >= 0) ? 1 : 0;
2680                        pi.sendIntent(null, code, null,
2681                                null, null);
2682                    } catch (SendIntentException e1) {
2683                        Slog.i(TAG, "Failed to send pending intent");
2684                    }
2685                }
2686            }
2687        });
2688    }
2689
2690    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2691        synchronized (mInstallLock) {
2692            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2693                throw new IOException("Failed to free enough space");
2694            }
2695        }
2696    }
2697
2698    @Override
2699    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2700        if (!sUserManager.exists(userId)) return null;
2701        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2702        synchronized (mPackages) {
2703            PackageParser.Activity a = mActivities.mActivities.get(component);
2704
2705            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2706            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2707                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2708                if (ps == null) return null;
2709                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2710                        userId);
2711            }
2712            if (mResolveComponentName.equals(component)) {
2713                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2714                        new PackageUserState(), userId);
2715            }
2716        }
2717        return null;
2718    }
2719
2720    @Override
2721    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2722            String resolvedType) {
2723        synchronized (mPackages) {
2724            PackageParser.Activity a = mActivities.mActivities.get(component);
2725            if (a == null) {
2726                return false;
2727            }
2728            for (int i=0; i<a.intents.size(); i++) {
2729                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2730                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2731                    return true;
2732                }
2733            }
2734            return false;
2735        }
2736    }
2737
2738    @Override
2739    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2740        if (!sUserManager.exists(userId)) return null;
2741        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2742        synchronized (mPackages) {
2743            PackageParser.Activity a = mReceivers.mActivities.get(component);
2744            if (DEBUG_PACKAGE_INFO) Log.v(
2745                TAG, "getReceiverInfo " + component + ": " + a);
2746            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2747                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2748                if (ps == null) return null;
2749                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2750                        userId);
2751            }
2752        }
2753        return null;
2754    }
2755
2756    @Override
2757    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2758        if (!sUserManager.exists(userId)) return null;
2759        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2760        synchronized (mPackages) {
2761            PackageParser.Service s = mServices.mServices.get(component);
2762            if (DEBUG_PACKAGE_INFO) Log.v(
2763                TAG, "getServiceInfo " + component + ": " + s);
2764            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2765                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2766                if (ps == null) return null;
2767                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2768                        userId);
2769            }
2770        }
2771        return null;
2772    }
2773
2774    @Override
2775    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2776        if (!sUserManager.exists(userId)) return null;
2777        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2778        synchronized (mPackages) {
2779            PackageParser.Provider p = mProviders.mProviders.get(component);
2780            if (DEBUG_PACKAGE_INFO) Log.v(
2781                TAG, "getProviderInfo " + component + ": " + p);
2782            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2783                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2784                if (ps == null) return null;
2785                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2786                        userId);
2787            }
2788        }
2789        return null;
2790    }
2791
2792    @Override
2793    public String[] getSystemSharedLibraryNames() {
2794        Set<String> libSet;
2795        synchronized (mPackages) {
2796            libSet = mSharedLibraries.keySet();
2797            int size = libSet.size();
2798            if (size > 0) {
2799                String[] libs = new String[size];
2800                libSet.toArray(libs);
2801                return libs;
2802            }
2803        }
2804        return null;
2805    }
2806
2807    /**
2808     * @hide
2809     */
2810    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2811        synchronized (mPackages) {
2812            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2813            if (lib != null && lib.apk != null) {
2814                return mPackages.get(lib.apk);
2815            }
2816        }
2817        return null;
2818    }
2819
2820    @Override
2821    public FeatureInfo[] getSystemAvailableFeatures() {
2822        Collection<FeatureInfo> featSet;
2823        synchronized (mPackages) {
2824            featSet = mAvailableFeatures.values();
2825            int size = featSet.size();
2826            if (size > 0) {
2827                FeatureInfo[] features = new FeatureInfo[size+1];
2828                featSet.toArray(features);
2829                FeatureInfo fi = new FeatureInfo();
2830                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2831                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2832                features[size] = fi;
2833                return features;
2834            }
2835        }
2836        return null;
2837    }
2838
2839    @Override
2840    public boolean hasSystemFeature(String name) {
2841        synchronized (mPackages) {
2842            return mAvailableFeatures.containsKey(name);
2843        }
2844    }
2845
2846    private void checkValidCaller(int uid, int userId) {
2847        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2848            return;
2849
2850        throw new SecurityException("Caller uid=" + uid
2851                + " is not privileged to communicate with user=" + userId);
2852    }
2853
2854    @Override
2855    public int checkPermission(String permName, String pkgName, int userId) {
2856        if (!sUserManager.exists(userId)) {
2857            return PackageManager.PERMISSION_DENIED;
2858        }
2859
2860        synchronized (mPackages) {
2861            final PackageParser.Package p = mPackages.get(pkgName);
2862            if (p != null && p.mExtras != null) {
2863                final PackageSetting ps = (PackageSetting) p.mExtras;
2864                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2865                    return PackageManager.PERMISSION_GRANTED;
2866                }
2867            }
2868        }
2869
2870        return PackageManager.PERMISSION_DENIED;
2871    }
2872
2873    @Override
2874    public int checkUidPermission(String permName, int uid) {
2875        final int userId = UserHandle.getUserId(uid);
2876
2877        if (!sUserManager.exists(userId)) {
2878            return PackageManager.PERMISSION_DENIED;
2879        }
2880
2881        synchronized (mPackages) {
2882            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2883            if (obj != null) {
2884                final SettingBase ps = (SettingBase) obj;
2885                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2886                    return PackageManager.PERMISSION_GRANTED;
2887                }
2888            } else {
2889                ArraySet<String> perms = mSystemPermissions.get(uid);
2890                if (perms != null && perms.contains(permName)) {
2891                    return PackageManager.PERMISSION_GRANTED;
2892                }
2893            }
2894        }
2895
2896        return PackageManager.PERMISSION_DENIED;
2897    }
2898
2899    /**
2900     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2901     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2902     * @param checkShell TODO(yamasani):
2903     * @param message the message to log on security exception
2904     */
2905    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2906            boolean checkShell, String message) {
2907        if (userId < 0) {
2908            throw new IllegalArgumentException("Invalid userId " + userId);
2909        }
2910        if (checkShell) {
2911            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2912        }
2913        if (userId == UserHandle.getUserId(callingUid)) return;
2914        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2915            if (requireFullPermission) {
2916                mContext.enforceCallingOrSelfPermission(
2917                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2918            } else {
2919                try {
2920                    mContext.enforceCallingOrSelfPermission(
2921                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2922                } catch (SecurityException se) {
2923                    mContext.enforceCallingOrSelfPermission(
2924                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2925                }
2926            }
2927        }
2928    }
2929
2930    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2931        if (callingUid == Process.SHELL_UID) {
2932            if (userHandle >= 0
2933                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2934                throw new SecurityException("Shell does not have permission to access user "
2935                        + userHandle);
2936            } else if (userHandle < 0) {
2937                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2938                        + Debug.getCallers(3));
2939            }
2940        }
2941    }
2942
2943    private BasePermission findPermissionTreeLP(String permName) {
2944        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2945            if (permName.startsWith(bp.name) &&
2946                    permName.length() > bp.name.length() &&
2947                    permName.charAt(bp.name.length()) == '.') {
2948                return bp;
2949            }
2950        }
2951        return null;
2952    }
2953
2954    private BasePermission checkPermissionTreeLP(String permName) {
2955        if (permName != null) {
2956            BasePermission bp = findPermissionTreeLP(permName);
2957            if (bp != null) {
2958                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2959                    return bp;
2960                }
2961                throw new SecurityException("Calling uid "
2962                        + Binder.getCallingUid()
2963                        + " is not allowed to add to permission tree "
2964                        + bp.name + " owned by uid " + bp.uid);
2965            }
2966        }
2967        throw new SecurityException("No permission tree found for " + permName);
2968    }
2969
2970    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2971        if (s1 == null) {
2972            return s2 == null;
2973        }
2974        if (s2 == null) {
2975            return false;
2976        }
2977        if (s1.getClass() != s2.getClass()) {
2978            return false;
2979        }
2980        return s1.equals(s2);
2981    }
2982
2983    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2984        if (pi1.icon != pi2.icon) return false;
2985        if (pi1.logo != pi2.logo) return false;
2986        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2987        if (!compareStrings(pi1.name, pi2.name)) return false;
2988        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2989        // We'll take care of setting this one.
2990        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2991        // These are not currently stored in settings.
2992        //if (!compareStrings(pi1.group, pi2.group)) return false;
2993        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2994        //if (pi1.labelRes != pi2.labelRes) return false;
2995        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2996        return true;
2997    }
2998
2999    int permissionInfoFootprint(PermissionInfo info) {
3000        int size = info.name.length();
3001        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3002        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3003        return size;
3004    }
3005
3006    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3007        int size = 0;
3008        for (BasePermission perm : mSettings.mPermissions.values()) {
3009            if (perm.uid == tree.uid) {
3010                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3011            }
3012        }
3013        return size;
3014    }
3015
3016    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3017        // We calculate the max size of permissions defined by this uid and throw
3018        // if that plus the size of 'info' would exceed our stated maximum.
3019        if (tree.uid != Process.SYSTEM_UID) {
3020            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3021            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3022                throw new SecurityException("Permission tree size cap exceeded");
3023            }
3024        }
3025    }
3026
3027    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3028        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3029            throw new SecurityException("Label must be specified in permission");
3030        }
3031        BasePermission tree = checkPermissionTreeLP(info.name);
3032        BasePermission bp = mSettings.mPermissions.get(info.name);
3033        boolean added = bp == null;
3034        boolean changed = true;
3035        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3036        if (added) {
3037            enforcePermissionCapLocked(info, tree);
3038            bp = new BasePermission(info.name, tree.sourcePackage,
3039                    BasePermission.TYPE_DYNAMIC);
3040        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3041            throw new SecurityException(
3042                    "Not allowed to modify non-dynamic permission "
3043                    + info.name);
3044        } else {
3045            if (bp.protectionLevel == fixedLevel
3046                    && bp.perm.owner.equals(tree.perm.owner)
3047                    && bp.uid == tree.uid
3048                    && comparePermissionInfos(bp.perm.info, info)) {
3049                changed = false;
3050            }
3051        }
3052        bp.protectionLevel = fixedLevel;
3053        info = new PermissionInfo(info);
3054        info.protectionLevel = fixedLevel;
3055        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3056        bp.perm.info.packageName = tree.perm.info.packageName;
3057        bp.uid = tree.uid;
3058        if (added) {
3059            mSettings.mPermissions.put(info.name, bp);
3060        }
3061        if (changed) {
3062            if (!async) {
3063                mSettings.writeLPr();
3064            } else {
3065                scheduleWriteSettingsLocked();
3066            }
3067        }
3068        return added;
3069    }
3070
3071    @Override
3072    public boolean addPermission(PermissionInfo info) {
3073        synchronized (mPackages) {
3074            return addPermissionLocked(info, false);
3075        }
3076    }
3077
3078    @Override
3079    public boolean addPermissionAsync(PermissionInfo info) {
3080        synchronized (mPackages) {
3081            return addPermissionLocked(info, true);
3082        }
3083    }
3084
3085    @Override
3086    public void removePermission(String name) {
3087        synchronized (mPackages) {
3088            checkPermissionTreeLP(name);
3089            BasePermission bp = mSettings.mPermissions.get(name);
3090            if (bp != null) {
3091                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3092                    throw new SecurityException(
3093                            "Not allowed to modify non-dynamic permission "
3094                            + name);
3095                }
3096                mSettings.mPermissions.remove(name);
3097                mSettings.writeLPr();
3098            }
3099        }
3100    }
3101
3102    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3103            BasePermission bp) {
3104        int index = pkg.requestedPermissions.indexOf(bp.name);
3105        if (index == -1) {
3106            throw new SecurityException("Package " + pkg.packageName
3107                    + " has not requested permission " + bp.name);
3108        }
3109        if (!bp.isRuntime()) {
3110            throw new SecurityException("Permission " + bp.name
3111                    + " is not a changeable permission type");
3112        }
3113    }
3114
3115    @Override
3116    public boolean grantPermission(String packageName, String name, int userId) {
3117        if (!RUNTIME_PERMISSIONS_ENABLED) {
3118            return false;
3119        }
3120
3121        if (!sUserManager.exists(userId)) {
3122            return false;
3123        }
3124
3125        mContext.enforceCallingOrSelfPermission(
3126                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3127                "grantPermission");
3128
3129        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3130                "grantPermission");
3131
3132        boolean gidsChanged = false;
3133        final SettingBase sb;
3134
3135        synchronized (mPackages) {
3136            final PackageParser.Package pkg = mPackages.get(packageName);
3137            if (pkg == null) {
3138                throw new IllegalArgumentException("Unknown package: " + packageName);
3139            }
3140
3141            final BasePermission bp = mSettings.mPermissions.get(name);
3142            if (bp == null) {
3143                throw new IllegalArgumentException("Unknown permission: " + name);
3144            }
3145
3146            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3147
3148            sb = (SettingBase) pkg.mExtras;
3149            if (sb == null) {
3150                throw new IllegalArgumentException("Unknown package: " + packageName);
3151            }
3152
3153            final PermissionsState permissionsState = sb.getPermissionsState();
3154
3155            final int result = permissionsState.grantRuntimePermission(bp, userId);
3156            switch (result) {
3157                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3158                    return false;
3159                }
3160
3161                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3162                    gidsChanged = true;
3163                } break;
3164            }
3165
3166            // Not critical if that is lost - app has to request again.
3167            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3168        }
3169
3170        if (gidsChanged) {
3171            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3172        }
3173
3174        return true;
3175    }
3176
3177    @Override
3178    public boolean revokePermission(String packageName, String name, int userId) {
3179        if (!RUNTIME_PERMISSIONS_ENABLED) {
3180            return false;
3181        }
3182
3183        if (!sUserManager.exists(userId)) {
3184            return false;
3185        }
3186
3187        mContext.enforceCallingOrSelfPermission(
3188                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3189                "revokePermission");
3190
3191        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3192                "revokePermission");
3193
3194        final SettingBase sb;
3195
3196        synchronized (mPackages) {
3197            final PackageParser.Package pkg = mPackages.get(packageName);
3198            if (pkg == null) {
3199                throw new IllegalArgumentException("Unknown package: " + packageName);
3200            }
3201
3202            final BasePermission bp = mSettings.mPermissions.get(name);
3203            if (bp == null) {
3204                throw new IllegalArgumentException("Unknown permission: " + name);
3205            }
3206
3207            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3208
3209            sb = (SettingBase) pkg.mExtras;
3210            if (sb == null) {
3211                throw new IllegalArgumentException("Unknown package: " + packageName);
3212            }
3213
3214            final PermissionsState permissionsState = sb.getPermissionsState();
3215
3216            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3217                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3218                return false;
3219            }
3220
3221            // Critical, after this call all should never have the permission.
3222            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3223        }
3224
3225        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3226
3227        return true;
3228    }
3229
3230    @Override
3231    public boolean isProtectedBroadcast(String actionName) {
3232        synchronized (mPackages) {
3233            return mProtectedBroadcasts.contains(actionName);
3234        }
3235    }
3236
3237    @Override
3238    public int checkSignatures(String pkg1, String pkg2) {
3239        synchronized (mPackages) {
3240            final PackageParser.Package p1 = mPackages.get(pkg1);
3241            final PackageParser.Package p2 = mPackages.get(pkg2);
3242            if (p1 == null || p1.mExtras == null
3243                    || p2 == null || p2.mExtras == null) {
3244                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3245            }
3246            return compareSignatures(p1.mSignatures, p2.mSignatures);
3247        }
3248    }
3249
3250    @Override
3251    public int checkUidSignatures(int uid1, int uid2) {
3252        // Map to base uids.
3253        uid1 = UserHandle.getAppId(uid1);
3254        uid2 = UserHandle.getAppId(uid2);
3255        // reader
3256        synchronized (mPackages) {
3257            Signature[] s1;
3258            Signature[] s2;
3259            Object obj = mSettings.getUserIdLPr(uid1);
3260            if (obj != null) {
3261                if (obj instanceof SharedUserSetting) {
3262                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3263                } else if (obj instanceof PackageSetting) {
3264                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3265                } else {
3266                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3267                }
3268            } else {
3269                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3270            }
3271            obj = mSettings.getUserIdLPr(uid2);
3272            if (obj != null) {
3273                if (obj instanceof SharedUserSetting) {
3274                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3275                } else if (obj instanceof PackageSetting) {
3276                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3277                } else {
3278                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3279                }
3280            } else {
3281                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3282            }
3283            return compareSignatures(s1, s2);
3284        }
3285    }
3286
3287    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3288        final long identity = Binder.clearCallingIdentity();
3289        try {
3290            if (sb instanceof SharedUserSetting) {
3291                SharedUserSetting sus = (SharedUserSetting) sb;
3292                final int packageCount = sus.packages.size();
3293                for (int i = 0; i < packageCount; i++) {
3294                    PackageSetting susPs = sus.packages.valueAt(i);
3295                    if (userId == UserHandle.USER_ALL) {
3296                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3297                    } else {
3298                        final int uid = UserHandle.getUid(userId, susPs.appId);
3299                        killUid(uid, reason);
3300                    }
3301                }
3302            } else if (sb instanceof PackageSetting) {
3303                PackageSetting ps = (PackageSetting) sb;
3304                if (userId == UserHandle.USER_ALL) {
3305                    killApplication(ps.pkg.packageName, ps.appId, reason);
3306                } else {
3307                    final int uid = UserHandle.getUid(userId, ps.appId);
3308                    killUid(uid, reason);
3309                }
3310            }
3311        } finally {
3312            Binder.restoreCallingIdentity(identity);
3313        }
3314    }
3315
3316    private static void killUid(int uid, String reason) {
3317        IActivityManager am = ActivityManagerNative.getDefault();
3318        if (am != null) {
3319            try {
3320                am.killUid(uid, reason);
3321            } catch (RemoteException e) {
3322                /* ignore - same process */
3323            }
3324        }
3325    }
3326
3327    /**
3328     * Compares two sets of signatures. Returns:
3329     * <br />
3330     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3331     * <br />
3332     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3333     * <br />
3334     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3335     * <br />
3336     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3337     * <br />
3338     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3339     */
3340    static int compareSignatures(Signature[] s1, Signature[] s2) {
3341        if (s1 == null) {
3342            return s2 == null
3343                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3344                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3345        }
3346
3347        if (s2 == null) {
3348            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3349        }
3350
3351        if (s1.length != s2.length) {
3352            return PackageManager.SIGNATURE_NO_MATCH;
3353        }
3354
3355        // Since both signature sets are of size 1, we can compare without HashSets.
3356        if (s1.length == 1) {
3357            return s1[0].equals(s2[0]) ?
3358                    PackageManager.SIGNATURE_MATCH :
3359                    PackageManager.SIGNATURE_NO_MATCH;
3360        }
3361
3362        ArraySet<Signature> set1 = new ArraySet<Signature>();
3363        for (Signature sig : s1) {
3364            set1.add(sig);
3365        }
3366        ArraySet<Signature> set2 = new ArraySet<Signature>();
3367        for (Signature sig : s2) {
3368            set2.add(sig);
3369        }
3370        // Make sure s2 contains all signatures in s1.
3371        if (set1.equals(set2)) {
3372            return PackageManager.SIGNATURE_MATCH;
3373        }
3374        return PackageManager.SIGNATURE_NO_MATCH;
3375    }
3376
3377    /**
3378     * If the database version for this type of package (internal storage or
3379     * external storage) is less than the version where package signatures
3380     * were updated, return true.
3381     */
3382    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3383        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3384                DatabaseVersion.SIGNATURE_END_ENTITY))
3385                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3386                        DatabaseVersion.SIGNATURE_END_ENTITY));
3387    }
3388
3389    /**
3390     * Used for backward compatibility to make sure any packages with
3391     * certificate chains get upgraded to the new style. {@code existingSigs}
3392     * will be in the old format (since they were stored on disk from before the
3393     * system upgrade) and {@code scannedSigs} will be in the newer format.
3394     */
3395    private int compareSignaturesCompat(PackageSignatures existingSigs,
3396            PackageParser.Package scannedPkg) {
3397        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3398            return PackageManager.SIGNATURE_NO_MATCH;
3399        }
3400
3401        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3402        for (Signature sig : existingSigs.mSignatures) {
3403            existingSet.add(sig);
3404        }
3405        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3406        for (Signature sig : scannedPkg.mSignatures) {
3407            try {
3408                Signature[] chainSignatures = sig.getChainSignatures();
3409                for (Signature chainSig : chainSignatures) {
3410                    scannedCompatSet.add(chainSig);
3411                }
3412            } catch (CertificateEncodingException e) {
3413                scannedCompatSet.add(sig);
3414            }
3415        }
3416        /*
3417         * Make sure the expanded scanned set contains all signatures in the
3418         * existing one.
3419         */
3420        if (scannedCompatSet.equals(existingSet)) {
3421            // Migrate the old signatures to the new scheme.
3422            existingSigs.assignSignatures(scannedPkg.mSignatures);
3423            // The new KeySets will be re-added later in the scanning process.
3424            synchronized (mPackages) {
3425                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3426            }
3427            return PackageManager.SIGNATURE_MATCH;
3428        }
3429        return PackageManager.SIGNATURE_NO_MATCH;
3430    }
3431
3432    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3433        if (isExternal(scannedPkg)) {
3434            return mSettings.isExternalDatabaseVersionOlderThan(
3435                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3436        } else {
3437            return mSettings.isInternalDatabaseVersionOlderThan(
3438                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3439        }
3440    }
3441
3442    private int compareSignaturesRecover(PackageSignatures existingSigs,
3443            PackageParser.Package scannedPkg) {
3444        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3445            return PackageManager.SIGNATURE_NO_MATCH;
3446        }
3447
3448        String msg = null;
3449        try {
3450            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3451                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3452                        + scannedPkg.packageName);
3453                return PackageManager.SIGNATURE_MATCH;
3454            }
3455        } catch (CertificateException e) {
3456            msg = e.getMessage();
3457        }
3458
3459        logCriticalInfo(Log.INFO,
3460                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3461        return PackageManager.SIGNATURE_NO_MATCH;
3462    }
3463
3464    @Override
3465    public String[] getPackagesForUid(int uid) {
3466        uid = UserHandle.getAppId(uid);
3467        // reader
3468        synchronized (mPackages) {
3469            Object obj = mSettings.getUserIdLPr(uid);
3470            if (obj instanceof SharedUserSetting) {
3471                final SharedUserSetting sus = (SharedUserSetting) obj;
3472                final int N = sus.packages.size();
3473                final String[] res = new String[N];
3474                final Iterator<PackageSetting> it = sus.packages.iterator();
3475                int i = 0;
3476                while (it.hasNext()) {
3477                    res[i++] = it.next().name;
3478                }
3479                return res;
3480            } else if (obj instanceof PackageSetting) {
3481                final PackageSetting ps = (PackageSetting) obj;
3482                return new String[] { ps.name };
3483            }
3484        }
3485        return null;
3486    }
3487
3488    @Override
3489    public String getNameForUid(int uid) {
3490        // reader
3491        synchronized (mPackages) {
3492            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3493            if (obj instanceof SharedUserSetting) {
3494                final SharedUserSetting sus = (SharedUserSetting) obj;
3495                return sus.name + ":" + sus.userId;
3496            } else if (obj instanceof PackageSetting) {
3497                final PackageSetting ps = (PackageSetting) obj;
3498                return ps.name;
3499            }
3500        }
3501        return null;
3502    }
3503
3504    @Override
3505    public int getUidForSharedUser(String sharedUserName) {
3506        if(sharedUserName == null) {
3507            return -1;
3508        }
3509        // reader
3510        synchronized (mPackages) {
3511            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3512            if (suid == null) {
3513                return -1;
3514            }
3515            return suid.userId;
3516        }
3517    }
3518
3519    @Override
3520    public int getFlagsForUid(int uid) {
3521        synchronized (mPackages) {
3522            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3523            if (obj instanceof SharedUserSetting) {
3524                final SharedUserSetting sus = (SharedUserSetting) obj;
3525                return sus.pkgFlags;
3526            } else if (obj instanceof PackageSetting) {
3527                final PackageSetting ps = (PackageSetting) obj;
3528                return ps.pkgFlags;
3529            }
3530        }
3531        return 0;
3532    }
3533
3534    @Override
3535    public int getPrivateFlagsForUid(int uid) {
3536        synchronized (mPackages) {
3537            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3538            if (obj instanceof SharedUserSetting) {
3539                final SharedUserSetting sus = (SharedUserSetting) obj;
3540                return sus.pkgPrivateFlags;
3541            } else if (obj instanceof PackageSetting) {
3542                final PackageSetting ps = (PackageSetting) obj;
3543                return ps.pkgPrivateFlags;
3544            }
3545        }
3546        return 0;
3547    }
3548
3549    @Override
3550    public boolean isUidPrivileged(int uid) {
3551        uid = UserHandle.getAppId(uid);
3552        // reader
3553        synchronized (mPackages) {
3554            Object obj = mSettings.getUserIdLPr(uid);
3555            if (obj instanceof SharedUserSetting) {
3556                final SharedUserSetting sus = (SharedUserSetting) obj;
3557                final Iterator<PackageSetting> it = sus.packages.iterator();
3558                while (it.hasNext()) {
3559                    if (it.next().isPrivileged()) {
3560                        return true;
3561                    }
3562                }
3563            } else if (obj instanceof PackageSetting) {
3564                final PackageSetting ps = (PackageSetting) obj;
3565                return ps.isPrivileged();
3566            }
3567        }
3568        return false;
3569    }
3570
3571    @Override
3572    public String[] getAppOpPermissionPackages(String permissionName) {
3573        synchronized (mPackages) {
3574            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3575            if (pkgs == null) {
3576                return null;
3577            }
3578            return pkgs.toArray(new String[pkgs.size()]);
3579        }
3580    }
3581
3582    @Override
3583    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3584            int flags, int userId) {
3585        if (!sUserManager.exists(userId)) return null;
3586        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3587        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3588        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3589    }
3590
3591    @Override
3592    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3593            IntentFilter filter, int match, ComponentName activity) {
3594        final int userId = UserHandle.getCallingUserId();
3595        if (DEBUG_PREFERRED) {
3596            Log.v(TAG, "setLastChosenActivity intent=" + intent
3597                + " resolvedType=" + resolvedType
3598                + " flags=" + flags
3599                + " filter=" + filter
3600                + " match=" + match
3601                + " activity=" + activity);
3602            filter.dump(new PrintStreamPrinter(System.out), "    ");
3603        }
3604        intent.setComponent(null);
3605        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3606        // Find any earlier preferred or last chosen entries and nuke them
3607        findPreferredActivity(intent, resolvedType,
3608                flags, query, 0, false, true, false, userId);
3609        // Add the new activity as the last chosen for this filter
3610        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3611                "Setting last chosen");
3612    }
3613
3614    @Override
3615    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3616        final int userId = UserHandle.getCallingUserId();
3617        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3618        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3619        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3620                false, false, false, userId);
3621    }
3622
3623    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3624            int flags, List<ResolveInfo> query, int userId) {
3625        if (query != null) {
3626            final int N = query.size();
3627            if (N == 1) {
3628                return query.get(0);
3629            } else if (N > 1) {
3630                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3631                // If there is more than one activity with the same priority,
3632                // then let the user decide between them.
3633                ResolveInfo r0 = query.get(0);
3634                ResolveInfo r1 = query.get(1);
3635                if (DEBUG_INTENT_MATCHING || debug) {
3636                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3637                            + r1.activityInfo.name + "=" + r1.priority);
3638                }
3639                // If the first activity has a higher priority, or a different
3640                // default, then it is always desireable to pick it.
3641                if (r0.priority != r1.priority
3642                        || r0.preferredOrder != r1.preferredOrder
3643                        || r0.isDefault != r1.isDefault) {
3644                    return query.get(0);
3645                }
3646                // If we have saved a preference for a preferred activity for
3647                // this Intent, use that.
3648                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3649                        flags, query, r0.priority, true, false, debug, userId);
3650                if (ri != null) {
3651                    return ri;
3652                }
3653                if (userId != 0) {
3654                    ri = new ResolveInfo(mResolveInfo);
3655                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3656                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3657                            ri.activityInfo.applicationInfo);
3658                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3659                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3660                    return ri;
3661                }
3662                return mResolveInfo;
3663            }
3664        }
3665        return null;
3666    }
3667
3668    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3669            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3670        final int N = query.size();
3671        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3672                .get(userId);
3673        // Get the list of persistent preferred activities that handle the intent
3674        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3675        List<PersistentPreferredActivity> pprefs = ppir != null
3676                ? ppir.queryIntent(intent, resolvedType,
3677                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3678                : null;
3679        if (pprefs != null && pprefs.size() > 0) {
3680            final int M = pprefs.size();
3681            for (int i=0; i<M; i++) {
3682                final PersistentPreferredActivity ppa = pprefs.get(i);
3683                if (DEBUG_PREFERRED || debug) {
3684                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3685                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3686                            + "\n  component=" + ppa.mComponent);
3687                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3688                }
3689                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3690                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3691                if (DEBUG_PREFERRED || debug) {
3692                    Slog.v(TAG, "Found persistent preferred activity:");
3693                    if (ai != null) {
3694                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3695                    } else {
3696                        Slog.v(TAG, "  null");
3697                    }
3698                }
3699                if (ai == null) {
3700                    // This previously registered persistent preferred activity
3701                    // component is no longer known. Ignore it and do NOT remove it.
3702                    continue;
3703                }
3704                for (int j=0; j<N; j++) {
3705                    final ResolveInfo ri = query.get(j);
3706                    if (!ri.activityInfo.applicationInfo.packageName
3707                            .equals(ai.applicationInfo.packageName)) {
3708                        continue;
3709                    }
3710                    if (!ri.activityInfo.name.equals(ai.name)) {
3711                        continue;
3712                    }
3713                    //  Found a persistent preference that can handle the intent.
3714                    if (DEBUG_PREFERRED || debug) {
3715                        Slog.v(TAG, "Returning persistent preferred activity: " +
3716                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3717                    }
3718                    return ri;
3719                }
3720            }
3721        }
3722        return null;
3723    }
3724
3725    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3726            List<ResolveInfo> query, int priority, boolean always,
3727            boolean removeMatches, boolean debug, int userId) {
3728        if (!sUserManager.exists(userId)) return null;
3729        // writer
3730        synchronized (mPackages) {
3731            if (intent.getSelector() != null) {
3732                intent = intent.getSelector();
3733            }
3734            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3735
3736            // Try to find a matching persistent preferred activity.
3737            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3738                    debug, userId);
3739
3740            // If a persistent preferred activity matched, use it.
3741            if (pri != null) {
3742                return pri;
3743            }
3744
3745            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3746            // Get the list of preferred activities that handle the intent
3747            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3748            List<PreferredActivity> prefs = pir != null
3749                    ? pir.queryIntent(intent, resolvedType,
3750                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3751                    : null;
3752            if (prefs != null && prefs.size() > 0) {
3753                boolean changed = false;
3754                try {
3755                    // First figure out how good the original match set is.
3756                    // We will only allow preferred activities that came
3757                    // from the same match quality.
3758                    int match = 0;
3759
3760                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3761
3762                    final int N = query.size();
3763                    for (int j=0; j<N; j++) {
3764                        final ResolveInfo ri = query.get(j);
3765                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3766                                + ": 0x" + Integer.toHexString(match));
3767                        if (ri.match > match) {
3768                            match = ri.match;
3769                        }
3770                    }
3771
3772                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3773                            + Integer.toHexString(match));
3774
3775                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3776                    final int M = prefs.size();
3777                    for (int i=0; i<M; i++) {
3778                        final PreferredActivity pa = prefs.get(i);
3779                        if (DEBUG_PREFERRED || debug) {
3780                            Slog.v(TAG, "Checking PreferredActivity ds="
3781                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3782                                    + "\n  component=" + pa.mPref.mComponent);
3783                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3784                        }
3785                        if (pa.mPref.mMatch != match) {
3786                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3787                                    + Integer.toHexString(pa.mPref.mMatch));
3788                            continue;
3789                        }
3790                        // If it's not an "always" type preferred activity and that's what we're
3791                        // looking for, skip it.
3792                        if (always && !pa.mPref.mAlways) {
3793                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3794                            continue;
3795                        }
3796                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3797                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3798                        if (DEBUG_PREFERRED || debug) {
3799                            Slog.v(TAG, "Found preferred activity:");
3800                            if (ai != null) {
3801                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3802                            } else {
3803                                Slog.v(TAG, "  null");
3804                            }
3805                        }
3806                        if (ai == null) {
3807                            // This previously registered preferred activity
3808                            // component is no longer known.  Most likely an update
3809                            // to the app was installed and in the new version this
3810                            // component no longer exists.  Clean it up by removing
3811                            // it from the preferred activities list, and skip it.
3812                            Slog.w(TAG, "Removing dangling preferred activity: "
3813                                    + pa.mPref.mComponent);
3814                            pir.removeFilter(pa);
3815                            changed = true;
3816                            continue;
3817                        }
3818                        for (int j=0; j<N; j++) {
3819                            final ResolveInfo ri = query.get(j);
3820                            if (!ri.activityInfo.applicationInfo.packageName
3821                                    .equals(ai.applicationInfo.packageName)) {
3822                                continue;
3823                            }
3824                            if (!ri.activityInfo.name.equals(ai.name)) {
3825                                continue;
3826                            }
3827
3828                            if (removeMatches) {
3829                                pir.removeFilter(pa);
3830                                changed = true;
3831                                if (DEBUG_PREFERRED) {
3832                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3833                                }
3834                                break;
3835                            }
3836
3837                            // Okay we found a previously set preferred or last chosen app.
3838                            // If the result set is different from when this
3839                            // was created, we need to clear it and re-ask the
3840                            // user their preference, if we're looking for an "always" type entry.
3841                            if (always && !pa.mPref.sameSet(query)) {
3842                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3843                                        + intent + " type " + resolvedType);
3844                                if (DEBUG_PREFERRED) {
3845                                    Slog.v(TAG, "Removing preferred activity since set changed "
3846                                            + pa.mPref.mComponent);
3847                                }
3848                                pir.removeFilter(pa);
3849                                // Re-add the filter as a "last chosen" entry (!always)
3850                                PreferredActivity lastChosen = new PreferredActivity(
3851                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3852                                pir.addFilter(lastChosen);
3853                                changed = true;
3854                                return null;
3855                            }
3856
3857                            // Yay! Either the set matched or we're looking for the last chosen
3858                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3859                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3860                            return ri;
3861                        }
3862                    }
3863                } finally {
3864                    if (changed) {
3865                        if (DEBUG_PREFERRED) {
3866                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3867                        }
3868                        scheduleWritePackageRestrictionsLocked(userId);
3869                    }
3870                }
3871            }
3872        }
3873        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3874        return null;
3875    }
3876
3877    /*
3878     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3879     */
3880    @Override
3881    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3882            int targetUserId) {
3883        mContext.enforceCallingOrSelfPermission(
3884                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3885        List<CrossProfileIntentFilter> matches =
3886                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3887        if (matches != null) {
3888            int size = matches.size();
3889            for (int i = 0; i < size; i++) {
3890                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3891            }
3892        }
3893        return false;
3894    }
3895
3896    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3897            String resolvedType, int userId) {
3898        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3899        if (resolver != null) {
3900            return resolver.queryIntent(intent, resolvedType, false, userId);
3901        }
3902        return null;
3903    }
3904
3905    @Override
3906    public List<ResolveInfo> queryIntentActivities(Intent intent,
3907            String resolvedType, int flags, int userId) {
3908        if (!sUserManager.exists(userId)) return Collections.emptyList();
3909        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3910        ComponentName comp = intent.getComponent();
3911        if (comp == null) {
3912            if (intent.getSelector() != null) {
3913                intent = intent.getSelector();
3914                comp = intent.getComponent();
3915            }
3916        }
3917
3918        if (comp != null) {
3919            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3920            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3921            if (ai != null) {
3922                final ResolveInfo ri = new ResolveInfo();
3923                ri.activityInfo = ai;
3924                list.add(ri);
3925            }
3926            return list;
3927        }
3928
3929        // reader
3930        synchronized (mPackages) {
3931            final String pkgName = intent.getPackage();
3932            if (pkgName == null) {
3933                List<CrossProfileIntentFilter> matchingFilters =
3934                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3935                // Check for results that need to skip the current profile.
3936                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3937                        resolvedType, flags, userId);
3938                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
3939                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3940                    result.add(resolveInfo);
3941                    return filterIfNotPrimaryUser(result, userId);
3942                }
3943
3944                // Check for results in the current profile.
3945                List<ResolveInfo> result = mActivities.queryIntent(
3946                        intent, resolvedType, flags, userId);
3947
3948                // Check for cross profile results.
3949                resolveInfo = queryCrossProfileIntents(
3950                        matchingFilters, intent, resolvedType, flags, userId);
3951                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
3952                    result.add(resolveInfo);
3953                    Collections.sort(result, mResolvePrioritySorter);
3954                }
3955                result = filterIfNotPrimaryUser(result, userId);
3956                if (result.size() > 1 && hasWebURI(intent)) {
3957                    return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result);
3958                }
3959                return result;
3960            }
3961            final PackageParser.Package pkg = mPackages.get(pkgName);
3962            if (pkg != null) {
3963                return filterIfNotPrimaryUser(
3964                        mActivities.queryIntentForPackage(
3965                                intent, resolvedType, flags, pkg.activities, userId),
3966                        userId);
3967            }
3968            return new ArrayList<ResolveInfo>();
3969        }
3970    }
3971
3972    private boolean isUserEnabled(int userId) {
3973        long callingId = Binder.clearCallingIdentity();
3974        try {
3975            UserInfo userInfo = sUserManager.getUserInfo(userId);
3976            return userInfo != null && userInfo.isEnabled();
3977        } finally {
3978            Binder.restoreCallingIdentity(callingId);
3979        }
3980    }
3981
3982    /**
3983     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
3984     *
3985     * @return filtered list
3986     */
3987    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
3988        if (userId == UserHandle.USER_OWNER) {
3989            return resolveInfos;
3990        }
3991        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
3992            ResolveInfo info = resolveInfos.get(i);
3993            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
3994                resolveInfos.remove(i);
3995            }
3996        }
3997        return resolveInfos;
3998    }
3999
4000    private static boolean hasWebURI(Intent intent) {
4001        if (intent.getData() == null) {
4002            return false;
4003        }
4004        final String scheme = intent.getScheme();
4005        if (TextUtils.isEmpty(scheme)) {
4006            return false;
4007        }
4008        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4009    }
4010
4011    private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr(
4012            int flags, List<ResolveInfo> candidates) {
4013        if (DEBUG_PREFERRED) {
4014            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4015                    candidates.size());
4016        }
4017
4018        final int userId = UserHandle.getCallingUserId();
4019        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4020        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4021        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4022        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4023
4024        synchronized (mPackages) {
4025            final int count = candidates.size();
4026            // First, try to use the domain prefered App
4027            for (int n=0; n<count; n++) {
4028                ResolveInfo info = candidates.get(n);
4029                String packageName = info.activityInfo.packageName;
4030                PackageSetting ps = mSettings.mPackages.get(packageName);
4031                if (ps != null) {
4032                    // Add to the special match all list (Browser use case)
4033                    if (info.handleAllWebDataURI) {
4034                        matchAllList.add(info);
4035                        continue;
4036                    }
4037                    // Try to get the status from User settings first
4038                    int status = getDomainVerificationStatusLPr(ps, userId);
4039                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4040                        result.add(info);
4041                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4042                        neverList.add(info);
4043                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4044                        undefinedList.add(info);
4045                    }
4046                }
4047            }
4048            // If there is nothing selected, add all candidates and remove the ones that the User
4049            // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and
4050            // also remove any Browser Apps ones.
4051            // If there is still none after this pass, add all undefined one and Browser Apps and
4052            // let the User decide with the Disambiguation dialog if there are several ones.
4053            if (result.size() == 0) {
4054                result.addAll(candidates);
4055            }
4056            result.removeAll(neverList);
4057            result.removeAll(matchAllList);
4058            if (result.size() == 0) {
4059                result.addAll(undefinedList);
4060                if ((flags & MATCH_ALL) != 0) {
4061                    result.addAll(matchAllList);
4062                } else {
4063                    // Try to add the Default Browser if we can
4064                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4065                            UserHandle.myUserId());
4066                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4067                        boolean defaultBrowserFound = false;
4068                        final int browserCount = matchAllList.size();
4069                        for (int n=0; n<browserCount; n++) {
4070                            ResolveInfo browser = matchAllList.get(n);
4071                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4072                                result.add(browser);
4073                                defaultBrowserFound = true;
4074                                break;
4075                            }
4076                        }
4077                        if (!defaultBrowserFound) {
4078                            result.addAll(matchAllList);
4079                        }
4080                    } else {
4081                        result.addAll(matchAllList);
4082                    }
4083                }
4084            }
4085        }
4086        if (DEBUG_PREFERRED) {
4087            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4088                    result.size());
4089        }
4090        return result;
4091    }
4092
4093    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4094        int status = ps.getDomainVerificationStatusForUser(userId);
4095        // if none available, get the master status
4096        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4097            if (ps.getIntentFilterVerificationInfo() != null) {
4098                status = ps.getIntentFilterVerificationInfo().getStatus();
4099            }
4100        }
4101        return status;
4102    }
4103
4104    private ResolveInfo querySkipCurrentProfileIntents(
4105            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4106            int flags, int sourceUserId) {
4107        if (matchingFilters != null) {
4108            int size = matchingFilters.size();
4109            for (int i = 0; i < size; i ++) {
4110                CrossProfileIntentFilter filter = matchingFilters.get(i);
4111                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4112                    // Checking if there are activities in the target user that can handle the
4113                    // intent.
4114                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4115                            flags, sourceUserId);
4116                    if (resolveInfo != null) {
4117                        return resolveInfo;
4118                    }
4119                }
4120            }
4121        }
4122        return null;
4123    }
4124
4125    // Return matching ResolveInfo if any for skip current profile intent filters.
4126    private ResolveInfo queryCrossProfileIntents(
4127            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4128            int flags, int sourceUserId) {
4129        if (matchingFilters != null) {
4130            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4131            // match the same intent. For performance reasons, it is better not to
4132            // run queryIntent twice for the same userId
4133            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4134            int size = matchingFilters.size();
4135            for (int i = 0; i < size; i++) {
4136                CrossProfileIntentFilter filter = matchingFilters.get(i);
4137                int targetUserId = filter.getTargetUserId();
4138                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4139                        && !alreadyTriedUserIds.get(targetUserId)) {
4140                    // Checking if there are activities in the target user that can handle the
4141                    // intent.
4142                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4143                            flags, sourceUserId);
4144                    if (resolveInfo != null) return resolveInfo;
4145                    alreadyTriedUserIds.put(targetUserId, true);
4146                }
4147            }
4148        }
4149        return null;
4150    }
4151
4152    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4153            String resolvedType, int flags, int sourceUserId) {
4154        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4155                resolvedType, flags, filter.getTargetUserId());
4156        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4157            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4158        }
4159        return null;
4160    }
4161
4162    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4163            int sourceUserId, int targetUserId) {
4164        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4165        String className;
4166        if (targetUserId == UserHandle.USER_OWNER) {
4167            className = FORWARD_INTENT_TO_USER_OWNER;
4168        } else {
4169            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4170        }
4171        ComponentName forwardingActivityComponentName = new ComponentName(
4172                mAndroidApplication.packageName, className);
4173        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4174                sourceUserId);
4175        if (targetUserId == UserHandle.USER_OWNER) {
4176            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4177            forwardingResolveInfo.noResourceId = true;
4178        }
4179        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4180        forwardingResolveInfo.priority = 0;
4181        forwardingResolveInfo.preferredOrder = 0;
4182        forwardingResolveInfo.match = 0;
4183        forwardingResolveInfo.isDefault = true;
4184        forwardingResolveInfo.filter = filter;
4185        forwardingResolveInfo.targetUserId = targetUserId;
4186        return forwardingResolveInfo;
4187    }
4188
4189    @Override
4190    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4191            Intent[] specifics, String[] specificTypes, Intent intent,
4192            String resolvedType, int flags, int userId) {
4193        if (!sUserManager.exists(userId)) return Collections.emptyList();
4194        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4195                false, "query intent activity options");
4196        final String resultsAction = intent.getAction();
4197
4198        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4199                | PackageManager.GET_RESOLVED_FILTER, userId);
4200
4201        if (DEBUG_INTENT_MATCHING) {
4202            Log.v(TAG, "Query " + intent + ": " + results);
4203        }
4204
4205        int specificsPos = 0;
4206        int N;
4207
4208        // todo: note that the algorithm used here is O(N^2).  This
4209        // isn't a problem in our current environment, but if we start running
4210        // into situations where we have more than 5 or 10 matches then this
4211        // should probably be changed to something smarter...
4212
4213        // First we go through and resolve each of the specific items
4214        // that were supplied, taking care of removing any corresponding
4215        // duplicate items in the generic resolve list.
4216        if (specifics != null) {
4217            for (int i=0; i<specifics.length; i++) {
4218                final Intent sintent = specifics[i];
4219                if (sintent == null) {
4220                    continue;
4221                }
4222
4223                if (DEBUG_INTENT_MATCHING) {
4224                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4225                }
4226
4227                String action = sintent.getAction();
4228                if (resultsAction != null && resultsAction.equals(action)) {
4229                    // If this action was explicitly requested, then don't
4230                    // remove things that have it.
4231                    action = null;
4232                }
4233
4234                ResolveInfo ri = null;
4235                ActivityInfo ai = null;
4236
4237                ComponentName comp = sintent.getComponent();
4238                if (comp == null) {
4239                    ri = resolveIntent(
4240                        sintent,
4241                        specificTypes != null ? specificTypes[i] : null,
4242                            flags, userId);
4243                    if (ri == null) {
4244                        continue;
4245                    }
4246                    if (ri == mResolveInfo) {
4247                        // ACK!  Must do something better with this.
4248                    }
4249                    ai = ri.activityInfo;
4250                    comp = new ComponentName(ai.applicationInfo.packageName,
4251                            ai.name);
4252                } else {
4253                    ai = getActivityInfo(comp, flags, userId);
4254                    if (ai == null) {
4255                        continue;
4256                    }
4257                }
4258
4259                // Look for any generic query activities that are duplicates
4260                // of this specific one, and remove them from the results.
4261                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4262                N = results.size();
4263                int j;
4264                for (j=specificsPos; j<N; j++) {
4265                    ResolveInfo sri = results.get(j);
4266                    if ((sri.activityInfo.name.equals(comp.getClassName())
4267                            && sri.activityInfo.applicationInfo.packageName.equals(
4268                                    comp.getPackageName()))
4269                        || (action != null && sri.filter.matchAction(action))) {
4270                        results.remove(j);
4271                        if (DEBUG_INTENT_MATCHING) Log.v(
4272                            TAG, "Removing duplicate item from " + j
4273                            + " due to specific " + specificsPos);
4274                        if (ri == null) {
4275                            ri = sri;
4276                        }
4277                        j--;
4278                        N--;
4279                    }
4280                }
4281
4282                // Add this specific item to its proper place.
4283                if (ri == null) {
4284                    ri = new ResolveInfo();
4285                    ri.activityInfo = ai;
4286                }
4287                results.add(specificsPos, ri);
4288                ri.specificIndex = i;
4289                specificsPos++;
4290            }
4291        }
4292
4293        // Now we go through the remaining generic results and remove any
4294        // duplicate actions that are found here.
4295        N = results.size();
4296        for (int i=specificsPos; i<N-1; i++) {
4297            final ResolveInfo rii = results.get(i);
4298            if (rii.filter == null) {
4299                continue;
4300            }
4301
4302            // Iterate over all of the actions of this result's intent
4303            // filter...  typically this should be just one.
4304            final Iterator<String> it = rii.filter.actionsIterator();
4305            if (it == null) {
4306                continue;
4307            }
4308            while (it.hasNext()) {
4309                final String action = it.next();
4310                if (resultsAction != null && resultsAction.equals(action)) {
4311                    // If this action was explicitly requested, then don't
4312                    // remove things that have it.
4313                    continue;
4314                }
4315                for (int j=i+1; j<N; j++) {
4316                    final ResolveInfo rij = results.get(j);
4317                    if (rij.filter != null && rij.filter.hasAction(action)) {
4318                        results.remove(j);
4319                        if (DEBUG_INTENT_MATCHING) Log.v(
4320                            TAG, "Removing duplicate item from " + j
4321                            + " due to action " + action + " at " + i);
4322                        j--;
4323                        N--;
4324                    }
4325                }
4326            }
4327
4328            // If the caller didn't request filter information, drop it now
4329            // so we don't have to marshall/unmarshall it.
4330            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4331                rii.filter = null;
4332            }
4333        }
4334
4335        // Filter out the caller activity if so requested.
4336        if (caller != null) {
4337            N = results.size();
4338            for (int i=0; i<N; i++) {
4339                ActivityInfo ainfo = results.get(i).activityInfo;
4340                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4341                        && caller.getClassName().equals(ainfo.name)) {
4342                    results.remove(i);
4343                    break;
4344                }
4345            }
4346        }
4347
4348        // If the caller didn't request filter information,
4349        // drop them now so we don't have to
4350        // marshall/unmarshall it.
4351        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4352            N = results.size();
4353            for (int i=0; i<N; i++) {
4354                results.get(i).filter = null;
4355            }
4356        }
4357
4358        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4359        return results;
4360    }
4361
4362    @Override
4363    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4364            int userId) {
4365        if (!sUserManager.exists(userId)) return Collections.emptyList();
4366        ComponentName comp = intent.getComponent();
4367        if (comp == null) {
4368            if (intent.getSelector() != null) {
4369                intent = intent.getSelector();
4370                comp = intent.getComponent();
4371            }
4372        }
4373        if (comp != null) {
4374            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4375            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4376            if (ai != null) {
4377                ResolveInfo ri = new ResolveInfo();
4378                ri.activityInfo = ai;
4379                list.add(ri);
4380            }
4381            return list;
4382        }
4383
4384        // reader
4385        synchronized (mPackages) {
4386            String pkgName = intent.getPackage();
4387            if (pkgName == null) {
4388                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4389            }
4390            final PackageParser.Package pkg = mPackages.get(pkgName);
4391            if (pkg != null) {
4392                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4393                        userId);
4394            }
4395            return null;
4396        }
4397    }
4398
4399    @Override
4400    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4401        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4402        if (!sUserManager.exists(userId)) return null;
4403        if (query != null) {
4404            if (query.size() >= 1) {
4405                // If there is more than one service with the same priority,
4406                // just arbitrarily pick the first one.
4407                return query.get(0);
4408            }
4409        }
4410        return null;
4411    }
4412
4413    @Override
4414    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4415            int userId) {
4416        if (!sUserManager.exists(userId)) return Collections.emptyList();
4417        ComponentName comp = intent.getComponent();
4418        if (comp == null) {
4419            if (intent.getSelector() != null) {
4420                intent = intent.getSelector();
4421                comp = intent.getComponent();
4422            }
4423        }
4424        if (comp != null) {
4425            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4426            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4427            if (si != null) {
4428                final ResolveInfo ri = new ResolveInfo();
4429                ri.serviceInfo = si;
4430                list.add(ri);
4431            }
4432            return list;
4433        }
4434
4435        // reader
4436        synchronized (mPackages) {
4437            String pkgName = intent.getPackage();
4438            if (pkgName == null) {
4439                return mServices.queryIntent(intent, resolvedType, flags, userId);
4440            }
4441            final PackageParser.Package pkg = mPackages.get(pkgName);
4442            if (pkg != null) {
4443                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4444                        userId);
4445            }
4446            return null;
4447        }
4448    }
4449
4450    @Override
4451    public List<ResolveInfo> queryIntentContentProviders(
4452            Intent intent, String resolvedType, int flags, int userId) {
4453        if (!sUserManager.exists(userId)) return Collections.emptyList();
4454        ComponentName comp = intent.getComponent();
4455        if (comp == null) {
4456            if (intent.getSelector() != null) {
4457                intent = intent.getSelector();
4458                comp = intent.getComponent();
4459            }
4460        }
4461        if (comp != null) {
4462            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4463            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4464            if (pi != null) {
4465                final ResolveInfo ri = new ResolveInfo();
4466                ri.providerInfo = pi;
4467                list.add(ri);
4468            }
4469            return list;
4470        }
4471
4472        // reader
4473        synchronized (mPackages) {
4474            String pkgName = intent.getPackage();
4475            if (pkgName == null) {
4476                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4477            }
4478            final PackageParser.Package pkg = mPackages.get(pkgName);
4479            if (pkg != null) {
4480                return mProviders.queryIntentForPackage(
4481                        intent, resolvedType, flags, pkg.providers, userId);
4482            }
4483            return null;
4484        }
4485    }
4486
4487    @Override
4488    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4489        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4490
4491        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4492
4493        // writer
4494        synchronized (mPackages) {
4495            ArrayList<PackageInfo> list;
4496            if (listUninstalled) {
4497                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4498                for (PackageSetting ps : mSettings.mPackages.values()) {
4499                    PackageInfo pi;
4500                    if (ps.pkg != null) {
4501                        pi = generatePackageInfo(ps.pkg, flags, userId);
4502                    } else {
4503                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4504                    }
4505                    if (pi != null) {
4506                        list.add(pi);
4507                    }
4508                }
4509            } else {
4510                list = new ArrayList<PackageInfo>(mPackages.size());
4511                for (PackageParser.Package p : mPackages.values()) {
4512                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4513                    if (pi != null) {
4514                        list.add(pi);
4515                    }
4516                }
4517            }
4518
4519            return new ParceledListSlice<PackageInfo>(list);
4520        }
4521    }
4522
4523    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4524            String[] permissions, boolean[] tmp, int flags, int userId) {
4525        int numMatch = 0;
4526        final PermissionsState permissionsState = ps.getPermissionsState();
4527        for (int i=0; i<permissions.length; i++) {
4528            final String permission = permissions[i];
4529            if (permissionsState.hasPermission(permission, userId)) {
4530                tmp[i] = true;
4531                numMatch++;
4532            } else {
4533                tmp[i] = false;
4534            }
4535        }
4536        if (numMatch == 0) {
4537            return;
4538        }
4539        PackageInfo pi;
4540        if (ps.pkg != null) {
4541            pi = generatePackageInfo(ps.pkg, flags, userId);
4542        } else {
4543            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4544        }
4545        // The above might return null in cases of uninstalled apps or install-state
4546        // skew across users/profiles.
4547        if (pi != null) {
4548            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4549                if (numMatch == permissions.length) {
4550                    pi.requestedPermissions = permissions;
4551                } else {
4552                    pi.requestedPermissions = new String[numMatch];
4553                    numMatch = 0;
4554                    for (int i=0; i<permissions.length; i++) {
4555                        if (tmp[i]) {
4556                            pi.requestedPermissions[numMatch] = permissions[i];
4557                            numMatch++;
4558                        }
4559                    }
4560                }
4561            }
4562            list.add(pi);
4563        }
4564    }
4565
4566    @Override
4567    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4568            String[] permissions, int flags, int userId) {
4569        if (!sUserManager.exists(userId)) return null;
4570        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4571
4572        // writer
4573        synchronized (mPackages) {
4574            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4575            boolean[] tmpBools = new boolean[permissions.length];
4576            if (listUninstalled) {
4577                for (PackageSetting ps : mSettings.mPackages.values()) {
4578                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4579                }
4580            } else {
4581                for (PackageParser.Package pkg : mPackages.values()) {
4582                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4583                    if (ps != null) {
4584                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4585                                userId);
4586                    }
4587                }
4588            }
4589
4590            return new ParceledListSlice<PackageInfo>(list);
4591        }
4592    }
4593
4594    @Override
4595    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4596        if (!sUserManager.exists(userId)) return null;
4597        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4598
4599        // writer
4600        synchronized (mPackages) {
4601            ArrayList<ApplicationInfo> list;
4602            if (listUninstalled) {
4603                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4604                for (PackageSetting ps : mSettings.mPackages.values()) {
4605                    ApplicationInfo ai;
4606                    if (ps.pkg != null) {
4607                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4608                                ps.readUserState(userId), userId);
4609                    } else {
4610                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4611                    }
4612                    if (ai != null) {
4613                        list.add(ai);
4614                    }
4615                }
4616            } else {
4617                list = new ArrayList<ApplicationInfo>(mPackages.size());
4618                for (PackageParser.Package p : mPackages.values()) {
4619                    if (p.mExtras != null) {
4620                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4621                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4622                        if (ai != null) {
4623                            list.add(ai);
4624                        }
4625                    }
4626                }
4627            }
4628
4629            return new ParceledListSlice<ApplicationInfo>(list);
4630        }
4631    }
4632
4633    public List<ApplicationInfo> getPersistentApplications(int flags) {
4634        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4635
4636        // reader
4637        synchronized (mPackages) {
4638            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4639            final int userId = UserHandle.getCallingUserId();
4640            while (i.hasNext()) {
4641                final PackageParser.Package p = i.next();
4642                if (p.applicationInfo != null
4643                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4644                        && (!mSafeMode || isSystemApp(p))) {
4645                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4646                    if (ps != null) {
4647                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4648                                ps.readUserState(userId), userId);
4649                        if (ai != null) {
4650                            finalList.add(ai);
4651                        }
4652                    }
4653                }
4654            }
4655        }
4656
4657        return finalList;
4658    }
4659
4660    @Override
4661    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4662        if (!sUserManager.exists(userId)) return null;
4663        // reader
4664        synchronized (mPackages) {
4665            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4666            PackageSetting ps = provider != null
4667                    ? mSettings.mPackages.get(provider.owner.packageName)
4668                    : null;
4669            return ps != null
4670                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4671                    && (!mSafeMode || (provider.info.applicationInfo.flags
4672                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4673                    ? PackageParser.generateProviderInfo(provider, flags,
4674                            ps.readUserState(userId), userId)
4675                    : null;
4676        }
4677    }
4678
4679    /**
4680     * @deprecated
4681     */
4682    @Deprecated
4683    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4684        // reader
4685        synchronized (mPackages) {
4686            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4687                    .entrySet().iterator();
4688            final int userId = UserHandle.getCallingUserId();
4689            while (i.hasNext()) {
4690                Map.Entry<String, PackageParser.Provider> entry = i.next();
4691                PackageParser.Provider p = entry.getValue();
4692                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4693
4694                if (ps != null && p.syncable
4695                        && (!mSafeMode || (p.info.applicationInfo.flags
4696                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4697                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4698                            ps.readUserState(userId), userId);
4699                    if (info != null) {
4700                        outNames.add(entry.getKey());
4701                        outInfo.add(info);
4702                    }
4703                }
4704            }
4705        }
4706    }
4707
4708    @Override
4709    public List<ProviderInfo> queryContentProviders(String processName,
4710            int uid, int flags) {
4711        ArrayList<ProviderInfo> finalList = null;
4712        // reader
4713        synchronized (mPackages) {
4714            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4715            final int userId = processName != null ?
4716                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4717            while (i.hasNext()) {
4718                final PackageParser.Provider p = i.next();
4719                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4720                if (ps != null && p.info.authority != null
4721                        && (processName == null
4722                                || (p.info.processName.equals(processName)
4723                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4724                        && mSettings.isEnabledLPr(p.info, flags, userId)
4725                        && (!mSafeMode
4726                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4727                    if (finalList == null) {
4728                        finalList = new ArrayList<ProviderInfo>(3);
4729                    }
4730                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4731                            ps.readUserState(userId), userId);
4732                    if (info != null) {
4733                        finalList.add(info);
4734                    }
4735                }
4736            }
4737        }
4738
4739        if (finalList != null) {
4740            Collections.sort(finalList, mProviderInitOrderSorter);
4741        }
4742
4743        return finalList;
4744    }
4745
4746    @Override
4747    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4748            int flags) {
4749        // reader
4750        synchronized (mPackages) {
4751            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4752            return PackageParser.generateInstrumentationInfo(i, flags);
4753        }
4754    }
4755
4756    @Override
4757    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4758            int flags) {
4759        ArrayList<InstrumentationInfo> finalList =
4760            new ArrayList<InstrumentationInfo>();
4761
4762        // reader
4763        synchronized (mPackages) {
4764            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4765            while (i.hasNext()) {
4766                final PackageParser.Instrumentation p = i.next();
4767                if (targetPackage == null
4768                        || targetPackage.equals(p.info.targetPackage)) {
4769                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4770                            flags);
4771                    if (ii != null) {
4772                        finalList.add(ii);
4773                    }
4774                }
4775            }
4776        }
4777
4778        return finalList;
4779    }
4780
4781    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4782        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4783        if (overlays == null) {
4784            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4785            return;
4786        }
4787        for (PackageParser.Package opkg : overlays.values()) {
4788            // Not much to do if idmap fails: we already logged the error
4789            // and we certainly don't want to abort installation of pkg simply
4790            // because an overlay didn't fit properly. For these reasons,
4791            // ignore the return value of createIdmapForPackagePairLI.
4792            createIdmapForPackagePairLI(pkg, opkg);
4793        }
4794    }
4795
4796    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4797            PackageParser.Package opkg) {
4798        if (!opkg.mTrustedOverlay) {
4799            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4800                    opkg.baseCodePath + ": overlay not trusted");
4801            return false;
4802        }
4803        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4804        if (overlaySet == null) {
4805            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4806                    opkg.baseCodePath + " but target package has no known overlays");
4807            return false;
4808        }
4809        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4810        // TODO: generate idmap for split APKs
4811        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4812            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4813                    + opkg.baseCodePath);
4814            return false;
4815        }
4816        PackageParser.Package[] overlayArray =
4817            overlaySet.values().toArray(new PackageParser.Package[0]);
4818        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4819            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4820                return p1.mOverlayPriority - p2.mOverlayPriority;
4821            }
4822        };
4823        Arrays.sort(overlayArray, cmp);
4824
4825        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4826        int i = 0;
4827        for (PackageParser.Package p : overlayArray) {
4828            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4829        }
4830        return true;
4831    }
4832
4833    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4834        final File[] files = dir.listFiles();
4835        if (ArrayUtils.isEmpty(files)) {
4836            Log.d(TAG, "No files in app dir " + dir);
4837            return;
4838        }
4839
4840        if (DEBUG_PACKAGE_SCANNING) {
4841            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4842                    + " flags=0x" + Integer.toHexString(parseFlags));
4843        }
4844
4845        for (File file : files) {
4846            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4847                    && !PackageInstallerService.isStageName(file.getName());
4848            if (!isPackage) {
4849                // Ignore entries which are not packages
4850                continue;
4851            }
4852            try {
4853                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4854                        scanFlags, currentTime, null);
4855            } catch (PackageManagerException e) {
4856                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4857
4858                // Delete invalid userdata apps
4859                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4860                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4861                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4862                    if (file.isDirectory()) {
4863                        mInstaller.rmPackageDir(file.getAbsolutePath());
4864                    } else {
4865                        file.delete();
4866                    }
4867                }
4868            }
4869        }
4870    }
4871
4872    private static File getSettingsProblemFile() {
4873        File dataDir = Environment.getDataDirectory();
4874        File systemDir = new File(dataDir, "system");
4875        File fname = new File(systemDir, "uiderrors.txt");
4876        return fname;
4877    }
4878
4879    static void reportSettingsProblem(int priority, String msg) {
4880        logCriticalInfo(priority, msg);
4881    }
4882
4883    static void logCriticalInfo(int priority, String msg) {
4884        Slog.println(priority, TAG, msg);
4885        EventLogTags.writePmCriticalInfo(msg);
4886        try {
4887            File fname = getSettingsProblemFile();
4888            FileOutputStream out = new FileOutputStream(fname, true);
4889            PrintWriter pw = new FastPrintWriter(out);
4890            SimpleDateFormat formatter = new SimpleDateFormat();
4891            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4892            pw.println(dateString + ": " + msg);
4893            pw.close();
4894            FileUtils.setPermissions(
4895                    fname.toString(),
4896                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4897                    -1, -1);
4898        } catch (java.io.IOException e) {
4899        }
4900    }
4901
4902    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4903            PackageParser.Package pkg, File srcFile, int parseFlags)
4904            throws PackageManagerException {
4905        if (ps != null
4906                && ps.codePath.equals(srcFile)
4907                && ps.timeStamp == srcFile.lastModified()
4908                && !isCompatSignatureUpdateNeeded(pkg)
4909                && !isRecoverSignatureUpdateNeeded(pkg)) {
4910            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4911            if (ps.signatures.mSignatures != null
4912                    && ps.signatures.mSignatures.length != 0
4913                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4914                // Optimization: reuse the existing cached certificates
4915                // if the package appears to be unchanged.
4916                pkg.mSignatures = ps.signatures.mSignatures;
4917                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4918                synchronized (mPackages) {
4919                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4920                }
4921                return;
4922            }
4923
4924            Slog.w(TAG, "PackageSetting for " + ps.name
4925                    + " is missing signatures.  Collecting certs again to recover them.");
4926        } else {
4927            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4928        }
4929
4930        try {
4931            pp.collectCertificates(pkg, parseFlags);
4932            pp.collectManifestDigest(pkg);
4933        } catch (PackageParserException e) {
4934            throw PackageManagerException.from(e);
4935        }
4936    }
4937
4938    /*
4939     *  Scan a package and return the newly parsed package.
4940     *  Returns null in case of errors and the error code is stored in mLastScanError
4941     */
4942    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4943            long currentTime, UserHandle user) throws PackageManagerException {
4944        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4945        parseFlags |= mDefParseFlags;
4946        PackageParser pp = new PackageParser();
4947        pp.setSeparateProcesses(mSeparateProcesses);
4948        pp.setOnlyCoreApps(mOnlyCore);
4949        pp.setDisplayMetrics(mMetrics);
4950
4951        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4952            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4953        }
4954
4955        final PackageParser.Package pkg;
4956        try {
4957            pkg = pp.parsePackage(scanFile, parseFlags);
4958        } catch (PackageParserException e) {
4959            throw PackageManagerException.from(e);
4960        }
4961
4962        PackageSetting ps = null;
4963        PackageSetting updatedPkg;
4964        // reader
4965        synchronized (mPackages) {
4966            // Look to see if we already know about this package.
4967            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4968            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4969                // This package has been renamed to its original name.  Let's
4970                // use that.
4971                ps = mSettings.peekPackageLPr(oldName);
4972            }
4973            // If there was no original package, see one for the real package name.
4974            if (ps == null) {
4975                ps = mSettings.peekPackageLPr(pkg.packageName);
4976            }
4977            // Check to see if this package could be hiding/updating a system
4978            // package.  Must look for it either under the original or real
4979            // package name depending on our state.
4980            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4981            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4982        }
4983        boolean updatedPkgBetter = false;
4984        // First check if this is a system package that may involve an update
4985        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4986            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
4987            // it needs to drop FLAG_PRIVILEGED.
4988            if (locationIsPrivileged(scanFile)) {
4989                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4990            } else {
4991                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4992            }
4993
4994            if (ps != null && !ps.codePath.equals(scanFile)) {
4995                // The path has changed from what was last scanned...  check the
4996                // version of the new path against what we have stored to determine
4997                // what to do.
4998                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4999                if (pkg.mVersionCode <= ps.versionCode) {
5000                    // The system package has been updated and the code path does not match
5001                    // Ignore entry. Skip it.
5002                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5003                            + " ignored: updated version " + ps.versionCode
5004                            + " better than this " + pkg.mVersionCode);
5005                    if (!updatedPkg.codePath.equals(scanFile)) {
5006                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5007                                + ps.name + " changing from " + updatedPkg.codePathString
5008                                + " to " + scanFile);
5009                        updatedPkg.codePath = scanFile;
5010                        updatedPkg.codePathString = scanFile.toString();
5011                        updatedPkg.resourcePath = scanFile;
5012                        updatedPkg.resourcePathString = scanFile.toString();
5013                    }
5014                    updatedPkg.pkg = pkg;
5015                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5016                } else {
5017                    // The current app on the system partition is better than
5018                    // what we have updated to on the data partition; switch
5019                    // back to the system partition version.
5020                    // At this point, its safely assumed that package installation for
5021                    // apps in system partition will go through. If not there won't be a working
5022                    // version of the app
5023                    // writer
5024                    synchronized (mPackages) {
5025                        // Just remove the loaded entries from package lists.
5026                        mPackages.remove(ps.name);
5027                    }
5028
5029                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5030                            + " reverting from " + ps.codePathString
5031                            + ": new version " + pkg.mVersionCode
5032                            + " better than installed " + ps.versionCode);
5033
5034                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5035                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
5036                            getAppDexInstructionSets(ps));
5037                    synchronized (mInstallLock) {
5038                        args.cleanUpResourcesLI();
5039                    }
5040                    synchronized (mPackages) {
5041                        mSettings.enableSystemPackageLPw(ps.name);
5042                    }
5043                    updatedPkgBetter = true;
5044                }
5045            }
5046        }
5047
5048        if (updatedPkg != null) {
5049            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5050            // initially
5051            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5052
5053            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5054            // flag set initially
5055            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5056                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5057            }
5058        }
5059
5060        // Verify certificates against what was last scanned
5061        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5062
5063        /*
5064         * A new system app appeared, but we already had a non-system one of the
5065         * same name installed earlier.
5066         */
5067        boolean shouldHideSystemApp = false;
5068        if (updatedPkg == null && ps != null
5069                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5070            /*
5071             * Check to make sure the signatures match first. If they don't,
5072             * wipe the installed application and its data.
5073             */
5074            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5075                    != PackageManager.SIGNATURE_MATCH) {
5076                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5077                        + " signatures don't match existing userdata copy; removing");
5078                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5079                ps = null;
5080            } else {
5081                /*
5082                 * If the newly-added system app is an older version than the
5083                 * already installed version, hide it. It will be scanned later
5084                 * and re-added like an update.
5085                 */
5086                if (pkg.mVersionCode <= ps.versionCode) {
5087                    shouldHideSystemApp = true;
5088                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5089                            + " but new version " + pkg.mVersionCode + " better than installed "
5090                            + ps.versionCode + "; hiding system");
5091                } else {
5092                    /*
5093                     * The newly found system app is a newer version that the
5094                     * one previously installed. Simply remove the
5095                     * already-installed application and replace it with our own
5096                     * while keeping the application data.
5097                     */
5098                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5099                            + " reverting from " + ps.codePathString + ": new version "
5100                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5101                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5102                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
5103                            getAppDexInstructionSets(ps));
5104                    synchronized (mInstallLock) {
5105                        args.cleanUpResourcesLI();
5106                    }
5107                }
5108            }
5109        }
5110
5111        // The apk is forward locked (not public) if its code and resources
5112        // are kept in different files. (except for app in either system or
5113        // vendor path).
5114        // TODO grab this value from PackageSettings
5115        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5116            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5117                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5118            }
5119        }
5120
5121        // TODO: extend to support forward-locked splits
5122        String resourcePath = null;
5123        String baseResourcePath = null;
5124        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5125            if (ps != null && ps.resourcePathString != null) {
5126                resourcePath = ps.resourcePathString;
5127                baseResourcePath = ps.resourcePathString;
5128            } else {
5129                // Should not happen at all. Just log an error.
5130                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5131            }
5132        } else {
5133            resourcePath = pkg.codePath;
5134            baseResourcePath = pkg.baseCodePath;
5135        }
5136
5137        // Set application objects path explicitly.
5138        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5139        pkg.applicationInfo.setCodePath(pkg.codePath);
5140        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5141        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5142        pkg.applicationInfo.setResourcePath(resourcePath);
5143        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5144        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5145
5146        // Note that we invoke the following method only if we are about to unpack an application
5147        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5148                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5149
5150        /*
5151         * If the system app should be overridden by a previously installed
5152         * data, hide the system app now and let the /data/app scan pick it up
5153         * again.
5154         */
5155        if (shouldHideSystemApp) {
5156            synchronized (mPackages) {
5157                /*
5158                 * We have to grant systems permissions before we hide, because
5159                 * grantPermissions will assume the package update is trying to
5160                 * expand its permissions.
5161                 */
5162                grantPermissionsLPw(pkg, true, pkg.packageName);
5163                mSettings.disableSystemPackageLPw(pkg.packageName);
5164            }
5165        }
5166
5167        return scannedPkg;
5168    }
5169
5170    private static String fixProcessName(String defProcessName,
5171            String processName, int uid) {
5172        if (processName == null) {
5173            return defProcessName;
5174        }
5175        return processName;
5176    }
5177
5178    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5179            throws PackageManagerException {
5180        if (pkgSetting.signatures.mSignatures != null) {
5181            // Already existing package. Make sure signatures match
5182            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5183                    == PackageManager.SIGNATURE_MATCH;
5184            if (!match) {
5185                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5186                        == PackageManager.SIGNATURE_MATCH;
5187            }
5188            if (!match) {
5189                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5190                        == PackageManager.SIGNATURE_MATCH;
5191            }
5192            if (!match) {
5193                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5194                        + pkg.packageName + " signatures do not match the "
5195                        + "previously installed version; ignoring!");
5196            }
5197        }
5198
5199        // Check for shared user signatures
5200        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5201            // Already existing package. Make sure signatures match
5202            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5203                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5204            if (!match) {
5205                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5206                        == PackageManager.SIGNATURE_MATCH;
5207            }
5208            if (!match) {
5209                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5210                        == PackageManager.SIGNATURE_MATCH;
5211            }
5212            if (!match) {
5213                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5214                        "Package " + pkg.packageName
5215                        + " has no signatures that match those in shared user "
5216                        + pkgSetting.sharedUser.name + "; ignoring!");
5217            }
5218        }
5219    }
5220
5221    /**
5222     * Enforces that only the system UID or root's UID can call a method exposed
5223     * via Binder.
5224     *
5225     * @param message used as message if SecurityException is thrown
5226     * @throws SecurityException if the caller is not system or root
5227     */
5228    private static final void enforceSystemOrRoot(String message) {
5229        final int uid = Binder.getCallingUid();
5230        if (uid != Process.SYSTEM_UID && uid != 0) {
5231            throw new SecurityException(message);
5232        }
5233    }
5234
5235    @Override
5236    public void performBootDexOpt() {
5237        enforceSystemOrRoot("Only the system can request dexopt be performed");
5238
5239        // Before everything else, see whether we need to fstrim.
5240        try {
5241            IMountService ms = PackageHelper.getMountService();
5242            if (ms != null) {
5243                final boolean isUpgrade = isUpgrade();
5244                boolean doTrim = isUpgrade;
5245                if (doTrim) {
5246                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5247                } else {
5248                    final long interval = android.provider.Settings.Global.getLong(
5249                            mContext.getContentResolver(),
5250                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5251                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5252                    if (interval > 0) {
5253                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5254                        if (timeSinceLast > interval) {
5255                            doTrim = true;
5256                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5257                                    + "; running immediately");
5258                        }
5259                    }
5260                }
5261                if (doTrim) {
5262                    if (!isFirstBoot()) {
5263                        try {
5264                            ActivityManagerNative.getDefault().showBootMessage(
5265                                    mContext.getResources().getString(
5266                                            R.string.android_upgrading_fstrim), true);
5267                        } catch (RemoteException e) {
5268                        }
5269                    }
5270                    ms.runMaintenance();
5271                }
5272            } else {
5273                Slog.e(TAG, "Mount service unavailable!");
5274            }
5275        } catch (RemoteException e) {
5276            // Can't happen; MountService is local
5277        }
5278
5279        final ArraySet<PackageParser.Package> pkgs;
5280        synchronized (mPackages) {
5281            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5282        }
5283
5284        if (pkgs != null) {
5285            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5286            // in case the device runs out of space.
5287            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5288            // Give priority to core apps.
5289            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5290                PackageParser.Package pkg = it.next();
5291                if (pkg.coreApp) {
5292                    if (DEBUG_DEXOPT) {
5293                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5294                    }
5295                    sortedPkgs.add(pkg);
5296                    it.remove();
5297                }
5298            }
5299            // Give priority to system apps that listen for pre boot complete.
5300            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5301            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5302            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5303                PackageParser.Package pkg = it.next();
5304                if (pkgNames.contains(pkg.packageName)) {
5305                    if (DEBUG_DEXOPT) {
5306                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5307                    }
5308                    sortedPkgs.add(pkg);
5309                    it.remove();
5310                }
5311            }
5312            // Give priority to system apps.
5313            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5314                PackageParser.Package pkg = it.next();
5315                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5316                    if (DEBUG_DEXOPT) {
5317                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5318                    }
5319                    sortedPkgs.add(pkg);
5320                    it.remove();
5321                }
5322            }
5323            // Give priority to updated system apps.
5324            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5325                PackageParser.Package pkg = it.next();
5326                if (pkg.isUpdatedSystemApp()) {
5327                    if (DEBUG_DEXOPT) {
5328                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5329                    }
5330                    sortedPkgs.add(pkg);
5331                    it.remove();
5332                }
5333            }
5334            // Give priority to apps that listen for boot complete.
5335            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5336            pkgNames = getPackageNamesForIntent(intent);
5337            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5338                PackageParser.Package pkg = it.next();
5339                if (pkgNames.contains(pkg.packageName)) {
5340                    if (DEBUG_DEXOPT) {
5341                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5342                    }
5343                    sortedPkgs.add(pkg);
5344                    it.remove();
5345                }
5346            }
5347            // Filter out packages that aren't recently used.
5348            filterRecentlyUsedApps(pkgs);
5349            // Add all remaining apps.
5350            for (PackageParser.Package pkg : pkgs) {
5351                if (DEBUG_DEXOPT) {
5352                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5353                }
5354                sortedPkgs.add(pkg);
5355            }
5356
5357            // If we want to be lazy, filter everything that wasn't recently used.
5358            if (mLazyDexOpt) {
5359                filterRecentlyUsedApps(sortedPkgs);
5360            }
5361
5362            int i = 0;
5363            int total = sortedPkgs.size();
5364            File dataDir = Environment.getDataDirectory();
5365            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5366            if (lowThreshold == 0) {
5367                throw new IllegalStateException("Invalid low memory threshold");
5368            }
5369            for (PackageParser.Package pkg : sortedPkgs) {
5370                long usableSpace = dataDir.getUsableSpace();
5371                if (usableSpace < lowThreshold) {
5372                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5373                    break;
5374                }
5375                performBootDexOpt(pkg, ++i, total);
5376            }
5377        }
5378    }
5379
5380    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5381        // Filter out packages that aren't recently used.
5382        //
5383        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5384        // should do a full dexopt.
5385        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5386            int total = pkgs.size();
5387            int skipped = 0;
5388            long now = System.currentTimeMillis();
5389            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5390                PackageParser.Package pkg = i.next();
5391                long then = pkg.mLastPackageUsageTimeInMills;
5392                if (then + mDexOptLRUThresholdInMills < now) {
5393                    if (DEBUG_DEXOPT) {
5394                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5395                              ((then == 0) ? "never" : new Date(then)));
5396                    }
5397                    i.remove();
5398                    skipped++;
5399                }
5400            }
5401            if (DEBUG_DEXOPT) {
5402                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5403            }
5404        }
5405    }
5406
5407    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5408        List<ResolveInfo> ris = null;
5409        try {
5410            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5411                    intent, null, 0, UserHandle.USER_OWNER);
5412        } catch (RemoteException e) {
5413        }
5414        ArraySet<String> pkgNames = new ArraySet<String>();
5415        if (ris != null) {
5416            for (ResolveInfo ri : ris) {
5417                pkgNames.add(ri.activityInfo.packageName);
5418            }
5419        }
5420        return pkgNames;
5421    }
5422
5423    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5424        if (DEBUG_DEXOPT) {
5425            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5426        }
5427        if (!isFirstBoot()) {
5428            try {
5429                ActivityManagerNative.getDefault().showBootMessage(
5430                        mContext.getResources().getString(R.string.android_upgrading_apk,
5431                                curr, total), true);
5432            } catch (RemoteException e) {
5433            }
5434        }
5435        PackageParser.Package p = pkg;
5436        synchronized (mInstallLock) {
5437            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5438                    false /* force dex */, false /* defer */, true /* include dependencies */);
5439        }
5440    }
5441
5442    @Override
5443    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5444        return performDexOpt(packageName, instructionSet, false);
5445    }
5446
5447    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5448        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5449        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5450        if (!dexopt && !updateUsage) {
5451            // We aren't going to dexopt or update usage, so bail early.
5452            return false;
5453        }
5454        PackageParser.Package p;
5455        final String targetInstructionSet;
5456        synchronized (mPackages) {
5457            p = mPackages.get(packageName);
5458            if (p == null) {
5459                return false;
5460            }
5461            if (updateUsage) {
5462                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5463            }
5464            mPackageUsage.write(false);
5465            if (!dexopt) {
5466                // We aren't going to dexopt, so bail early.
5467                return false;
5468            }
5469
5470            targetInstructionSet = instructionSet != null ? instructionSet :
5471                    getPrimaryInstructionSet(p.applicationInfo);
5472            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5473                return false;
5474            }
5475        }
5476
5477        synchronized (mInstallLock) {
5478            final String[] instructionSets = new String[] { targetInstructionSet };
5479            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5480                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5481            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5482        }
5483    }
5484
5485    public ArraySet<String> getPackagesThatNeedDexOpt() {
5486        ArraySet<String> pkgs = null;
5487        synchronized (mPackages) {
5488            for (PackageParser.Package p : mPackages.values()) {
5489                if (DEBUG_DEXOPT) {
5490                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5491                }
5492                if (!p.mDexOptPerformed.isEmpty()) {
5493                    continue;
5494                }
5495                if (pkgs == null) {
5496                    pkgs = new ArraySet<String>();
5497                }
5498                pkgs.add(p.packageName);
5499            }
5500        }
5501        return pkgs;
5502    }
5503
5504    public void shutdown() {
5505        mPackageUsage.write(true);
5506    }
5507
5508    @Override
5509    public void forceDexOpt(String packageName) {
5510        enforceSystemOrRoot("forceDexOpt");
5511
5512        PackageParser.Package pkg;
5513        synchronized (mPackages) {
5514            pkg = mPackages.get(packageName);
5515            if (pkg == null) {
5516                throw new IllegalArgumentException("Missing package: " + packageName);
5517            }
5518        }
5519
5520        synchronized (mInstallLock) {
5521            final String[] instructionSets = new String[] {
5522                    getPrimaryInstructionSet(pkg.applicationInfo) };
5523            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5524                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5525            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5526                throw new IllegalStateException("Failed to dexopt: " + res);
5527            }
5528        }
5529    }
5530
5531    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5532        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5533            Slog.w(TAG, "Unable to update from " + oldPkg.name
5534                    + " to " + newPkg.packageName
5535                    + ": old package not in system partition");
5536            return false;
5537        } else if (mPackages.get(oldPkg.name) != null) {
5538            Slog.w(TAG, "Unable to update from " + oldPkg.name
5539                    + " to " + newPkg.packageName
5540                    + ": old package still exists");
5541            return false;
5542        }
5543        return true;
5544    }
5545
5546    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5547        int[] users = sUserManager.getUserIds();
5548        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5549        if (res < 0) {
5550            return res;
5551        }
5552        for (int user : users) {
5553            if (user != 0) {
5554                res = mInstaller.createUserData(volumeUuid, packageName,
5555                        UserHandle.getUid(user, uid), user, seinfo);
5556                if (res < 0) {
5557                    return res;
5558                }
5559            }
5560        }
5561        return res;
5562    }
5563
5564    private int removeDataDirsLI(String volumeUuid, String packageName) {
5565        int[] users = sUserManager.getUserIds();
5566        int res = 0;
5567        for (int user : users) {
5568            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5569            if (resInner < 0) {
5570                res = resInner;
5571            }
5572        }
5573
5574        return res;
5575    }
5576
5577    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5578        int[] users = sUserManager.getUserIds();
5579        int res = 0;
5580        for (int user : users) {
5581            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5582            if (resInner < 0) {
5583                res = resInner;
5584            }
5585        }
5586        return res;
5587    }
5588
5589    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5590            PackageParser.Package changingLib) {
5591        if (file.path != null) {
5592            usesLibraryFiles.add(file.path);
5593            return;
5594        }
5595        PackageParser.Package p = mPackages.get(file.apk);
5596        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5597            // If we are doing this while in the middle of updating a library apk,
5598            // then we need to make sure to use that new apk for determining the
5599            // dependencies here.  (We haven't yet finished committing the new apk
5600            // to the package manager state.)
5601            if (p == null || p.packageName.equals(changingLib.packageName)) {
5602                p = changingLib;
5603            }
5604        }
5605        if (p != null) {
5606            usesLibraryFiles.addAll(p.getAllCodePaths());
5607        }
5608    }
5609
5610    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5611            PackageParser.Package changingLib) throws PackageManagerException {
5612        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5613            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5614            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5615            for (int i=0; i<N; i++) {
5616                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5617                if (file == null) {
5618                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5619                            "Package " + pkg.packageName + " requires unavailable shared library "
5620                            + pkg.usesLibraries.get(i) + "; failing!");
5621                }
5622                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5623            }
5624            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5625            for (int i=0; i<N; i++) {
5626                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5627                if (file == null) {
5628                    Slog.w(TAG, "Package " + pkg.packageName
5629                            + " desires unavailable shared library "
5630                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5631                } else {
5632                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5633                }
5634            }
5635            N = usesLibraryFiles.size();
5636            if (N > 0) {
5637                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5638            } else {
5639                pkg.usesLibraryFiles = null;
5640            }
5641        }
5642    }
5643
5644    private static boolean hasString(List<String> list, List<String> which) {
5645        if (list == null) {
5646            return false;
5647        }
5648        for (int i=list.size()-1; i>=0; i--) {
5649            for (int j=which.size()-1; j>=0; j--) {
5650                if (which.get(j).equals(list.get(i))) {
5651                    return true;
5652                }
5653            }
5654        }
5655        return false;
5656    }
5657
5658    private void updateAllSharedLibrariesLPw() {
5659        for (PackageParser.Package pkg : mPackages.values()) {
5660            try {
5661                updateSharedLibrariesLPw(pkg, null);
5662            } catch (PackageManagerException e) {
5663                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5664            }
5665        }
5666    }
5667
5668    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5669            PackageParser.Package changingPkg) {
5670        ArrayList<PackageParser.Package> res = null;
5671        for (PackageParser.Package pkg : mPackages.values()) {
5672            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5673                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5674                if (res == null) {
5675                    res = new ArrayList<PackageParser.Package>();
5676                }
5677                res.add(pkg);
5678                try {
5679                    updateSharedLibrariesLPw(pkg, changingPkg);
5680                } catch (PackageManagerException e) {
5681                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5682                }
5683            }
5684        }
5685        return res;
5686    }
5687
5688    /**
5689     * Derive the value of the {@code cpuAbiOverride} based on the provided
5690     * value and an optional stored value from the package settings.
5691     */
5692    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5693        String cpuAbiOverride = null;
5694
5695        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5696            cpuAbiOverride = null;
5697        } else if (abiOverride != null) {
5698            cpuAbiOverride = abiOverride;
5699        } else if (settings != null) {
5700            cpuAbiOverride = settings.cpuAbiOverrideString;
5701        }
5702
5703        return cpuAbiOverride;
5704    }
5705
5706    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5707            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5708        boolean success = false;
5709        try {
5710            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5711                    currentTime, user);
5712            success = true;
5713            return res;
5714        } finally {
5715            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5716                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
5717            }
5718        }
5719    }
5720
5721    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5722            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5723        final File scanFile = new File(pkg.codePath);
5724        if (pkg.applicationInfo.getCodePath() == null ||
5725                pkg.applicationInfo.getResourcePath() == null) {
5726            // Bail out. The resource and code paths haven't been set.
5727            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5728                    "Code and resource paths haven't been set correctly");
5729        }
5730
5731        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5732            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5733        } else {
5734            // Only allow system apps to be flagged as core apps.
5735            pkg.coreApp = false;
5736        }
5737
5738        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5739            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5740        }
5741
5742        if (mCustomResolverComponentName != null &&
5743                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5744            setUpCustomResolverActivity(pkg);
5745        }
5746
5747        if (pkg.packageName.equals("android")) {
5748            synchronized (mPackages) {
5749                if (mAndroidApplication != null) {
5750                    Slog.w(TAG, "*************************************************");
5751                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5752                    Slog.w(TAG, " file=" + scanFile);
5753                    Slog.w(TAG, "*************************************************");
5754                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5755                            "Core android package being redefined.  Skipping.");
5756                }
5757
5758                // Set up information for our fall-back user intent resolution activity.
5759                mPlatformPackage = pkg;
5760                pkg.mVersionCode = mSdkVersion;
5761                mAndroidApplication = pkg.applicationInfo;
5762
5763                if (!mResolverReplaced) {
5764                    mResolveActivity.applicationInfo = mAndroidApplication;
5765                    mResolveActivity.name = ResolverActivity.class.getName();
5766                    mResolveActivity.packageName = mAndroidApplication.packageName;
5767                    mResolveActivity.processName = "system:ui";
5768                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5769                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5770                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5771                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5772                    mResolveActivity.exported = true;
5773                    mResolveActivity.enabled = true;
5774                    mResolveInfo.activityInfo = mResolveActivity;
5775                    mResolveInfo.priority = 0;
5776                    mResolveInfo.preferredOrder = 0;
5777                    mResolveInfo.match = 0;
5778                    mResolveComponentName = new ComponentName(
5779                            mAndroidApplication.packageName, mResolveActivity.name);
5780                }
5781            }
5782        }
5783
5784        if (DEBUG_PACKAGE_SCANNING) {
5785            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5786                Log.d(TAG, "Scanning package " + pkg.packageName);
5787        }
5788
5789        if (mPackages.containsKey(pkg.packageName)
5790                || mSharedLibraries.containsKey(pkg.packageName)) {
5791            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5792                    "Application package " + pkg.packageName
5793                    + " already installed.  Skipping duplicate.");
5794        }
5795
5796        // If we're only installing presumed-existing packages, require that the
5797        // scanned APK is both already known and at the path previously established
5798        // for it.  Previously unknown packages we pick up normally, but if we have an
5799        // a priori expectation about this package's install presence, enforce it.
5800        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
5801            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
5802            if (known != null) {
5803                if (DEBUG_PACKAGE_SCANNING) {
5804                    Log.d(TAG, "Examining " + pkg.codePath
5805                            + " and requiring known paths " + known.codePathString
5806                            + " & " + known.resourcePathString);
5807                }
5808                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
5809                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
5810                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
5811                            "Application package " + pkg.packageName
5812                            + " found at " + pkg.applicationInfo.getCodePath()
5813                            + " but expected at " + known.codePathString + "; ignoring.");
5814                }
5815            }
5816        }
5817
5818        // Initialize package source and resource directories
5819        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5820        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5821
5822        SharedUserSetting suid = null;
5823        PackageSetting pkgSetting = null;
5824
5825        if (!isSystemApp(pkg)) {
5826            // Only system apps can use these features.
5827            pkg.mOriginalPackages = null;
5828            pkg.mRealPackage = null;
5829            pkg.mAdoptPermissions = null;
5830        }
5831
5832        // writer
5833        synchronized (mPackages) {
5834            if (pkg.mSharedUserId != null) {
5835                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5836                if (suid == null) {
5837                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5838                            "Creating application package " + pkg.packageName
5839                            + " for shared user failed");
5840                }
5841                if (DEBUG_PACKAGE_SCANNING) {
5842                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5843                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5844                                + "): packages=" + suid.packages);
5845                }
5846            }
5847
5848            // Check if we are renaming from an original package name.
5849            PackageSetting origPackage = null;
5850            String realName = null;
5851            if (pkg.mOriginalPackages != null) {
5852                // This package may need to be renamed to a previously
5853                // installed name.  Let's check on that...
5854                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5855                if (pkg.mOriginalPackages.contains(renamed)) {
5856                    // This package had originally been installed as the
5857                    // original name, and we have already taken care of
5858                    // transitioning to the new one.  Just update the new
5859                    // one to continue using the old name.
5860                    realName = pkg.mRealPackage;
5861                    if (!pkg.packageName.equals(renamed)) {
5862                        // Callers into this function may have already taken
5863                        // care of renaming the package; only do it here if
5864                        // it is not already done.
5865                        pkg.setPackageName(renamed);
5866                    }
5867
5868                } else {
5869                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5870                        if ((origPackage = mSettings.peekPackageLPr(
5871                                pkg.mOriginalPackages.get(i))) != null) {
5872                            // We do have the package already installed under its
5873                            // original name...  should we use it?
5874                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5875                                // New package is not compatible with original.
5876                                origPackage = null;
5877                                continue;
5878                            } else if (origPackage.sharedUser != null) {
5879                                // Make sure uid is compatible between packages.
5880                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5881                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5882                                            + " to " + pkg.packageName + ": old uid "
5883                                            + origPackage.sharedUser.name
5884                                            + " differs from " + pkg.mSharedUserId);
5885                                    origPackage = null;
5886                                    continue;
5887                                }
5888                            } else {
5889                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5890                                        + pkg.packageName + " to old name " + origPackage.name);
5891                            }
5892                            break;
5893                        }
5894                    }
5895                }
5896            }
5897
5898            if (mTransferedPackages.contains(pkg.packageName)) {
5899                Slog.w(TAG, "Package " + pkg.packageName
5900                        + " was transferred to another, but its .apk remains");
5901            }
5902
5903            // Just create the setting, don't add it yet. For already existing packages
5904            // the PkgSetting exists already and doesn't have to be created.
5905            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5906                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5907                    pkg.applicationInfo.primaryCpuAbi,
5908                    pkg.applicationInfo.secondaryCpuAbi,
5909                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
5910                    user, false);
5911            if (pkgSetting == null) {
5912                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5913                        "Creating application package " + pkg.packageName + " failed");
5914            }
5915
5916            if (pkgSetting.origPackage != null) {
5917                // If we are first transitioning from an original package,
5918                // fix up the new package's name now.  We need to do this after
5919                // looking up the package under its new name, so getPackageLP
5920                // can take care of fiddling things correctly.
5921                pkg.setPackageName(origPackage.name);
5922
5923                // File a report about this.
5924                String msg = "New package " + pkgSetting.realName
5925                        + " renamed to replace old package " + pkgSetting.name;
5926                reportSettingsProblem(Log.WARN, msg);
5927
5928                // Make a note of it.
5929                mTransferedPackages.add(origPackage.name);
5930
5931                // No longer need to retain this.
5932                pkgSetting.origPackage = null;
5933            }
5934
5935            if (realName != null) {
5936                // Make a note of it.
5937                mTransferedPackages.add(pkg.packageName);
5938            }
5939
5940            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5941                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5942            }
5943
5944            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5945                // Check all shared libraries and map to their actual file path.
5946                // We only do this here for apps not on a system dir, because those
5947                // are the only ones that can fail an install due to this.  We
5948                // will take care of the system apps by updating all of their
5949                // library paths after the scan is done.
5950                updateSharedLibrariesLPw(pkg, null);
5951            }
5952
5953            if (mFoundPolicyFile) {
5954                SELinuxMMAC.assignSeinfoValue(pkg);
5955            }
5956
5957            pkg.applicationInfo.uid = pkgSetting.appId;
5958            pkg.mExtras = pkgSetting;
5959            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5960                try {
5961                    verifySignaturesLP(pkgSetting, pkg);
5962                    // We just determined the app is signed correctly, so bring
5963                    // over the latest parsed certs.
5964                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5965                } catch (PackageManagerException e) {
5966                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5967                        throw e;
5968                    }
5969                    // The signature has changed, but this package is in the system
5970                    // image...  let's recover!
5971                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5972                    // However...  if this package is part of a shared user, but it
5973                    // doesn't match the signature of the shared user, let's fail.
5974                    // What this means is that you can't change the signatures
5975                    // associated with an overall shared user, which doesn't seem all
5976                    // that unreasonable.
5977                    if (pkgSetting.sharedUser != null) {
5978                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5979                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5980                            throw new PackageManagerException(
5981                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5982                                            "Signature mismatch for shared user : "
5983                                            + pkgSetting.sharedUser);
5984                        }
5985                    }
5986                    // File a report about this.
5987                    String msg = "System package " + pkg.packageName
5988                        + " signature changed; retaining data.";
5989                    reportSettingsProblem(Log.WARN, msg);
5990                }
5991            } else {
5992                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5993                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5994                            + pkg.packageName + " upgrade keys do not match the "
5995                            + "previously installed version");
5996                } else {
5997                    // We just determined the app is signed correctly, so bring
5998                    // over the latest parsed certs.
5999                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6000                }
6001            }
6002            // Verify that this new package doesn't have any content providers
6003            // that conflict with existing packages.  Only do this if the
6004            // package isn't already installed, since we don't want to break
6005            // things that are installed.
6006            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6007                final int N = pkg.providers.size();
6008                int i;
6009                for (i=0; i<N; i++) {
6010                    PackageParser.Provider p = pkg.providers.get(i);
6011                    if (p.info.authority != null) {
6012                        String names[] = p.info.authority.split(";");
6013                        for (int j = 0; j < names.length; j++) {
6014                            if (mProvidersByAuthority.containsKey(names[j])) {
6015                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6016                                final String otherPackageName =
6017                                        ((other != null && other.getComponentName() != null) ?
6018                                                other.getComponentName().getPackageName() : "?");
6019                                throw new PackageManagerException(
6020                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6021                                                "Can't install because provider name " + names[j]
6022                                                + " (in package " + pkg.applicationInfo.packageName
6023                                                + ") is already used by " + otherPackageName);
6024                            }
6025                        }
6026                    }
6027                }
6028            }
6029
6030            if (pkg.mAdoptPermissions != null) {
6031                // This package wants to adopt ownership of permissions from
6032                // another package.
6033                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6034                    final String origName = pkg.mAdoptPermissions.get(i);
6035                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6036                    if (orig != null) {
6037                        if (verifyPackageUpdateLPr(orig, pkg)) {
6038                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6039                                    + pkg.packageName);
6040                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6041                        }
6042                    }
6043                }
6044            }
6045        }
6046
6047        final String pkgName = pkg.packageName;
6048
6049        final long scanFileTime = scanFile.lastModified();
6050        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6051        pkg.applicationInfo.processName = fixProcessName(
6052                pkg.applicationInfo.packageName,
6053                pkg.applicationInfo.processName,
6054                pkg.applicationInfo.uid);
6055
6056        File dataPath;
6057        if (mPlatformPackage == pkg) {
6058            // The system package is special.
6059            dataPath = new File(Environment.getDataDirectory(), "system");
6060
6061            pkg.applicationInfo.dataDir = dataPath.getPath();
6062
6063        } else {
6064            // This is a normal package, need to make its data directory.
6065            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6066                    UserHandle.USER_OWNER);
6067
6068            boolean uidError = false;
6069            if (dataPath.exists()) {
6070                int currentUid = 0;
6071                try {
6072                    StructStat stat = Os.stat(dataPath.getPath());
6073                    currentUid = stat.st_uid;
6074                } catch (ErrnoException e) {
6075                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6076                }
6077
6078                // If we have mismatched owners for the data path, we have a problem.
6079                if (currentUid != pkg.applicationInfo.uid) {
6080                    boolean recovered = false;
6081                    if (currentUid == 0) {
6082                        // The directory somehow became owned by root.  Wow.
6083                        // This is probably because the system was stopped while
6084                        // installd was in the middle of messing with its libs
6085                        // directory.  Ask installd to fix that.
6086                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6087                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6088                        if (ret >= 0) {
6089                            recovered = true;
6090                            String msg = "Package " + pkg.packageName
6091                                    + " unexpectedly changed to uid 0; recovered to " +
6092                                    + pkg.applicationInfo.uid;
6093                            reportSettingsProblem(Log.WARN, msg);
6094                        }
6095                    }
6096                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6097                            || (scanFlags&SCAN_BOOTING) != 0)) {
6098                        // If this is a system app, we can at least delete its
6099                        // current data so the application will still work.
6100                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6101                        if (ret >= 0) {
6102                            // TODO: Kill the processes first
6103                            // Old data gone!
6104                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6105                                    ? "System package " : "Third party package ";
6106                            String msg = prefix + pkg.packageName
6107                                    + " has changed from uid: "
6108                                    + currentUid + " to "
6109                                    + pkg.applicationInfo.uid + "; old data erased";
6110                            reportSettingsProblem(Log.WARN, msg);
6111                            recovered = true;
6112
6113                            // And now re-install the app.
6114                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6115                                    pkg.applicationInfo.seinfo);
6116                            if (ret == -1) {
6117                                // Ack should not happen!
6118                                msg = prefix + pkg.packageName
6119                                        + " could not have data directory re-created after delete.";
6120                                reportSettingsProblem(Log.WARN, msg);
6121                                throw new PackageManagerException(
6122                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6123                            }
6124                        }
6125                        if (!recovered) {
6126                            mHasSystemUidErrors = true;
6127                        }
6128                    } else if (!recovered) {
6129                        // If we allow this install to proceed, we will be broken.
6130                        // Abort, abort!
6131                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6132                                "scanPackageLI");
6133                    }
6134                    if (!recovered) {
6135                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6136                            + pkg.applicationInfo.uid + "/fs_"
6137                            + currentUid;
6138                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6139                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6140                        String msg = "Package " + pkg.packageName
6141                                + " has mismatched uid: "
6142                                + currentUid + " on disk, "
6143                                + pkg.applicationInfo.uid + " in settings";
6144                        // writer
6145                        synchronized (mPackages) {
6146                            mSettings.mReadMessages.append(msg);
6147                            mSettings.mReadMessages.append('\n');
6148                            uidError = true;
6149                            if (!pkgSetting.uidError) {
6150                                reportSettingsProblem(Log.ERROR, msg);
6151                            }
6152                        }
6153                    }
6154                }
6155                pkg.applicationInfo.dataDir = dataPath.getPath();
6156                if (mShouldRestoreconData) {
6157                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6158                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6159                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6160                }
6161            } else {
6162                if (DEBUG_PACKAGE_SCANNING) {
6163                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6164                        Log.v(TAG, "Want this data dir: " + dataPath);
6165                }
6166                //invoke installer to do the actual installation
6167                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6168                        pkg.applicationInfo.seinfo);
6169                if (ret < 0) {
6170                    // Error from installer
6171                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6172                            "Unable to create data dirs [errorCode=" + ret + "]");
6173                }
6174
6175                if (dataPath.exists()) {
6176                    pkg.applicationInfo.dataDir = dataPath.getPath();
6177                } else {
6178                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6179                    pkg.applicationInfo.dataDir = null;
6180                }
6181            }
6182
6183            pkgSetting.uidError = uidError;
6184        }
6185
6186        final String path = scanFile.getPath();
6187        final String codePath = pkg.applicationInfo.getCodePath();
6188        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6189        if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6190            setBundledAppAbisAndRoots(pkg, pkgSetting);
6191
6192            // If we haven't found any native libraries for the app, check if it has
6193            // renderscript code. We'll need to force the app to 32 bit if it has
6194            // renderscript bitcode.
6195            if (pkg.applicationInfo.primaryCpuAbi == null
6196                    && pkg.applicationInfo.secondaryCpuAbi == null
6197                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
6198                NativeLibraryHelper.Handle handle = null;
6199                try {
6200                    handle = NativeLibraryHelper.Handle.create(scanFile);
6201                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6202                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6203                    }
6204                } catch (IOException ioe) {
6205                    Slog.w(TAG, "Error scanning system app : " + ioe);
6206                } finally {
6207                    IoUtils.closeQuietly(handle);
6208                }
6209            }
6210
6211            setNativeLibraryPaths(pkg);
6212        } else {
6213            // TODO: We can probably be smarter about this stuff. For installed apps,
6214            // we can calculate this information at install time once and for all. For
6215            // system apps, we can probably assume that this information doesn't change
6216            // after the first boot scan. As things stand, we do lots of unnecessary work.
6217
6218            // Give ourselves some initial paths; we'll come back for another
6219            // pass once we've determined ABI below.
6220            setNativeLibraryPaths(pkg);
6221
6222            final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg);
6223            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6224            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6225
6226            NativeLibraryHelper.Handle handle = null;
6227            try {
6228                handle = NativeLibraryHelper.Handle.create(scanFile);
6229                // TODO(multiArch): This can be null for apps that didn't go through the
6230                // usual installation process. We can calculate it again, like we
6231                // do during install time.
6232                //
6233                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6234                // unnecessary.
6235                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6236
6237                // Null out the abis so that they can be recalculated.
6238                pkg.applicationInfo.primaryCpuAbi = null;
6239                pkg.applicationInfo.secondaryCpuAbi = null;
6240                if (isMultiArch(pkg.applicationInfo)) {
6241                    // Warn if we've set an abiOverride for multi-lib packages..
6242                    // By definition, we need to copy both 32 and 64 bit libraries for
6243                    // such packages.
6244                    if (pkg.cpuAbiOverride != null
6245                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
6246                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
6247                    }
6248
6249                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
6250                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
6251                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
6252                        if (isAsec) {
6253                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
6254                        } else {
6255                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6256                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
6257                                    useIsaSpecificSubdirs);
6258                        }
6259                    }
6260
6261                    maybeThrowExceptionForMultiArchCopy(
6262                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
6263
6264                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
6265                        if (isAsec) {
6266                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
6267                        } else {
6268                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6269                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
6270                                    useIsaSpecificSubdirs);
6271                        }
6272                    }
6273
6274                    maybeThrowExceptionForMultiArchCopy(
6275                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
6276
6277                    if (abi64 >= 0) {
6278                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
6279                    }
6280
6281                    if (abi32 >= 0) {
6282                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
6283                        if (abi64 >= 0) {
6284                            pkg.applicationInfo.secondaryCpuAbi = abi;
6285                        } else {
6286                            pkg.applicationInfo.primaryCpuAbi = abi;
6287                        }
6288                    }
6289                } else {
6290                    String[] abiList = (cpuAbiOverride != null) ?
6291                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
6292
6293                    // Enable gross and lame hacks for apps that are built with old
6294                    // SDK tools. We must scan their APKs for renderscript bitcode and
6295                    // not launch them if it's present. Don't bother checking on devices
6296                    // that don't have 64 bit support.
6297                    boolean needsRenderScriptOverride = false;
6298                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
6299                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6300                        abiList = Build.SUPPORTED_32_BIT_ABIS;
6301                        needsRenderScriptOverride = true;
6302                    }
6303
6304                    final int copyRet;
6305                    if (isAsec) {
6306                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6307                    } else {
6308                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6309                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
6310                    }
6311
6312                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
6313                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6314                                "Error unpackaging native libs for app, errorCode=" + copyRet);
6315                    }
6316
6317                    if (copyRet >= 0) {
6318                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
6319                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
6320                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
6321                    } else if (needsRenderScriptOverride) {
6322                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
6323                    }
6324                }
6325            } catch (IOException ioe) {
6326                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
6327            } finally {
6328                IoUtils.closeQuietly(handle);
6329            }
6330
6331            // Now that we've calculated the ABIs and determined if it's an internal app,
6332            // we will go ahead and populate the nativeLibraryPath.
6333            setNativeLibraryPaths(pkg);
6334
6335            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6336            final int[] userIds = sUserManager.getUserIds();
6337            synchronized (mInstallLock) {
6338                // Create a native library symlink only if we have native libraries
6339                // and if the native libraries are 32 bit libraries. We do not provide
6340                // this symlink for 64 bit libraries.
6341                if (pkg.applicationInfo.primaryCpuAbi != null &&
6342                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6343                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6344                    for (int userId : userIds) {
6345                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6346                                nativeLibPath, userId) < 0) {
6347                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6348                                    "Failed linking native library dir (user=" + userId + ")");
6349                        }
6350                    }
6351                }
6352            }
6353        }
6354
6355        // This is a special case for the "system" package, where the ABI is
6356        // dictated by the zygote configuration (and init.rc). We should keep track
6357        // of this ABI so that we can deal with "normal" applications that run under
6358        // the same UID correctly.
6359        if (mPlatformPackage == pkg) {
6360            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6361                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6362        }
6363
6364        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6365        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6366        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6367        // Copy the derived override back to the parsed package, so that we can
6368        // update the package settings accordingly.
6369        pkg.cpuAbiOverride = cpuAbiOverride;
6370
6371        if (DEBUG_ABI_SELECTION) {
6372            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6373                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6374                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6375        }
6376
6377        // Push the derived path down into PackageSettings so we know what to
6378        // clean up at uninstall time.
6379        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6380
6381        if (DEBUG_ABI_SELECTION) {
6382            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6383                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6384                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6385        }
6386
6387        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6388            // We don't do this here during boot because we can do it all
6389            // at once after scanning all existing packages.
6390            //
6391            // We also do this *before* we perform dexopt on this package, so that
6392            // we can avoid redundant dexopts, and also to make sure we've got the
6393            // code and package path correct.
6394            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6395                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6396        }
6397
6398        if ((scanFlags & SCAN_NO_DEX) == 0) {
6399            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6400                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6401            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6402                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6403            }
6404        }
6405        if (mFactoryTest && pkg.requestedPermissions.contains(
6406                android.Manifest.permission.FACTORY_TEST)) {
6407            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6408        }
6409
6410        ArrayList<PackageParser.Package> clientLibPkgs = null;
6411
6412        // writer
6413        synchronized (mPackages) {
6414            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6415                // Only system apps can add new shared libraries.
6416                if (pkg.libraryNames != null) {
6417                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6418                        String name = pkg.libraryNames.get(i);
6419                        boolean allowed = false;
6420                        if (pkg.isUpdatedSystemApp()) {
6421                            // New library entries can only be added through the
6422                            // system image.  This is important to get rid of a lot
6423                            // of nasty edge cases: for example if we allowed a non-
6424                            // system update of the app to add a library, then uninstalling
6425                            // the update would make the library go away, and assumptions
6426                            // we made such as through app install filtering would now
6427                            // have allowed apps on the device which aren't compatible
6428                            // with it.  Better to just have the restriction here, be
6429                            // conservative, and create many fewer cases that can negatively
6430                            // impact the user experience.
6431                            final PackageSetting sysPs = mSettings
6432                                    .getDisabledSystemPkgLPr(pkg.packageName);
6433                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6434                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6435                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6436                                        allowed = true;
6437                                        allowed = true;
6438                                        break;
6439                                    }
6440                                }
6441                            }
6442                        } else {
6443                            allowed = true;
6444                        }
6445                        if (allowed) {
6446                            if (!mSharedLibraries.containsKey(name)) {
6447                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6448                            } else if (!name.equals(pkg.packageName)) {
6449                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6450                                        + name + " already exists; skipping");
6451                            }
6452                        } else {
6453                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6454                                    + name + " that is not declared on system image; skipping");
6455                        }
6456                    }
6457                    if ((scanFlags&SCAN_BOOTING) == 0) {
6458                        // If we are not booting, we need to update any applications
6459                        // that are clients of our shared library.  If we are booting,
6460                        // this will all be done once the scan is complete.
6461                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6462                    }
6463                }
6464            }
6465        }
6466
6467        // We also need to dexopt any apps that are dependent on this library.  Note that
6468        // if these fail, we should abort the install since installing the library will
6469        // result in some apps being broken.
6470        if (clientLibPkgs != null) {
6471            if ((scanFlags & SCAN_NO_DEX) == 0) {
6472                for (int i = 0; i < clientLibPkgs.size(); i++) {
6473                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6474                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6475                            null /* instruction sets */, forceDex,
6476                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6477                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6478                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6479                                "scanPackageLI failed to dexopt clientLibPkgs");
6480                    }
6481                }
6482            }
6483        }
6484
6485        // Request the ActivityManager to kill the process(only for existing packages)
6486        // so that we do not end up in a confused state while the user is still using the older
6487        // version of the application while the new one gets installed.
6488        if ((scanFlags & SCAN_REPLACING) != 0) {
6489            killApplication(pkg.applicationInfo.packageName,
6490                        pkg.applicationInfo.uid, "update pkg");
6491        }
6492
6493        // Also need to kill any apps that are dependent on the library.
6494        if (clientLibPkgs != null) {
6495            for (int i=0; i<clientLibPkgs.size(); i++) {
6496                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6497                killApplication(clientPkg.applicationInfo.packageName,
6498                        clientPkg.applicationInfo.uid, "update lib");
6499            }
6500        }
6501
6502        // writer
6503        synchronized (mPackages) {
6504            // We don't expect installation to fail beyond this point
6505
6506            // Add the new setting to mSettings
6507            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6508            // Add the new setting to mPackages
6509            mPackages.put(pkg.applicationInfo.packageName, pkg);
6510            // Make sure we don't accidentally delete its data.
6511            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6512            while (iter.hasNext()) {
6513                PackageCleanItem item = iter.next();
6514                if (pkgName.equals(item.packageName)) {
6515                    iter.remove();
6516                }
6517            }
6518
6519            // Take care of first install / last update times.
6520            if (currentTime != 0) {
6521                if (pkgSetting.firstInstallTime == 0) {
6522                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6523                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6524                    pkgSetting.lastUpdateTime = currentTime;
6525                }
6526            } else if (pkgSetting.firstInstallTime == 0) {
6527                // We need *something*.  Take time time stamp of the file.
6528                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6529            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6530                if (scanFileTime != pkgSetting.timeStamp) {
6531                    // A package on the system image has changed; consider this
6532                    // to be an update.
6533                    pkgSetting.lastUpdateTime = scanFileTime;
6534                }
6535            }
6536
6537            // Add the package's KeySets to the global KeySetManagerService
6538            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6539            try {
6540                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6541                if (pkg.mKeySetMapping != null) {
6542                    ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping);
6543                    if (pkg.mUpgradeKeySets != null) {
6544                        ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets);
6545                    }
6546                }
6547            } catch (NullPointerException e) {
6548                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6549            } catch (IllegalArgumentException e) {
6550                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6551            }
6552
6553            int N = pkg.providers.size();
6554            StringBuilder r = null;
6555            int i;
6556            for (i=0; i<N; i++) {
6557                PackageParser.Provider p = pkg.providers.get(i);
6558                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6559                        p.info.processName, pkg.applicationInfo.uid);
6560                mProviders.addProvider(p);
6561                p.syncable = p.info.isSyncable;
6562                if (p.info.authority != null) {
6563                    String names[] = p.info.authority.split(";");
6564                    p.info.authority = null;
6565                    for (int j = 0; j < names.length; j++) {
6566                        if (j == 1 && p.syncable) {
6567                            // We only want the first authority for a provider to possibly be
6568                            // syncable, so if we already added this provider using a different
6569                            // authority clear the syncable flag. We copy the provider before
6570                            // changing it because the mProviders object contains a reference
6571                            // to a provider that we don't want to change.
6572                            // Only do this for the second authority since the resulting provider
6573                            // object can be the same for all future authorities for this provider.
6574                            p = new PackageParser.Provider(p);
6575                            p.syncable = false;
6576                        }
6577                        if (!mProvidersByAuthority.containsKey(names[j])) {
6578                            mProvidersByAuthority.put(names[j], p);
6579                            if (p.info.authority == null) {
6580                                p.info.authority = names[j];
6581                            } else {
6582                                p.info.authority = p.info.authority + ";" + names[j];
6583                            }
6584                            if (DEBUG_PACKAGE_SCANNING) {
6585                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6586                                    Log.d(TAG, "Registered content provider: " + names[j]
6587                                            + ", className = " + p.info.name + ", isSyncable = "
6588                                            + p.info.isSyncable);
6589                            }
6590                        } else {
6591                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6592                            Slog.w(TAG, "Skipping provider name " + names[j] +
6593                                    " (in package " + pkg.applicationInfo.packageName +
6594                                    "): name already used by "
6595                                    + ((other != null && other.getComponentName() != null)
6596                                            ? other.getComponentName().getPackageName() : "?"));
6597                        }
6598                    }
6599                }
6600                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6601                    if (r == null) {
6602                        r = new StringBuilder(256);
6603                    } else {
6604                        r.append(' ');
6605                    }
6606                    r.append(p.info.name);
6607                }
6608            }
6609            if (r != null) {
6610                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6611            }
6612
6613            N = pkg.services.size();
6614            r = null;
6615            for (i=0; i<N; i++) {
6616                PackageParser.Service s = pkg.services.get(i);
6617                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6618                        s.info.processName, pkg.applicationInfo.uid);
6619                mServices.addService(s);
6620                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6621                    if (r == null) {
6622                        r = new StringBuilder(256);
6623                    } else {
6624                        r.append(' ');
6625                    }
6626                    r.append(s.info.name);
6627                }
6628            }
6629            if (r != null) {
6630                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6631            }
6632
6633            N = pkg.receivers.size();
6634            r = null;
6635            for (i=0; i<N; i++) {
6636                PackageParser.Activity a = pkg.receivers.get(i);
6637                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6638                        a.info.processName, pkg.applicationInfo.uid);
6639                mReceivers.addActivity(a, "receiver");
6640                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6641                    if (r == null) {
6642                        r = new StringBuilder(256);
6643                    } else {
6644                        r.append(' ');
6645                    }
6646                    r.append(a.info.name);
6647                }
6648            }
6649            if (r != null) {
6650                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6651            }
6652
6653            N = pkg.activities.size();
6654            r = null;
6655            for (i=0; i<N; i++) {
6656                PackageParser.Activity a = pkg.activities.get(i);
6657                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6658                        a.info.processName, pkg.applicationInfo.uid);
6659                mActivities.addActivity(a, "activity");
6660                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6661                    if (r == null) {
6662                        r = new StringBuilder(256);
6663                    } else {
6664                        r.append(' ');
6665                    }
6666                    r.append(a.info.name);
6667                }
6668            }
6669            if (r != null) {
6670                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6671            }
6672
6673            N = pkg.permissionGroups.size();
6674            r = null;
6675            for (i=0; i<N; i++) {
6676                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6677                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6678                if (cur == null) {
6679                    mPermissionGroups.put(pg.info.name, pg);
6680                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6681                        if (r == null) {
6682                            r = new StringBuilder(256);
6683                        } else {
6684                            r.append(' ');
6685                        }
6686                        r.append(pg.info.name);
6687                    }
6688                } else {
6689                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6690                            + pg.info.packageName + " ignored: original from "
6691                            + cur.info.packageName);
6692                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6693                        if (r == null) {
6694                            r = new StringBuilder(256);
6695                        } else {
6696                            r.append(' ');
6697                        }
6698                        r.append("DUP:");
6699                        r.append(pg.info.name);
6700                    }
6701                }
6702            }
6703            if (r != null) {
6704                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6705            }
6706
6707            N = pkg.permissions.size();
6708            r = null;
6709            for (i=0; i<N; i++) {
6710                PackageParser.Permission p = pkg.permissions.get(i);
6711
6712                // Now that permission groups have a special meaning, we ignore permission
6713                // groups for legacy apps to prevent unexpected behavior. In particular,
6714                // permissions for one app being granted to someone just becuase they happen
6715                // to be in a group defined by another app (before this had no implications).
6716                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6717                    p.group = mPermissionGroups.get(p.info.group);
6718                    // Warn for a permission in an unknown group.
6719                    if (p.info.group != null && p.group == null) {
6720                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6721                                + p.info.packageName + " in an unknown group " + p.info.group);
6722                    }
6723                }
6724
6725                ArrayMap<String, BasePermission> permissionMap =
6726                        p.tree ? mSettings.mPermissionTrees
6727                                : mSettings.mPermissions;
6728                BasePermission bp = permissionMap.get(p.info.name);
6729
6730                // Allow system apps to redefine non-system permissions
6731                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6732                    final boolean currentOwnerIsSystem = (bp.perm != null
6733                            && isSystemApp(bp.perm.owner));
6734                    if (isSystemApp(p.owner)) {
6735                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6736                            // It's a built-in permission and no owner, take ownership now
6737                            bp.packageSetting = pkgSetting;
6738                            bp.perm = p;
6739                            bp.uid = pkg.applicationInfo.uid;
6740                            bp.sourcePackage = p.info.packageName;
6741                        } else if (!currentOwnerIsSystem) {
6742                            String msg = "New decl " + p.owner + " of permission  "
6743                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6744                            reportSettingsProblem(Log.WARN, msg);
6745                            bp = null;
6746                        }
6747                    }
6748                }
6749
6750                if (bp == null) {
6751                    bp = new BasePermission(p.info.name, p.info.packageName,
6752                            BasePermission.TYPE_NORMAL);
6753                    permissionMap.put(p.info.name, bp);
6754                }
6755
6756                if (bp.perm == null) {
6757                    if (bp.sourcePackage == null
6758                            || bp.sourcePackage.equals(p.info.packageName)) {
6759                        BasePermission tree = findPermissionTreeLP(p.info.name);
6760                        if (tree == null
6761                                || tree.sourcePackage.equals(p.info.packageName)) {
6762                            bp.packageSetting = pkgSetting;
6763                            bp.perm = p;
6764                            bp.uid = pkg.applicationInfo.uid;
6765                            bp.sourcePackage = p.info.packageName;
6766                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6767                                if (r == null) {
6768                                    r = new StringBuilder(256);
6769                                } else {
6770                                    r.append(' ');
6771                                }
6772                                r.append(p.info.name);
6773                            }
6774                        } else {
6775                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6776                                    + p.info.packageName + " ignored: base tree "
6777                                    + tree.name + " is from package "
6778                                    + tree.sourcePackage);
6779                        }
6780                    } else {
6781                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6782                                + p.info.packageName + " ignored: original from "
6783                                + bp.sourcePackage);
6784                    }
6785                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6786                    if (r == null) {
6787                        r = new StringBuilder(256);
6788                    } else {
6789                        r.append(' ');
6790                    }
6791                    r.append("DUP:");
6792                    r.append(p.info.name);
6793                }
6794                if (bp.perm == p) {
6795                    bp.protectionLevel = p.info.protectionLevel;
6796                }
6797            }
6798
6799            if (r != null) {
6800                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6801            }
6802
6803            N = pkg.instrumentation.size();
6804            r = null;
6805            for (i=0; i<N; i++) {
6806                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6807                a.info.packageName = pkg.applicationInfo.packageName;
6808                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6809                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6810                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6811                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6812                a.info.dataDir = pkg.applicationInfo.dataDir;
6813
6814                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6815                // need other information about the application, like the ABI and what not ?
6816                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6817                mInstrumentation.put(a.getComponentName(), a);
6818                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6819                    if (r == null) {
6820                        r = new StringBuilder(256);
6821                    } else {
6822                        r.append(' ');
6823                    }
6824                    r.append(a.info.name);
6825                }
6826            }
6827            if (r != null) {
6828                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6829            }
6830
6831            if (pkg.protectedBroadcasts != null) {
6832                N = pkg.protectedBroadcasts.size();
6833                for (i=0; i<N; i++) {
6834                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6835                }
6836            }
6837
6838            pkgSetting.setTimeStamp(scanFileTime);
6839
6840            // Create idmap files for pairs of (packages, overlay packages).
6841            // Note: "android", ie framework-res.apk, is handled by native layers.
6842            if (pkg.mOverlayTarget != null) {
6843                // This is an overlay package.
6844                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6845                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6846                        mOverlays.put(pkg.mOverlayTarget,
6847                                new ArrayMap<String, PackageParser.Package>());
6848                    }
6849                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6850                    map.put(pkg.packageName, pkg);
6851                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6852                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6853                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6854                                "scanPackageLI failed to createIdmap");
6855                    }
6856                }
6857            } else if (mOverlays.containsKey(pkg.packageName) &&
6858                    !pkg.packageName.equals("android")) {
6859                // This is a regular package, with one or more known overlay packages.
6860                createIdmapsForPackageLI(pkg);
6861            }
6862        }
6863
6864        return pkg;
6865    }
6866
6867    /**
6868     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6869     * i.e, so that all packages can be run inside a single process if required.
6870     *
6871     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6872     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6873     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6874     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6875     * updating a package that belongs to a shared user.
6876     *
6877     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6878     * adds unnecessary complexity.
6879     */
6880    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6881            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6882        String requiredInstructionSet = null;
6883        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6884            requiredInstructionSet = VMRuntime.getInstructionSet(
6885                     scannedPackage.applicationInfo.primaryCpuAbi);
6886        }
6887
6888        PackageSetting requirer = null;
6889        for (PackageSetting ps : packagesForUser) {
6890            // If packagesForUser contains scannedPackage, we skip it. This will happen
6891            // when scannedPackage is an update of an existing package. Without this check,
6892            // we will never be able to change the ABI of any package belonging to a shared
6893            // user, even if it's compatible with other packages.
6894            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6895                if (ps.primaryCpuAbiString == null) {
6896                    continue;
6897                }
6898
6899                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6900                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6901                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6902                    // this but there's not much we can do.
6903                    String errorMessage = "Instruction set mismatch, "
6904                            + ((requirer == null) ? "[caller]" : requirer)
6905                            + " requires " + requiredInstructionSet + " whereas " + ps
6906                            + " requires " + instructionSet;
6907                    Slog.w(TAG, errorMessage);
6908                }
6909
6910                if (requiredInstructionSet == null) {
6911                    requiredInstructionSet = instructionSet;
6912                    requirer = ps;
6913                }
6914            }
6915        }
6916
6917        if (requiredInstructionSet != null) {
6918            String adjustedAbi;
6919            if (requirer != null) {
6920                // requirer != null implies that either scannedPackage was null or that scannedPackage
6921                // did not require an ABI, in which case we have to adjust scannedPackage to match
6922                // the ABI of the set (which is the same as requirer's ABI)
6923                adjustedAbi = requirer.primaryCpuAbiString;
6924                if (scannedPackage != null) {
6925                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6926                }
6927            } else {
6928                // requirer == null implies that we're updating all ABIs in the set to
6929                // match scannedPackage.
6930                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6931            }
6932
6933            for (PackageSetting ps : packagesForUser) {
6934                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6935                    if (ps.primaryCpuAbiString != null) {
6936                        continue;
6937                    }
6938
6939                    ps.primaryCpuAbiString = adjustedAbi;
6940                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6941                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6942                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6943
6944                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
6945                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
6946                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6947                            ps.primaryCpuAbiString = null;
6948                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6949                            return;
6950                        } else {
6951                            mInstaller.rmdex(ps.codePathString,
6952                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
6953                        }
6954                    }
6955                }
6956            }
6957        }
6958    }
6959
6960    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6961        synchronized (mPackages) {
6962            mResolverReplaced = true;
6963            // Set up information for custom user intent resolution activity.
6964            mResolveActivity.applicationInfo = pkg.applicationInfo;
6965            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6966            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6967            mResolveActivity.processName = pkg.applicationInfo.packageName;
6968            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6969            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6970                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6971            mResolveActivity.theme = 0;
6972            mResolveActivity.exported = true;
6973            mResolveActivity.enabled = true;
6974            mResolveInfo.activityInfo = mResolveActivity;
6975            mResolveInfo.priority = 0;
6976            mResolveInfo.preferredOrder = 0;
6977            mResolveInfo.match = 0;
6978            mResolveComponentName = mCustomResolverComponentName;
6979            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6980                    mResolveComponentName);
6981        }
6982    }
6983
6984    private static String calculateBundledApkRoot(final String codePathString) {
6985        final File codePath = new File(codePathString);
6986        final File codeRoot;
6987        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6988            codeRoot = Environment.getRootDirectory();
6989        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6990            codeRoot = Environment.getOemDirectory();
6991        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6992            codeRoot = Environment.getVendorDirectory();
6993        } else {
6994            // Unrecognized code path; take its top real segment as the apk root:
6995            // e.g. /something/app/blah.apk => /something
6996            try {
6997                File f = codePath.getCanonicalFile();
6998                File parent = f.getParentFile();    // non-null because codePath is a file
6999                File tmp;
7000                while ((tmp = parent.getParentFile()) != null) {
7001                    f = parent;
7002                    parent = tmp;
7003                }
7004                codeRoot = f;
7005                Slog.w(TAG, "Unrecognized code path "
7006                        + codePath + " - using " + codeRoot);
7007            } catch (IOException e) {
7008                // Can't canonicalize the code path -- shenanigans?
7009                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7010                return Environment.getRootDirectory().getPath();
7011            }
7012        }
7013        return codeRoot.getPath();
7014    }
7015
7016    /**
7017     * Derive and set the location of native libraries for the given package,
7018     * which varies depending on where and how the package was installed.
7019     */
7020    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7021        final ApplicationInfo info = pkg.applicationInfo;
7022        final String codePath = pkg.codePath;
7023        final File codeFile = new File(codePath);
7024        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7025        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7026
7027        info.nativeLibraryRootDir = null;
7028        info.nativeLibraryRootRequiresIsa = false;
7029        info.nativeLibraryDir = null;
7030        info.secondaryNativeLibraryDir = null;
7031
7032        if (isApkFile(codeFile)) {
7033            // Monolithic install
7034            if (bundledApp) {
7035                // If "/system/lib64/apkname" exists, assume that is the per-package
7036                // native library directory to use; otherwise use "/system/lib/apkname".
7037                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7038                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7039                        getPrimaryInstructionSet(info));
7040
7041                // This is a bundled system app so choose the path based on the ABI.
7042                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7043                // is just the default path.
7044                final String apkName = deriveCodePathName(codePath);
7045                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7046                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7047                        apkName).getAbsolutePath();
7048
7049                if (info.secondaryCpuAbi != null) {
7050                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7051                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7052                            secondaryLibDir, apkName).getAbsolutePath();
7053                }
7054            } else if (asecApp) {
7055                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7056                        .getAbsolutePath();
7057            } else {
7058                final String apkName = deriveCodePathName(codePath);
7059                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7060                        .getAbsolutePath();
7061            }
7062
7063            info.nativeLibraryRootRequiresIsa = false;
7064            info.nativeLibraryDir = info.nativeLibraryRootDir;
7065        } else {
7066            // Cluster install
7067            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7068            info.nativeLibraryRootRequiresIsa = true;
7069
7070            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7071                    getPrimaryInstructionSet(info)).getAbsolutePath();
7072
7073            if (info.secondaryCpuAbi != null) {
7074                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7075                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7076            }
7077        }
7078    }
7079
7080    /**
7081     * Calculate the abis and roots for a bundled app. These can uniquely
7082     * be determined from the contents of the system partition, i.e whether
7083     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7084     * of this information, and instead assume that the system was built
7085     * sensibly.
7086     */
7087    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7088                                           PackageSetting pkgSetting) {
7089        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7090
7091        // If "/system/lib64/apkname" exists, assume that is the per-package
7092        // native library directory to use; otherwise use "/system/lib/apkname".
7093        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7094        setBundledAppAbi(pkg, apkRoot, apkName);
7095        // pkgSetting might be null during rescan following uninstall of updates
7096        // to a bundled app, so accommodate that possibility.  The settings in
7097        // that case will be established later from the parsed package.
7098        //
7099        // If the settings aren't null, sync them up with what we've just derived.
7100        // note that apkRoot isn't stored in the package settings.
7101        if (pkgSetting != null) {
7102            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7103            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7104        }
7105    }
7106
7107    /**
7108     * Deduces the ABI of a bundled app and sets the relevant fields on the
7109     * parsed pkg object.
7110     *
7111     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7112     *        under which system libraries are installed.
7113     * @param apkName the name of the installed package.
7114     */
7115    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7116        final File codeFile = new File(pkg.codePath);
7117
7118        final boolean has64BitLibs;
7119        final boolean has32BitLibs;
7120        if (isApkFile(codeFile)) {
7121            // Monolithic install
7122            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7123            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7124        } else {
7125            // Cluster install
7126            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7127            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7128                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7129                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7130                has64BitLibs = (new File(rootDir, isa)).exists();
7131            } else {
7132                has64BitLibs = false;
7133            }
7134            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7135                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7136                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7137                has32BitLibs = (new File(rootDir, isa)).exists();
7138            } else {
7139                has32BitLibs = false;
7140            }
7141        }
7142
7143        if (has64BitLibs && !has32BitLibs) {
7144            // The package has 64 bit libs, but not 32 bit libs. Its primary
7145            // ABI should be 64 bit. We can safely assume here that the bundled
7146            // native libraries correspond to the most preferred ABI in the list.
7147
7148            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7149            pkg.applicationInfo.secondaryCpuAbi = null;
7150        } else if (has32BitLibs && !has64BitLibs) {
7151            // The package has 32 bit libs but not 64 bit libs. Its primary
7152            // ABI should be 32 bit.
7153
7154            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7155            pkg.applicationInfo.secondaryCpuAbi = null;
7156        } else if (has32BitLibs && has64BitLibs) {
7157            // The application has both 64 and 32 bit bundled libraries. We check
7158            // here that the app declares multiArch support, and warn if it doesn't.
7159            //
7160            // We will be lenient here and record both ABIs. The primary will be the
7161            // ABI that's higher on the list, i.e, a device that's configured to prefer
7162            // 64 bit apps will see a 64 bit primary ABI,
7163
7164            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7165                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7166            }
7167
7168            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7169                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7170                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7171            } else {
7172                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7173                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7174            }
7175        } else {
7176            pkg.applicationInfo.primaryCpuAbi = null;
7177            pkg.applicationInfo.secondaryCpuAbi = null;
7178        }
7179    }
7180
7181    private void killApplication(String pkgName, int appId, String reason) {
7182        // Request the ActivityManager to kill the process(only for existing packages)
7183        // so that we do not end up in a confused state while the user is still using the older
7184        // version of the application while the new one gets installed.
7185        IActivityManager am = ActivityManagerNative.getDefault();
7186        if (am != null) {
7187            try {
7188                am.killApplicationWithAppId(pkgName, appId, reason);
7189            } catch (RemoteException e) {
7190            }
7191        }
7192    }
7193
7194    void removePackageLI(PackageSetting ps, boolean chatty) {
7195        if (DEBUG_INSTALL) {
7196            if (chatty)
7197                Log.d(TAG, "Removing package " + ps.name);
7198        }
7199
7200        // writer
7201        synchronized (mPackages) {
7202            mPackages.remove(ps.name);
7203            final PackageParser.Package pkg = ps.pkg;
7204            if (pkg != null) {
7205                cleanPackageDataStructuresLILPw(pkg, chatty);
7206            }
7207        }
7208    }
7209
7210    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7211        if (DEBUG_INSTALL) {
7212            if (chatty)
7213                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7214        }
7215
7216        // writer
7217        synchronized (mPackages) {
7218            mPackages.remove(pkg.applicationInfo.packageName);
7219            cleanPackageDataStructuresLILPw(pkg, chatty);
7220        }
7221    }
7222
7223    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7224        int N = pkg.providers.size();
7225        StringBuilder r = null;
7226        int i;
7227        for (i=0; i<N; i++) {
7228            PackageParser.Provider p = pkg.providers.get(i);
7229            mProviders.removeProvider(p);
7230            if (p.info.authority == null) {
7231
7232                /* There was another ContentProvider with this authority when
7233                 * this app was installed so this authority is null,
7234                 * Ignore it as we don't have to unregister the provider.
7235                 */
7236                continue;
7237            }
7238            String names[] = p.info.authority.split(";");
7239            for (int j = 0; j < names.length; j++) {
7240                if (mProvidersByAuthority.get(names[j]) == p) {
7241                    mProvidersByAuthority.remove(names[j]);
7242                    if (DEBUG_REMOVE) {
7243                        if (chatty)
7244                            Log.d(TAG, "Unregistered content provider: " + names[j]
7245                                    + ", className = " + p.info.name + ", isSyncable = "
7246                                    + p.info.isSyncable);
7247                    }
7248                }
7249            }
7250            if (DEBUG_REMOVE && chatty) {
7251                if (r == null) {
7252                    r = new StringBuilder(256);
7253                } else {
7254                    r.append(' ');
7255                }
7256                r.append(p.info.name);
7257            }
7258        }
7259        if (r != null) {
7260            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7261        }
7262
7263        N = pkg.services.size();
7264        r = null;
7265        for (i=0; i<N; i++) {
7266            PackageParser.Service s = pkg.services.get(i);
7267            mServices.removeService(s);
7268            if (chatty) {
7269                if (r == null) {
7270                    r = new StringBuilder(256);
7271                } else {
7272                    r.append(' ');
7273                }
7274                r.append(s.info.name);
7275            }
7276        }
7277        if (r != null) {
7278            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7279        }
7280
7281        N = pkg.receivers.size();
7282        r = null;
7283        for (i=0; i<N; i++) {
7284            PackageParser.Activity a = pkg.receivers.get(i);
7285            mReceivers.removeActivity(a, "receiver");
7286            if (DEBUG_REMOVE && chatty) {
7287                if (r == null) {
7288                    r = new StringBuilder(256);
7289                } else {
7290                    r.append(' ');
7291                }
7292                r.append(a.info.name);
7293            }
7294        }
7295        if (r != null) {
7296            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7297        }
7298
7299        N = pkg.activities.size();
7300        r = null;
7301        for (i=0; i<N; i++) {
7302            PackageParser.Activity a = pkg.activities.get(i);
7303            mActivities.removeActivity(a, "activity");
7304            if (DEBUG_REMOVE && chatty) {
7305                if (r == null) {
7306                    r = new StringBuilder(256);
7307                } else {
7308                    r.append(' ');
7309                }
7310                r.append(a.info.name);
7311            }
7312        }
7313        if (r != null) {
7314            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7315        }
7316
7317        N = pkg.permissions.size();
7318        r = null;
7319        for (i=0; i<N; i++) {
7320            PackageParser.Permission p = pkg.permissions.get(i);
7321            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7322            if (bp == null) {
7323                bp = mSettings.mPermissionTrees.get(p.info.name);
7324            }
7325            if (bp != null && bp.perm == p) {
7326                bp.perm = null;
7327                if (DEBUG_REMOVE && chatty) {
7328                    if (r == null) {
7329                        r = new StringBuilder(256);
7330                    } else {
7331                        r.append(' ');
7332                    }
7333                    r.append(p.info.name);
7334                }
7335            }
7336            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7337                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7338                if (appOpPerms != null) {
7339                    appOpPerms.remove(pkg.packageName);
7340                }
7341            }
7342        }
7343        if (r != null) {
7344            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7345        }
7346
7347        N = pkg.requestedPermissions.size();
7348        r = null;
7349        for (i=0; i<N; i++) {
7350            String perm = pkg.requestedPermissions.get(i);
7351            BasePermission bp = mSettings.mPermissions.get(perm);
7352            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7353                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7354                if (appOpPerms != null) {
7355                    appOpPerms.remove(pkg.packageName);
7356                    if (appOpPerms.isEmpty()) {
7357                        mAppOpPermissionPackages.remove(perm);
7358                    }
7359                }
7360            }
7361        }
7362        if (r != null) {
7363            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7364        }
7365
7366        N = pkg.instrumentation.size();
7367        r = null;
7368        for (i=0; i<N; i++) {
7369            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7370            mInstrumentation.remove(a.getComponentName());
7371            if (DEBUG_REMOVE && chatty) {
7372                if (r == null) {
7373                    r = new StringBuilder(256);
7374                } else {
7375                    r.append(' ');
7376                }
7377                r.append(a.info.name);
7378            }
7379        }
7380        if (r != null) {
7381            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7382        }
7383
7384        r = null;
7385        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7386            // Only system apps can hold shared libraries.
7387            if (pkg.libraryNames != null) {
7388                for (i=0; i<pkg.libraryNames.size(); i++) {
7389                    String name = pkg.libraryNames.get(i);
7390                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7391                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7392                        mSharedLibraries.remove(name);
7393                        if (DEBUG_REMOVE && chatty) {
7394                            if (r == null) {
7395                                r = new StringBuilder(256);
7396                            } else {
7397                                r.append(' ');
7398                            }
7399                            r.append(name);
7400                        }
7401                    }
7402                }
7403            }
7404        }
7405        if (r != null) {
7406            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7407        }
7408    }
7409
7410    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7411        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7412            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7413                return true;
7414            }
7415        }
7416        return false;
7417    }
7418
7419    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7420    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7421    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7422
7423    private void updatePermissionsLPw(String changingPkg,
7424            PackageParser.Package pkgInfo, int flags) {
7425        // Make sure there are no dangling permission trees.
7426        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7427        while (it.hasNext()) {
7428            final BasePermission bp = it.next();
7429            if (bp.packageSetting == null) {
7430                // We may not yet have parsed the package, so just see if
7431                // we still know about its settings.
7432                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7433            }
7434            if (bp.packageSetting == null) {
7435                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7436                        + " from package " + bp.sourcePackage);
7437                it.remove();
7438            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7439                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7440                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7441                            + " from package " + bp.sourcePackage);
7442                    flags |= UPDATE_PERMISSIONS_ALL;
7443                    it.remove();
7444                }
7445            }
7446        }
7447
7448        // Make sure all dynamic permissions have been assigned to a package,
7449        // and make sure there are no dangling permissions.
7450        it = mSettings.mPermissions.values().iterator();
7451        while (it.hasNext()) {
7452            final BasePermission bp = it.next();
7453            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7454                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7455                        + bp.name + " pkg=" + bp.sourcePackage
7456                        + " info=" + bp.pendingInfo);
7457                if (bp.packageSetting == null && bp.pendingInfo != null) {
7458                    final BasePermission tree = findPermissionTreeLP(bp.name);
7459                    if (tree != null && tree.perm != null) {
7460                        bp.packageSetting = tree.packageSetting;
7461                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7462                                new PermissionInfo(bp.pendingInfo));
7463                        bp.perm.info.packageName = tree.perm.info.packageName;
7464                        bp.perm.info.name = bp.name;
7465                        bp.uid = tree.uid;
7466                    }
7467                }
7468            }
7469            if (bp.packageSetting == null) {
7470                // We may not yet have parsed the package, so just see if
7471                // we still know about its settings.
7472                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7473            }
7474            if (bp.packageSetting == null) {
7475                Slog.w(TAG, "Removing dangling permission: " + bp.name
7476                        + " from package " + bp.sourcePackage);
7477                it.remove();
7478            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7479                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7480                    Slog.i(TAG, "Removing old permission: " + bp.name
7481                            + " from package " + bp.sourcePackage);
7482                    flags |= UPDATE_PERMISSIONS_ALL;
7483                    it.remove();
7484                }
7485            }
7486        }
7487
7488        // Now update the permissions for all packages, in particular
7489        // replace the granted permissions of the system packages.
7490        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7491            for (PackageParser.Package pkg : mPackages.values()) {
7492                if (pkg != pkgInfo) {
7493                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7494                            changingPkg);
7495                }
7496            }
7497        }
7498
7499        if (pkgInfo != null) {
7500            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7501        }
7502    }
7503
7504    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7505            String packageOfInterest) {
7506        // IMPORTANT: There are two types of permissions: install and runtime.
7507        // Install time permissions are granted when the app is installed to
7508        // all device users and users added in the future. Runtime permissions
7509        // are granted at runtime explicitly to specific users. Normal and signature
7510        // protected permissions are install time permissions. Dangerous permissions
7511        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7512        // otherwise they are runtime permissions. This function does not manage
7513        // runtime permissions except for the case an app targeting Lollipop MR1
7514        // being upgraded to target a newer SDK, in which case dangerous permissions
7515        // are transformed from install time to runtime ones.
7516
7517        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7518        if (ps == null) {
7519            return;
7520        }
7521
7522        PermissionsState permissionsState = ps.getPermissionsState();
7523        PermissionsState origPermissions = permissionsState;
7524
7525        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7526
7527        int[] upgradeUserIds = PermissionsState.USERS_NONE;
7528        int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE;
7529
7530        boolean changedInstallPermission = false;
7531
7532        if (replace) {
7533            ps.installPermissionsFixed = false;
7534            if (!ps.isSharedUser()) {
7535                origPermissions = new PermissionsState(permissionsState);
7536                permissionsState.reset();
7537            }
7538        }
7539
7540        permissionsState.setGlobalGids(mGlobalGids);
7541
7542        final int N = pkg.requestedPermissions.size();
7543        for (int i=0; i<N; i++) {
7544            final String name = pkg.requestedPermissions.get(i);
7545            final BasePermission bp = mSettings.mPermissions.get(name);
7546
7547            if (DEBUG_INSTALL) {
7548                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7549            }
7550
7551            if (bp == null || bp.packageSetting == null) {
7552                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7553                    Slog.w(TAG, "Unknown permission " + name
7554                            + " in package " + pkg.packageName);
7555                }
7556                continue;
7557            }
7558
7559            final String perm = bp.name;
7560            boolean allowedSig = false;
7561            int grant = GRANT_DENIED;
7562
7563            // Keep track of app op permissions.
7564            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7565                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7566                if (pkgs == null) {
7567                    pkgs = new ArraySet<>();
7568                    mAppOpPermissionPackages.put(bp.name, pkgs);
7569                }
7570                pkgs.add(pkg.packageName);
7571            }
7572
7573            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7574            switch (level) {
7575                case PermissionInfo.PROTECTION_NORMAL: {
7576                    // For all apps normal permissions are install time ones.
7577                    grant = GRANT_INSTALL;
7578                } break;
7579
7580                case PermissionInfo.PROTECTION_DANGEROUS: {
7581                    if (!RUNTIME_PERMISSIONS_ENABLED
7582                            || pkg.applicationInfo.targetSdkVersion
7583                                    <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7584                        // For legacy apps dangerous permissions are install time ones.
7585                        grant = GRANT_INSTALL;
7586                    } else if (ps.isSystem()) {
7587                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7588                        if (origPermissions.hasInstallPermission(bp.name)) {
7589                            // If a system app had an install permission, then the app was
7590                            // upgraded and we grant the permissions as runtime to all users.
7591                            grant = GRANT_UPGRADE;
7592                            upgradeUserIds = currentUserIds;
7593                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7594                            // If users changed since the last permissions update for a
7595                            // system app, we grant the permission as runtime to the new users.
7596                            grant = GRANT_UPGRADE;
7597                            upgradeUserIds = currentUserIds;
7598                            for (int userId : updatedUserIds) {
7599                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7600                            }
7601                        } else {
7602                            // Otherwise, we grant the permission as runtime if the app
7603                            // already had it, i.e. we preserve runtime permissions.
7604                            grant = GRANT_RUNTIME;
7605                        }
7606                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7607                        // For legacy apps that became modern, install becomes runtime.
7608                        grant = GRANT_UPGRADE;
7609                        upgradeUserIds = currentUserIds;
7610                    } else if (replace) {
7611                        // For upgraded modern apps keep runtime permissions unchanged.
7612                        grant = GRANT_RUNTIME;
7613                    }
7614                } break;
7615
7616                case PermissionInfo.PROTECTION_SIGNATURE: {
7617                    // For all apps signature permissions are install time ones.
7618                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7619                    if (allowedSig) {
7620                        grant = GRANT_INSTALL;
7621                    }
7622                } break;
7623            }
7624
7625            if (DEBUG_INSTALL) {
7626                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7627            }
7628
7629            if (grant != GRANT_DENIED) {
7630                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7631                    // If this is an existing, non-system package, then
7632                    // we can't add any new permissions to it.
7633                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7634                        // Except...  if this is a permission that was added
7635                        // to the platform (note: need to only do this when
7636                        // updating the platform).
7637                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7638                            grant = GRANT_DENIED;
7639                        }
7640                    }
7641                }
7642
7643                switch (grant) {
7644                    case GRANT_INSTALL: {
7645                        // Grant an install permission.
7646                        if (permissionsState.grantInstallPermission(bp) !=
7647                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7648                            changedInstallPermission = true;
7649                        }
7650                    } break;
7651
7652                    case GRANT_RUNTIME: {
7653                        // Grant previously granted runtime permissions.
7654                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7655                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7656                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7657                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7658                                    // If we cannot put the permission as it was, we have to write.
7659                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7660                                            changedRuntimePermissionUserIds, userId);
7661                                }
7662                            }
7663                        }
7664                    } break;
7665
7666                    case GRANT_UPGRADE: {
7667                        // Grant runtime permissions for a previously held install permission.
7668                        permissionsState.revokeInstallPermission(bp);
7669                        for (int userId : upgradeUserIds) {
7670                            if (permissionsState.grantRuntimePermission(bp, userId) !=
7671                                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
7672                                // If we granted the permission, we have to write.
7673                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7674                                        changedRuntimePermissionUserIds, userId);
7675                            }
7676                        }
7677                    } break;
7678
7679                    default: {
7680                        if (packageOfInterest == null
7681                                || packageOfInterest.equals(pkg.packageName)) {
7682                            Slog.w(TAG, "Not granting permission " + perm
7683                                    + " to package " + pkg.packageName
7684                                    + " because it was previously installed without");
7685                        }
7686                    } break;
7687                }
7688            } else {
7689                if (permissionsState.revokeInstallPermission(bp) !=
7690                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7691                    changedInstallPermission = true;
7692                    Slog.i(TAG, "Un-granting permission " + perm
7693                            + " from package " + pkg.packageName
7694                            + " (protectionLevel=" + bp.protectionLevel
7695                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7696                            + ")");
7697                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7698                    // Don't print warning for app op permissions, since it is fine for them
7699                    // not to be granted, there is a UI for the user to decide.
7700                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7701                        Slog.w(TAG, "Not granting permission " + perm
7702                                + " to package " + pkg.packageName
7703                                + " (protectionLevel=" + bp.protectionLevel
7704                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7705                                + ")");
7706                    }
7707                }
7708            }
7709        }
7710
7711        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7712                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7713            // This is the first that we have heard about this package, so the
7714            // permissions we have now selected are fixed until explicitly
7715            // changed.
7716            ps.installPermissionsFixed = true;
7717        }
7718
7719        ps.setPermissionsUpdatedForUserIds(currentUserIds);
7720
7721        // Persist the runtime permissions state for users with changes.
7722        if (RUNTIME_PERMISSIONS_ENABLED) {
7723            for (int userId : changedRuntimePermissionUserIds) {
7724                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
7725            }
7726        }
7727    }
7728
7729    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7730        boolean allowed = false;
7731        final int NP = PackageParser.NEW_PERMISSIONS.length;
7732        for (int ip=0; ip<NP; ip++) {
7733            final PackageParser.NewPermissionInfo npi
7734                    = PackageParser.NEW_PERMISSIONS[ip];
7735            if (npi.name.equals(perm)
7736                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7737                allowed = true;
7738                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7739                        + pkg.packageName);
7740                break;
7741            }
7742        }
7743        return allowed;
7744    }
7745
7746    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7747            BasePermission bp, PermissionsState origPermissions) {
7748        boolean allowed;
7749        allowed = (compareSignatures(
7750                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7751                        == PackageManager.SIGNATURE_MATCH)
7752                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7753                        == PackageManager.SIGNATURE_MATCH);
7754        if (!allowed && (bp.protectionLevel
7755                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7756            if (isSystemApp(pkg)) {
7757                // For updated system applications, a system permission
7758                // is granted only if it had been defined by the original application.
7759                if (pkg.isUpdatedSystemApp()) {
7760                    final PackageSetting sysPs = mSettings
7761                            .getDisabledSystemPkgLPr(pkg.packageName);
7762                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
7763                        // If the original was granted this permission, we take
7764                        // that grant decision as read and propagate it to the
7765                        // update.
7766                        if (sysPs.isPrivileged()) {
7767                            allowed = true;
7768                        }
7769                    } else {
7770                        // The system apk may have been updated with an older
7771                        // version of the one on the data partition, but which
7772                        // granted a new system permission that it didn't have
7773                        // before.  In this case we do want to allow the app to
7774                        // now get the new permission if the ancestral apk is
7775                        // privileged to get it.
7776                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7777                            for (int j=0;
7778                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7779                                if (perm.equals(
7780                                        sysPs.pkg.requestedPermissions.get(j))) {
7781                                    allowed = true;
7782                                    break;
7783                                }
7784                            }
7785                        }
7786                    }
7787                } else {
7788                    allowed = isPrivilegedApp(pkg);
7789                }
7790            }
7791        }
7792        if (!allowed && (bp.protectionLevel
7793                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7794            // For development permissions, a development permission
7795            // is granted only if it was already granted.
7796            allowed = origPermissions.hasInstallPermission(perm);
7797        }
7798        return allowed;
7799    }
7800
7801    final class ActivityIntentResolver
7802            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7803        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7804                boolean defaultOnly, int userId) {
7805            if (!sUserManager.exists(userId)) return null;
7806            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7807            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7808        }
7809
7810        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7811                int userId) {
7812            if (!sUserManager.exists(userId)) return null;
7813            mFlags = flags;
7814            return super.queryIntent(intent, resolvedType,
7815                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7816        }
7817
7818        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7819                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7820            if (!sUserManager.exists(userId)) return null;
7821            if (packageActivities == null) {
7822                return null;
7823            }
7824            mFlags = flags;
7825            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7826            final int N = packageActivities.size();
7827            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7828                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7829
7830            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7831            for (int i = 0; i < N; ++i) {
7832                intentFilters = packageActivities.get(i).intents;
7833                if (intentFilters != null && intentFilters.size() > 0) {
7834                    PackageParser.ActivityIntentInfo[] array =
7835                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7836                    intentFilters.toArray(array);
7837                    listCut.add(array);
7838                }
7839            }
7840            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7841        }
7842
7843        public final void addActivity(PackageParser.Activity a, String type) {
7844            final boolean systemApp = a.info.applicationInfo.isSystemApp();
7845            mActivities.put(a.getComponentName(), a);
7846            if (DEBUG_SHOW_INFO)
7847                Log.v(
7848                TAG, "  " + type + " " +
7849                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7850            if (DEBUG_SHOW_INFO)
7851                Log.v(TAG, "    Class=" + a.info.name);
7852            final int NI = a.intents.size();
7853            for (int j=0; j<NI; j++) {
7854                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7855                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7856                    intent.setPriority(0);
7857                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7858                            + a.className + " with priority > 0, forcing to 0");
7859                }
7860                if (DEBUG_SHOW_INFO) {
7861                    Log.v(TAG, "    IntentFilter:");
7862                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7863                }
7864                if (!intent.debugCheck()) {
7865                    Log.w(TAG, "==> For Activity " + a.info.name);
7866                }
7867                addFilter(intent);
7868            }
7869        }
7870
7871        public final void removeActivity(PackageParser.Activity a, String type) {
7872            mActivities.remove(a.getComponentName());
7873            if (DEBUG_SHOW_INFO) {
7874                Log.v(TAG, "  " + type + " "
7875                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7876                                : a.info.name) + ":");
7877                Log.v(TAG, "    Class=" + a.info.name);
7878            }
7879            final int NI = a.intents.size();
7880            for (int j=0; j<NI; j++) {
7881                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7882                if (DEBUG_SHOW_INFO) {
7883                    Log.v(TAG, "    IntentFilter:");
7884                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7885                }
7886                removeFilter(intent);
7887            }
7888        }
7889
7890        @Override
7891        protected boolean allowFilterResult(
7892                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7893            ActivityInfo filterAi = filter.activity.info;
7894            for (int i=dest.size()-1; i>=0; i--) {
7895                ActivityInfo destAi = dest.get(i).activityInfo;
7896                if (destAi.name == filterAi.name
7897                        && destAi.packageName == filterAi.packageName) {
7898                    return false;
7899                }
7900            }
7901            return true;
7902        }
7903
7904        @Override
7905        protected ActivityIntentInfo[] newArray(int size) {
7906            return new ActivityIntentInfo[size];
7907        }
7908
7909        @Override
7910        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7911            if (!sUserManager.exists(userId)) return true;
7912            PackageParser.Package p = filter.activity.owner;
7913            if (p != null) {
7914                PackageSetting ps = (PackageSetting)p.mExtras;
7915                if (ps != null) {
7916                    // System apps are never considered stopped for purposes of
7917                    // filtering, because there may be no way for the user to
7918                    // actually re-launch them.
7919                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7920                            && ps.getStopped(userId);
7921                }
7922            }
7923            return false;
7924        }
7925
7926        @Override
7927        protected boolean isPackageForFilter(String packageName,
7928                PackageParser.ActivityIntentInfo info) {
7929            return packageName.equals(info.activity.owner.packageName);
7930        }
7931
7932        @Override
7933        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7934                int match, int userId) {
7935            if (!sUserManager.exists(userId)) return null;
7936            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7937                return null;
7938            }
7939            final PackageParser.Activity activity = info.activity;
7940            if (mSafeMode && (activity.info.applicationInfo.flags
7941                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7942                return null;
7943            }
7944            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7945            if (ps == null) {
7946                return null;
7947            }
7948            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7949                    ps.readUserState(userId), userId);
7950            if (ai == null) {
7951                return null;
7952            }
7953            final ResolveInfo res = new ResolveInfo();
7954            res.activityInfo = ai;
7955            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7956                res.filter = info;
7957            }
7958            if (info != null) {
7959                res.handleAllWebDataURI = info.handleAllWebDataURI();
7960            }
7961            res.priority = info.getPriority();
7962            res.preferredOrder = activity.owner.mPreferredOrder;
7963            //System.out.println("Result: " + res.activityInfo.className +
7964            //                   " = " + res.priority);
7965            res.match = match;
7966            res.isDefault = info.hasDefault;
7967            res.labelRes = info.labelRes;
7968            res.nonLocalizedLabel = info.nonLocalizedLabel;
7969            if (userNeedsBadging(userId)) {
7970                res.noResourceId = true;
7971            } else {
7972                res.icon = info.icon;
7973            }
7974            res.system = res.activityInfo.applicationInfo.isSystemApp();
7975            return res;
7976        }
7977
7978        @Override
7979        protected void sortResults(List<ResolveInfo> results) {
7980            Collections.sort(results, mResolvePrioritySorter);
7981        }
7982
7983        @Override
7984        protected void dumpFilter(PrintWriter out, String prefix,
7985                PackageParser.ActivityIntentInfo filter) {
7986            out.print(prefix); out.print(
7987                    Integer.toHexString(System.identityHashCode(filter.activity)));
7988                    out.print(' ');
7989                    filter.activity.printComponentShortName(out);
7990                    out.print(" filter ");
7991                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7992        }
7993
7994        @Override
7995        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
7996            return filter.activity;
7997        }
7998
7999        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8000            PackageParser.Activity activity = (PackageParser.Activity)label;
8001            out.print(prefix); out.print(
8002                    Integer.toHexString(System.identityHashCode(activity)));
8003                    out.print(' ');
8004                    activity.printComponentShortName(out);
8005            if (count > 1) {
8006                out.print(" ("); out.print(count); out.print(" filters)");
8007            }
8008            out.println();
8009        }
8010
8011//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8012//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8013//            final List<ResolveInfo> retList = Lists.newArrayList();
8014//            while (i.hasNext()) {
8015//                final ResolveInfo resolveInfo = i.next();
8016//                if (isEnabledLP(resolveInfo.activityInfo)) {
8017//                    retList.add(resolveInfo);
8018//                }
8019//            }
8020//            return retList;
8021//        }
8022
8023        // Keys are String (activity class name), values are Activity.
8024        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8025                = new ArrayMap<ComponentName, PackageParser.Activity>();
8026        private int mFlags;
8027    }
8028
8029    private final class ServiceIntentResolver
8030            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8031        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8032                boolean defaultOnly, int userId) {
8033            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8034            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8035        }
8036
8037        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8038                int userId) {
8039            if (!sUserManager.exists(userId)) return null;
8040            mFlags = flags;
8041            return super.queryIntent(intent, resolvedType,
8042                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8043        }
8044
8045        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8046                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8047            if (!sUserManager.exists(userId)) return null;
8048            if (packageServices == null) {
8049                return null;
8050            }
8051            mFlags = flags;
8052            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8053            final int N = packageServices.size();
8054            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8055                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8056
8057            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8058            for (int i = 0; i < N; ++i) {
8059                intentFilters = packageServices.get(i).intents;
8060                if (intentFilters != null && intentFilters.size() > 0) {
8061                    PackageParser.ServiceIntentInfo[] array =
8062                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8063                    intentFilters.toArray(array);
8064                    listCut.add(array);
8065                }
8066            }
8067            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8068        }
8069
8070        public final void addService(PackageParser.Service s) {
8071            mServices.put(s.getComponentName(), s);
8072            if (DEBUG_SHOW_INFO) {
8073                Log.v(TAG, "  "
8074                        + (s.info.nonLocalizedLabel != null
8075                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8076                Log.v(TAG, "    Class=" + s.info.name);
8077            }
8078            final int NI = s.intents.size();
8079            int j;
8080            for (j=0; j<NI; j++) {
8081                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8082                if (DEBUG_SHOW_INFO) {
8083                    Log.v(TAG, "    IntentFilter:");
8084                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8085                }
8086                if (!intent.debugCheck()) {
8087                    Log.w(TAG, "==> For Service " + s.info.name);
8088                }
8089                addFilter(intent);
8090            }
8091        }
8092
8093        public final void removeService(PackageParser.Service s) {
8094            mServices.remove(s.getComponentName());
8095            if (DEBUG_SHOW_INFO) {
8096                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8097                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8098                Log.v(TAG, "    Class=" + s.info.name);
8099            }
8100            final int NI = s.intents.size();
8101            int j;
8102            for (j=0; j<NI; j++) {
8103                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8104                if (DEBUG_SHOW_INFO) {
8105                    Log.v(TAG, "    IntentFilter:");
8106                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8107                }
8108                removeFilter(intent);
8109            }
8110        }
8111
8112        @Override
8113        protected boolean allowFilterResult(
8114                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8115            ServiceInfo filterSi = filter.service.info;
8116            for (int i=dest.size()-1; i>=0; i--) {
8117                ServiceInfo destAi = dest.get(i).serviceInfo;
8118                if (destAi.name == filterSi.name
8119                        && destAi.packageName == filterSi.packageName) {
8120                    return false;
8121                }
8122            }
8123            return true;
8124        }
8125
8126        @Override
8127        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8128            return new PackageParser.ServiceIntentInfo[size];
8129        }
8130
8131        @Override
8132        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8133            if (!sUserManager.exists(userId)) return true;
8134            PackageParser.Package p = filter.service.owner;
8135            if (p != null) {
8136                PackageSetting ps = (PackageSetting)p.mExtras;
8137                if (ps != null) {
8138                    // System apps are never considered stopped for purposes of
8139                    // filtering, because there may be no way for the user to
8140                    // actually re-launch them.
8141                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8142                            && ps.getStopped(userId);
8143                }
8144            }
8145            return false;
8146        }
8147
8148        @Override
8149        protected boolean isPackageForFilter(String packageName,
8150                PackageParser.ServiceIntentInfo info) {
8151            return packageName.equals(info.service.owner.packageName);
8152        }
8153
8154        @Override
8155        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8156                int match, int userId) {
8157            if (!sUserManager.exists(userId)) return null;
8158            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8159            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8160                return null;
8161            }
8162            final PackageParser.Service service = info.service;
8163            if (mSafeMode && (service.info.applicationInfo.flags
8164                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8165                return null;
8166            }
8167            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8168            if (ps == null) {
8169                return null;
8170            }
8171            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8172                    ps.readUserState(userId), userId);
8173            if (si == null) {
8174                return null;
8175            }
8176            final ResolveInfo res = new ResolveInfo();
8177            res.serviceInfo = si;
8178            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8179                res.filter = filter;
8180            }
8181            res.priority = info.getPriority();
8182            res.preferredOrder = service.owner.mPreferredOrder;
8183            res.match = match;
8184            res.isDefault = info.hasDefault;
8185            res.labelRes = info.labelRes;
8186            res.nonLocalizedLabel = info.nonLocalizedLabel;
8187            res.icon = info.icon;
8188            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8189            return res;
8190        }
8191
8192        @Override
8193        protected void sortResults(List<ResolveInfo> results) {
8194            Collections.sort(results, mResolvePrioritySorter);
8195        }
8196
8197        @Override
8198        protected void dumpFilter(PrintWriter out, String prefix,
8199                PackageParser.ServiceIntentInfo filter) {
8200            out.print(prefix); out.print(
8201                    Integer.toHexString(System.identityHashCode(filter.service)));
8202                    out.print(' ');
8203                    filter.service.printComponentShortName(out);
8204                    out.print(" filter ");
8205                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8206        }
8207
8208        @Override
8209        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8210            return filter.service;
8211        }
8212
8213        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8214            PackageParser.Service service = (PackageParser.Service)label;
8215            out.print(prefix); out.print(
8216                    Integer.toHexString(System.identityHashCode(service)));
8217                    out.print(' ');
8218                    service.printComponentShortName(out);
8219            if (count > 1) {
8220                out.print(" ("); out.print(count); out.print(" filters)");
8221            }
8222            out.println();
8223        }
8224
8225//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8226//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8227//            final List<ResolveInfo> retList = Lists.newArrayList();
8228//            while (i.hasNext()) {
8229//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8230//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8231//                    retList.add(resolveInfo);
8232//                }
8233//            }
8234//            return retList;
8235//        }
8236
8237        // Keys are String (activity class name), values are Activity.
8238        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8239                = new ArrayMap<ComponentName, PackageParser.Service>();
8240        private int mFlags;
8241    };
8242
8243    private final class ProviderIntentResolver
8244            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8245        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8246                boolean defaultOnly, int userId) {
8247            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8248            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8249        }
8250
8251        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8252                int userId) {
8253            if (!sUserManager.exists(userId))
8254                return null;
8255            mFlags = flags;
8256            return super.queryIntent(intent, resolvedType,
8257                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8258        }
8259
8260        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8261                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8262            if (!sUserManager.exists(userId))
8263                return null;
8264            if (packageProviders == null) {
8265                return null;
8266            }
8267            mFlags = flags;
8268            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8269            final int N = packageProviders.size();
8270            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8271                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8272
8273            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8274            for (int i = 0; i < N; ++i) {
8275                intentFilters = packageProviders.get(i).intents;
8276                if (intentFilters != null && intentFilters.size() > 0) {
8277                    PackageParser.ProviderIntentInfo[] array =
8278                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8279                    intentFilters.toArray(array);
8280                    listCut.add(array);
8281                }
8282            }
8283            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8284        }
8285
8286        public final void addProvider(PackageParser.Provider p) {
8287            if (mProviders.containsKey(p.getComponentName())) {
8288                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8289                return;
8290            }
8291
8292            mProviders.put(p.getComponentName(), p);
8293            if (DEBUG_SHOW_INFO) {
8294                Log.v(TAG, "  "
8295                        + (p.info.nonLocalizedLabel != null
8296                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8297                Log.v(TAG, "    Class=" + p.info.name);
8298            }
8299            final int NI = p.intents.size();
8300            int j;
8301            for (j = 0; j < NI; j++) {
8302                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8303                if (DEBUG_SHOW_INFO) {
8304                    Log.v(TAG, "    IntentFilter:");
8305                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8306                }
8307                if (!intent.debugCheck()) {
8308                    Log.w(TAG, "==> For Provider " + p.info.name);
8309                }
8310                addFilter(intent);
8311            }
8312        }
8313
8314        public final void removeProvider(PackageParser.Provider p) {
8315            mProviders.remove(p.getComponentName());
8316            if (DEBUG_SHOW_INFO) {
8317                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8318                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8319                Log.v(TAG, "    Class=" + p.info.name);
8320            }
8321            final int NI = p.intents.size();
8322            int j;
8323            for (j = 0; j < NI; j++) {
8324                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8325                if (DEBUG_SHOW_INFO) {
8326                    Log.v(TAG, "    IntentFilter:");
8327                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8328                }
8329                removeFilter(intent);
8330            }
8331        }
8332
8333        @Override
8334        protected boolean allowFilterResult(
8335                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8336            ProviderInfo filterPi = filter.provider.info;
8337            for (int i = dest.size() - 1; i >= 0; i--) {
8338                ProviderInfo destPi = dest.get(i).providerInfo;
8339                if (destPi.name == filterPi.name
8340                        && destPi.packageName == filterPi.packageName) {
8341                    return false;
8342                }
8343            }
8344            return true;
8345        }
8346
8347        @Override
8348        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8349            return new PackageParser.ProviderIntentInfo[size];
8350        }
8351
8352        @Override
8353        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8354            if (!sUserManager.exists(userId))
8355                return true;
8356            PackageParser.Package p = filter.provider.owner;
8357            if (p != null) {
8358                PackageSetting ps = (PackageSetting) p.mExtras;
8359                if (ps != null) {
8360                    // System apps are never considered stopped for purposes of
8361                    // filtering, because there may be no way for the user to
8362                    // actually re-launch them.
8363                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8364                            && ps.getStopped(userId);
8365                }
8366            }
8367            return false;
8368        }
8369
8370        @Override
8371        protected boolean isPackageForFilter(String packageName,
8372                PackageParser.ProviderIntentInfo info) {
8373            return packageName.equals(info.provider.owner.packageName);
8374        }
8375
8376        @Override
8377        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8378                int match, int userId) {
8379            if (!sUserManager.exists(userId))
8380                return null;
8381            final PackageParser.ProviderIntentInfo info = filter;
8382            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8383                return null;
8384            }
8385            final PackageParser.Provider provider = info.provider;
8386            if (mSafeMode && (provider.info.applicationInfo.flags
8387                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8388                return null;
8389            }
8390            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8391            if (ps == null) {
8392                return null;
8393            }
8394            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8395                    ps.readUserState(userId), userId);
8396            if (pi == null) {
8397                return null;
8398            }
8399            final ResolveInfo res = new ResolveInfo();
8400            res.providerInfo = pi;
8401            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8402                res.filter = filter;
8403            }
8404            res.priority = info.getPriority();
8405            res.preferredOrder = provider.owner.mPreferredOrder;
8406            res.match = match;
8407            res.isDefault = info.hasDefault;
8408            res.labelRes = info.labelRes;
8409            res.nonLocalizedLabel = info.nonLocalizedLabel;
8410            res.icon = info.icon;
8411            res.system = res.providerInfo.applicationInfo.isSystemApp();
8412            return res;
8413        }
8414
8415        @Override
8416        protected void sortResults(List<ResolveInfo> results) {
8417            Collections.sort(results, mResolvePrioritySorter);
8418        }
8419
8420        @Override
8421        protected void dumpFilter(PrintWriter out, String prefix,
8422                PackageParser.ProviderIntentInfo filter) {
8423            out.print(prefix);
8424            out.print(
8425                    Integer.toHexString(System.identityHashCode(filter.provider)));
8426            out.print(' ');
8427            filter.provider.printComponentShortName(out);
8428            out.print(" filter ");
8429            out.println(Integer.toHexString(System.identityHashCode(filter)));
8430        }
8431
8432        @Override
8433        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8434            return filter.provider;
8435        }
8436
8437        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8438            PackageParser.Provider provider = (PackageParser.Provider)label;
8439            out.print(prefix); out.print(
8440                    Integer.toHexString(System.identityHashCode(provider)));
8441                    out.print(' ');
8442                    provider.printComponentShortName(out);
8443            if (count > 1) {
8444                out.print(" ("); out.print(count); out.print(" filters)");
8445            }
8446            out.println();
8447        }
8448
8449        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8450                = new ArrayMap<ComponentName, PackageParser.Provider>();
8451        private int mFlags;
8452    };
8453
8454    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8455            new Comparator<ResolveInfo>() {
8456        public int compare(ResolveInfo r1, ResolveInfo r2) {
8457            int v1 = r1.priority;
8458            int v2 = r2.priority;
8459            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8460            if (v1 != v2) {
8461                return (v1 > v2) ? -1 : 1;
8462            }
8463            v1 = r1.preferredOrder;
8464            v2 = r2.preferredOrder;
8465            if (v1 != v2) {
8466                return (v1 > v2) ? -1 : 1;
8467            }
8468            if (r1.isDefault != r2.isDefault) {
8469                return r1.isDefault ? -1 : 1;
8470            }
8471            v1 = r1.match;
8472            v2 = r2.match;
8473            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8474            if (v1 != v2) {
8475                return (v1 > v2) ? -1 : 1;
8476            }
8477            if (r1.system != r2.system) {
8478                return r1.system ? -1 : 1;
8479            }
8480            return 0;
8481        }
8482    };
8483
8484    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8485            new Comparator<ProviderInfo>() {
8486        public int compare(ProviderInfo p1, ProviderInfo p2) {
8487            final int v1 = p1.initOrder;
8488            final int v2 = p2.initOrder;
8489            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8490        }
8491    };
8492
8493    static final void sendPackageBroadcast(String action, String pkg,
8494            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
8495            int[] userIds) {
8496        IActivityManager am = ActivityManagerNative.getDefault();
8497        if (am != null) {
8498            try {
8499                if (userIds == null) {
8500                    userIds = am.getRunningUserIds();
8501                }
8502                for (int id : userIds) {
8503                    final Intent intent = new Intent(action,
8504                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
8505                    if (extras != null) {
8506                        intent.putExtras(extras);
8507                    }
8508                    if (targetPkg != null) {
8509                        intent.setPackage(targetPkg);
8510                    }
8511                    // Modify the UID when posting to other users
8512                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8513                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
8514                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8515                        intent.putExtra(Intent.EXTRA_UID, uid);
8516                    }
8517                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8518                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8519                    if (DEBUG_BROADCASTS) {
8520                        RuntimeException here = new RuntimeException("here");
8521                        here.fillInStackTrace();
8522                        Slog.d(TAG, "Sending to user " + id + ": "
8523                                + intent.toShortString(false, true, false, false)
8524                                + " " + intent.getExtras(), here);
8525                    }
8526                    am.broadcastIntent(null, intent, null, finishedReceiver,
8527                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
8528                            finishedReceiver != null, false, id);
8529                }
8530            } catch (RemoteException ex) {
8531            }
8532        }
8533    }
8534
8535    /**
8536     * Check if the external storage media is available. This is true if there
8537     * is a mounted external storage medium or if the external storage is
8538     * emulated.
8539     */
8540    private boolean isExternalMediaAvailable() {
8541        return mMediaMounted || Environment.isExternalStorageEmulated();
8542    }
8543
8544    @Override
8545    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8546        // writer
8547        synchronized (mPackages) {
8548            if (!isExternalMediaAvailable()) {
8549                // If the external storage is no longer mounted at this point,
8550                // the caller may not have been able to delete all of this
8551                // packages files and can not delete any more.  Bail.
8552                return null;
8553            }
8554            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8555            if (lastPackage != null) {
8556                pkgs.remove(lastPackage);
8557            }
8558            if (pkgs.size() > 0) {
8559                return pkgs.get(0);
8560            }
8561        }
8562        return null;
8563    }
8564
8565    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8566        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8567                userId, andCode ? 1 : 0, packageName);
8568        if (mSystemReady) {
8569            msg.sendToTarget();
8570        } else {
8571            if (mPostSystemReadyMessages == null) {
8572                mPostSystemReadyMessages = new ArrayList<>();
8573            }
8574            mPostSystemReadyMessages.add(msg);
8575        }
8576    }
8577
8578    void startCleaningPackages() {
8579        // reader
8580        synchronized (mPackages) {
8581            if (!isExternalMediaAvailable()) {
8582                return;
8583            }
8584            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8585                return;
8586            }
8587        }
8588        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8589        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8590        IActivityManager am = ActivityManagerNative.getDefault();
8591        if (am != null) {
8592            try {
8593                am.startService(null, intent, null, UserHandle.USER_OWNER);
8594            } catch (RemoteException e) {
8595            }
8596        }
8597    }
8598
8599    @Override
8600    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8601            int installFlags, String installerPackageName, VerificationParams verificationParams,
8602            String packageAbiOverride) {
8603        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8604                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8605    }
8606
8607    @Override
8608    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8609            int installFlags, String installerPackageName, VerificationParams verificationParams,
8610            String packageAbiOverride, int userId) {
8611        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8612
8613        final int callingUid = Binder.getCallingUid();
8614        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8615
8616        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8617            try {
8618                if (observer != null) {
8619                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8620                }
8621            } catch (RemoteException re) {
8622            }
8623            return;
8624        }
8625
8626        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8627            installFlags |= PackageManager.INSTALL_FROM_ADB;
8628
8629        } else {
8630            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8631            // about installerPackageName.
8632
8633            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8634            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8635        }
8636
8637        UserHandle user;
8638        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8639            user = UserHandle.ALL;
8640        } else {
8641            user = new UserHandle(userId);
8642        }
8643
8644        // Only system components can circumvent runtime permissions when installing.
8645        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
8646                && mContext.checkCallingOrSelfPermission(Manifest.permission
8647                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
8648            throw new SecurityException("You need the "
8649                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
8650                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
8651        }
8652
8653        verificationParams.setInstallerUid(callingUid);
8654
8655        final File originFile = new File(originPath);
8656        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8657
8658        final Message msg = mHandler.obtainMessage(INIT_COPY);
8659        msg.obj = new InstallParams(origin, observer, installFlags,
8660                installerPackageName, null, verificationParams, user, packageAbiOverride);
8661        mHandler.sendMessage(msg);
8662    }
8663
8664    void installStage(String packageName, File stagedDir, String stagedCid,
8665            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8666            String installerPackageName, int installerUid, UserHandle user) {
8667        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8668                params.referrerUri, installerUid, null);
8669
8670        final OriginInfo origin;
8671        if (stagedDir != null) {
8672            origin = OriginInfo.fromStagedFile(stagedDir);
8673        } else {
8674            origin = OriginInfo.fromStagedContainer(stagedCid);
8675        }
8676
8677        final Message msg = mHandler.obtainMessage(INIT_COPY);
8678        msg.obj = new InstallParams(origin, observer, params.installFlags,
8679                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8680        mHandler.sendMessage(msg);
8681    }
8682
8683    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8684        Bundle extras = new Bundle(1);
8685        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8686
8687        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8688                packageName, extras, null, null, new int[] {userId});
8689        try {
8690            IActivityManager am = ActivityManagerNative.getDefault();
8691            final boolean isSystem =
8692                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8693            if (isSystem && am.isUserRunning(userId, false)) {
8694                // The just-installed/enabled app is bundled on the system, so presumed
8695                // to be able to run automatically without needing an explicit launch.
8696                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8697                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8698                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8699                        .setPackage(packageName);
8700                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8701                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8702            }
8703        } catch (RemoteException e) {
8704            // shouldn't happen
8705            Slog.w(TAG, "Unable to bootstrap installed package", e);
8706        }
8707    }
8708
8709    @Override
8710    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8711            int userId) {
8712        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8713        PackageSetting pkgSetting;
8714        final int uid = Binder.getCallingUid();
8715        enforceCrossUserPermission(uid, userId, true, true,
8716                "setApplicationHiddenSetting for user " + userId);
8717
8718        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8719            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8720            return false;
8721        }
8722
8723        long callingId = Binder.clearCallingIdentity();
8724        try {
8725            boolean sendAdded = false;
8726            boolean sendRemoved = false;
8727            // writer
8728            synchronized (mPackages) {
8729                pkgSetting = mSettings.mPackages.get(packageName);
8730                if (pkgSetting == null) {
8731                    return false;
8732                }
8733                if (pkgSetting.getHidden(userId) != hidden) {
8734                    pkgSetting.setHidden(hidden, userId);
8735                    mSettings.writePackageRestrictionsLPr(userId);
8736                    if (hidden) {
8737                        sendRemoved = true;
8738                    } else {
8739                        sendAdded = true;
8740                    }
8741                }
8742            }
8743            if (sendAdded) {
8744                sendPackageAddedForUser(packageName, pkgSetting, userId);
8745                return true;
8746            }
8747            if (sendRemoved) {
8748                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8749                        "hiding pkg");
8750                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8751            }
8752        } finally {
8753            Binder.restoreCallingIdentity(callingId);
8754        }
8755        return false;
8756    }
8757
8758    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8759            int userId) {
8760        final PackageRemovedInfo info = new PackageRemovedInfo();
8761        info.removedPackage = packageName;
8762        info.removedUsers = new int[] {userId};
8763        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8764        info.sendBroadcast(false, false, false);
8765    }
8766
8767    /**
8768     * Returns true if application is not found or there was an error. Otherwise it returns
8769     * the hidden state of the package for the given user.
8770     */
8771    @Override
8772    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8773        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8774        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8775                false, "getApplicationHidden for user " + userId);
8776        PackageSetting pkgSetting;
8777        long callingId = Binder.clearCallingIdentity();
8778        try {
8779            // writer
8780            synchronized (mPackages) {
8781                pkgSetting = mSettings.mPackages.get(packageName);
8782                if (pkgSetting == null) {
8783                    return true;
8784                }
8785                return pkgSetting.getHidden(userId);
8786            }
8787        } finally {
8788            Binder.restoreCallingIdentity(callingId);
8789        }
8790    }
8791
8792    /**
8793     * @hide
8794     */
8795    @Override
8796    public int installExistingPackageAsUser(String packageName, int userId) {
8797        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8798                null);
8799        PackageSetting pkgSetting;
8800        final int uid = Binder.getCallingUid();
8801        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8802                + userId);
8803        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8804            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8805        }
8806
8807        long callingId = Binder.clearCallingIdentity();
8808        try {
8809            boolean sendAdded = false;
8810
8811            // writer
8812            synchronized (mPackages) {
8813                pkgSetting = mSettings.mPackages.get(packageName);
8814                if (pkgSetting == null) {
8815                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8816                }
8817                if (!pkgSetting.getInstalled(userId)) {
8818                    pkgSetting.setInstalled(true, userId);
8819                    pkgSetting.setHidden(false, userId);
8820                    mSettings.writePackageRestrictionsLPr(userId);
8821                    sendAdded = true;
8822                }
8823            }
8824
8825            if (sendAdded) {
8826                sendPackageAddedForUser(packageName, pkgSetting, userId);
8827            }
8828        } finally {
8829            Binder.restoreCallingIdentity(callingId);
8830        }
8831
8832        return PackageManager.INSTALL_SUCCEEDED;
8833    }
8834
8835    boolean isUserRestricted(int userId, String restrictionKey) {
8836        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8837        if (restrictions.getBoolean(restrictionKey, false)) {
8838            Log.w(TAG, "User is restricted: " + restrictionKey);
8839            return true;
8840        }
8841        return false;
8842    }
8843
8844    @Override
8845    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8846        mContext.enforceCallingOrSelfPermission(
8847                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8848                "Only package verification agents can verify applications");
8849
8850        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8851        final PackageVerificationResponse response = new PackageVerificationResponse(
8852                verificationCode, Binder.getCallingUid());
8853        msg.arg1 = id;
8854        msg.obj = response;
8855        mHandler.sendMessage(msg);
8856    }
8857
8858    @Override
8859    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8860            long millisecondsToDelay) {
8861        mContext.enforceCallingOrSelfPermission(
8862                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8863                "Only package verification agents can extend verification timeouts");
8864
8865        final PackageVerificationState state = mPendingVerification.get(id);
8866        final PackageVerificationResponse response = new PackageVerificationResponse(
8867                verificationCodeAtTimeout, Binder.getCallingUid());
8868
8869        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8870            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8871        }
8872        if (millisecondsToDelay < 0) {
8873            millisecondsToDelay = 0;
8874        }
8875        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8876                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8877            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8878        }
8879
8880        if ((state != null) && !state.timeoutExtended()) {
8881            state.extendTimeout();
8882
8883            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8884            msg.arg1 = id;
8885            msg.obj = response;
8886            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8887        }
8888    }
8889
8890    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8891            int verificationCode, UserHandle user) {
8892        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8893        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8894        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8895        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8896        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8897
8898        mContext.sendBroadcastAsUser(intent, user,
8899                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8900    }
8901
8902    private ComponentName matchComponentForVerifier(String packageName,
8903            List<ResolveInfo> receivers) {
8904        ActivityInfo targetReceiver = null;
8905
8906        final int NR = receivers.size();
8907        for (int i = 0; i < NR; i++) {
8908            final ResolveInfo info = receivers.get(i);
8909            if (info.activityInfo == null) {
8910                continue;
8911            }
8912
8913            if (packageName.equals(info.activityInfo.packageName)) {
8914                targetReceiver = info.activityInfo;
8915                break;
8916            }
8917        }
8918
8919        if (targetReceiver == null) {
8920            return null;
8921        }
8922
8923        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8924    }
8925
8926    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8927            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8928        if (pkgInfo.verifiers.length == 0) {
8929            return null;
8930        }
8931
8932        final int N = pkgInfo.verifiers.length;
8933        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8934        for (int i = 0; i < N; i++) {
8935            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8936
8937            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8938                    receivers);
8939            if (comp == null) {
8940                continue;
8941            }
8942
8943            final int verifierUid = getUidForVerifier(verifierInfo);
8944            if (verifierUid == -1) {
8945                continue;
8946            }
8947
8948            if (DEBUG_VERIFY) {
8949                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8950                        + " with the correct signature");
8951            }
8952            sufficientVerifiers.add(comp);
8953            verificationState.addSufficientVerifier(verifierUid);
8954        }
8955
8956        return sufficientVerifiers;
8957    }
8958
8959    private int getUidForVerifier(VerifierInfo verifierInfo) {
8960        synchronized (mPackages) {
8961            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8962            if (pkg == null) {
8963                return -1;
8964            } else if (pkg.mSignatures.length != 1) {
8965                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8966                        + " has more than one signature; ignoring");
8967                return -1;
8968            }
8969
8970            /*
8971             * If the public key of the package's signature does not match
8972             * our expected public key, then this is a different package and
8973             * we should skip.
8974             */
8975
8976            final byte[] expectedPublicKey;
8977            try {
8978                final Signature verifierSig = pkg.mSignatures[0];
8979                final PublicKey publicKey = verifierSig.getPublicKey();
8980                expectedPublicKey = publicKey.getEncoded();
8981            } catch (CertificateException e) {
8982                return -1;
8983            }
8984
8985            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8986
8987            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8988                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8989                        + " does not have the expected public key; ignoring");
8990                return -1;
8991            }
8992
8993            return pkg.applicationInfo.uid;
8994        }
8995    }
8996
8997    @Override
8998    public void finishPackageInstall(int token) {
8999        enforceSystemOrRoot("Only the system is allowed to finish installs");
9000
9001        if (DEBUG_INSTALL) {
9002            Slog.v(TAG, "BM finishing package install for " + token);
9003        }
9004
9005        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9006        mHandler.sendMessage(msg);
9007    }
9008
9009    /**
9010     * Get the verification agent timeout.
9011     *
9012     * @return verification timeout in milliseconds
9013     */
9014    private long getVerificationTimeout() {
9015        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9016                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9017                DEFAULT_VERIFICATION_TIMEOUT);
9018    }
9019
9020    /**
9021     * Get the default verification agent response code.
9022     *
9023     * @return default verification response code
9024     */
9025    private int getDefaultVerificationResponse() {
9026        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9027                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9028                DEFAULT_VERIFICATION_RESPONSE);
9029    }
9030
9031    /**
9032     * Check whether or not package verification has been enabled.
9033     *
9034     * @return true if verification should be performed
9035     */
9036    private boolean isVerificationEnabled(int userId, int installFlags) {
9037        if (!DEFAULT_VERIFY_ENABLE) {
9038            return false;
9039        }
9040
9041        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9042
9043        // Check if installing from ADB
9044        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9045            // Do not run verification in a test harness environment
9046            if (ActivityManager.isRunningInTestHarness()) {
9047                return false;
9048            }
9049            if (ensureVerifyAppsEnabled) {
9050                return true;
9051            }
9052            // Check if the developer does not want package verification for ADB installs
9053            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9054                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9055                return false;
9056            }
9057        }
9058
9059        if (ensureVerifyAppsEnabled) {
9060            return true;
9061        }
9062
9063        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9064                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9065    }
9066
9067    @Override
9068    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9069            throws RemoteException {
9070        mContext.enforceCallingOrSelfPermission(
9071                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9072                "Only intentfilter verification agents can verify applications");
9073
9074        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9075        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9076                Binder.getCallingUid(), verificationCode, failedDomains);
9077        msg.arg1 = id;
9078        msg.obj = response;
9079        mHandler.sendMessage(msg);
9080    }
9081
9082    @Override
9083    public int getIntentVerificationStatus(String packageName, int userId) {
9084        synchronized (mPackages) {
9085            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9086        }
9087    }
9088
9089    @Override
9090    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9091        boolean result = false;
9092        synchronized (mPackages) {
9093            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9094        }
9095        scheduleWritePackageRestrictionsLocked(userId);
9096        return result;
9097    }
9098
9099    @Override
9100    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9101        synchronized (mPackages) {
9102            return mSettings.getIntentFilterVerificationsLPr(packageName);
9103        }
9104    }
9105
9106    @Override
9107    public List<IntentFilter> getAllIntentFilters(String packageName) {
9108        if (TextUtils.isEmpty(packageName)) {
9109            return Collections.<IntentFilter>emptyList();
9110        }
9111        synchronized (mPackages) {
9112            PackageParser.Package pkg = mPackages.get(packageName);
9113            if (pkg == null || pkg.activities == null) {
9114                return Collections.<IntentFilter>emptyList();
9115            }
9116            final int count = pkg.activities.size();
9117            ArrayList<IntentFilter> result = new ArrayList<>();
9118            for (int n=0; n<count; n++) {
9119                PackageParser.Activity activity = pkg.activities.get(n);
9120                if (activity.intents != null || activity.intents.size() > 0) {
9121                    result.addAll(activity.intents);
9122                }
9123            }
9124            return result;
9125        }
9126    }
9127
9128    @Override
9129    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9130        synchronized (mPackages) {
9131            return mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9132        }
9133    }
9134
9135    @Override
9136    public String getDefaultBrowserPackageName(int userId) {
9137        synchronized (mPackages) {
9138            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9139        }
9140    }
9141
9142    /**
9143     * Get the "allow unknown sources" setting.
9144     *
9145     * @return the current "allow unknown sources" setting
9146     */
9147    private int getUnknownSourcesSettings() {
9148        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9149                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9150                -1);
9151    }
9152
9153    @Override
9154    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9155        final int uid = Binder.getCallingUid();
9156        // writer
9157        synchronized (mPackages) {
9158            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9159            if (targetPackageSetting == null) {
9160                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9161            }
9162
9163            PackageSetting installerPackageSetting;
9164            if (installerPackageName != null) {
9165                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9166                if (installerPackageSetting == null) {
9167                    throw new IllegalArgumentException("Unknown installer package: "
9168                            + installerPackageName);
9169                }
9170            } else {
9171                installerPackageSetting = null;
9172            }
9173
9174            Signature[] callerSignature;
9175            Object obj = mSettings.getUserIdLPr(uid);
9176            if (obj != null) {
9177                if (obj instanceof SharedUserSetting) {
9178                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9179                } else if (obj instanceof PackageSetting) {
9180                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9181                } else {
9182                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9183                }
9184            } else {
9185                throw new SecurityException("Unknown calling uid " + uid);
9186            }
9187
9188            // Verify: can't set installerPackageName to a package that is
9189            // not signed with the same cert as the caller.
9190            if (installerPackageSetting != null) {
9191                if (compareSignatures(callerSignature,
9192                        installerPackageSetting.signatures.mSignatures)
9193                        != PackageManager.SIGNATURE_MATCH) {
9194                    throw new SecurityException(
9195                            "Caller does not have same cert as new installer package "
9196                            + installerPackageName);
9197                }
9198            }
9199
9200            // Verify: if target already has an installer package, it must
9201            // be signed with the same cert as the caller.
9202            if (targetPackageSetting.installerPackageName != null) {
9203                PackageSetting setting = mSettings.mPackages.get(
9204                        targetPackageSetting.installerPackageName);
9205                // If the currently set package isn't valid, then it's always
9206                // okay to change it.
9207                if (setting != null) {
9208                    if (compareSignatures(callerSignature,
9209                            setting.signatures.mSignatures)
9210                            != PackageManager.SIGNATURE_MATCH) {
9211                        throw new SecurityException(
9212                                "Caller does not have same cert as old installer package "
9213                                + targetPackageSetting.installerPackageName);
9214                    }
9215                }
9216            }
9217
9218            // Okay!
9219            targetPackageSetting.installerPackageName = installerPackageName;
9220            scheduleWriteSettingsLocked();
9221        }
9222    }
9223
9224    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9225        // Queue up an async operation since the package installation may take a little while.
9226        mHandler.post(new Runnable() {
9227            public void run() {
9228                mHandler.removeCallbacks(this);
9229                 // Result object to be returned
9230                PackageInstalledInfo res = new PackageInstalledInfo();
9231                res.returnCode = currentStatus;
9232                res.uid = -1;
9233                res.pkg = null;
9234                res.removedInfo = new PackageRemovedInfo();
9235                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9236                    args.doPreInstall(res.returnCode);
9237                    synchronized (mInstallLock) {
9238                        installPackageLI(args, res);
9239                    }
9240                    args.doPostInstall(res.returnCode, res.uid);
9241                }
9242
9243                // A restore should be performed at this point if (a) the install
9244                // succeeded, (b) the operation is not an update, and (c) the new
9245                // package has not opted out of backup participation.
9246                final boolean update = res.removedInfo.removedPackage != null;
9247                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9248                boolean doRestore = !update
9249                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9250
9251                // Set up the post-install work request bookkeeping.  This will be used
9252                // and cleaned up by the post-install event handling regardless of whether
9253                // there's a restore pass performed.  Token values are >= 1.
9254                int token;
9255                if (mNextInstallToken < 0) mNextInstallToken = 1;
9256                token = mNextInstallToken++;
9257
9258                PostInstallData data = new PostInstallData(args, res);
9259                mRunningInstalls.put(token, data);
9260                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9261
9262                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9263                    // Pass responsibility to the Backup Manager.  It will perform a
9264                    // restore if appropriate, then pass responsibility back to the
9265                    // Package Manager to run the post-install observer callbacks
9266                    // and broadcasts.
9267                    IBackupManager bm = IBackupManager.Stub.asInterface(
9268                            ServiceManager.getService(Context.BACKUP_SERVICE));
9269                    if (bm != null) {
9270                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9271                                + " to BM for possible restore");
9272                        try {
9273                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9274                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9275                            } else {
9276                                doRestore = false;
9277                            }
9278                        } catch (RemoteException e) {
9279                            // can't happen; the backup manager is local
9280                        } catch (Exception e) {
9281                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9282                            doRestore = false;
9283                        }
9284                    } else {
9285                        Slog.e(TAG, "Backup Manager not found!");
9286                        doRestore = false;
9287                    }
9288                }
9289
9290                if (!doRestore) {
9291                    // No restore possible, or the Backup Manager was mysteriously not
9292                    // available -- just fire the post-install work request directly.
9293                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9294                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9295                    mHandler.sendMessage(msg);
9296                }
9297            }
9298        });
9299    }
9300
9301    private abstract class HandlerParams {
9302        private static final int MAX_RETRIES = 4;
9303
9304        /**
9305         * Number of times startCopy() has been attempted and had a non-fatal
9306         * error.
9307         */
9308        private int mRetries = 0;
9309
9310        /** User handle for the user requesting the information or installation. */
9311        private final UserHandle mUser;
9312
9313        HandlerParams(UserHandle user) {
9314            mUser = user;
9315        }
9316
9317        UserHandle getUser() {
9318            return mUser;
9319        }
9320
9321        final boolean startCopy() {
9322            boolean res;
9323            try {
9324                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9325
9326                if (++mRetries > MAX_RETRIES) {
9327                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9328                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9329                    handleServiceError();
9330                    return false;
9331                } else {
9332                    handleStartCopy();
9333                    res = true;
9334                }
9335            } catch (RemoteException e) {
9336                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9337                mHandler.sendEmptyMessage(MCS_RECONNECT);
9338                res = false;
9339            }
9340            handleReturnCode();
9341            return res;
9342        }
9343
9344        final void serviceError() {
9345            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9346            handleServiceError();
9347            handleReturnCode();
9348        }
9349
9350        abstract void handleStartCopy() throws RemoteException;
9351        abstract void handleServiceError();
9352        abstract void handleReturnCode();
9353    }
9354
9355    class MeasureParams extends HandlerParams {
9356        private final PackageStats mStats;
9357        private boolean mSuccess;
9358
9359        private final IPackageStatsObserver mObserver;
9360
9361        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9362            super(new UserHandle(stats.userHandle));
9363            mObserver = observer;
9364            mStats = stats;
9365        }
9366
9367        @Override
9368        public String toString() {
9369            return "MeasureParams{"
9370                + Integer.toHexString(System.identityHashCode(this))
9371                + " " + mStats.packageName + "}";
9372        }
9373
9374        @Override
9375        void handleStartCopy() throws RemoteException {
9376            synchronized (mInstallLock) {
9377                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9378            }
9379
9380            if (mSuccess) {
9381                final boolean mounted;
9382                if (Environment.isExternalStorageEmulated()) {
9383                    mounted = true;
9384                } else {
9385                    final String status = Environment.getExternalStorageState();
9386                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9387                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9388                }
9389
9390                if (mounted) {
9391                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9392
9393                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9394                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9395
9396                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9397                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9398
9399                    // Always subtract cache size, since it's a subdirectory
9400                    mStats.externalDataSize -= mStats.externalCacheSize;
9401
9402                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9403                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9404
9405                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9406                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9407                }
9408            }
9409        }
9410
9411        @Override
9412        void handleReturnCode() {
9413            if (mObserver != null) {
9414                try {
9415                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9416                } catch (RemoteException e) {
9417                    Slog.i(TAG, "Observer no longer exists.");
9418                }
9419            }
9420        }
9421
9422        @Override
9423        void handleServiceError() {
9424            Slog.e(TAG, "Could not measure application " + mStats.packageName
9425                            + " external storage");
9426        }
9427    }
9428
9429    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9430            throws RemoteException {
9431        long result = 0;
9432        for (File path : paths) {
9433            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9434        }
9435        return result;
9436    }
9437
9438    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9439        for (File path : paths) {
9440            try {
9441                mcs.clearDirectory(path.getAbsolutePath());
9442            } catch (RemoteException e) {
9443            }
9444        }
9445    }
9446
9447    static class OriginInfo {
9448        /**
9449         * Location where install is coming from, before it has been
9450         * copied/renamed into place. This could be a single monolithic APK
9451         * file, or a cluster directory. This location may be untrusted.
9452         */
9453        final File file;
9454        final String cid;
9455
9456        /**
9457         * Flag indicating that {@link #file} or {@link #cid} has already been
9458         * staged, meaning downstream users don't need to defensively copy the
9459         * contents.
9460         */
9461        final boolean staged;
9462
9463        /**
9464         * Flag indicating that {@link #file} or {@link #cid} is an already
9465         * installed app that is being moved.
9466         */
9467        final boolean existing;
9468
9469        final String resolvedPath;
9470        final File resolvedFile;
9471
9472        static OriginInfo fromNothing() {
9473            return new OriginInfo(null, null, false, false);
9474        }
9475
9476        static OriginInfo fromUntrustedFile(File file) {
9477            return new OriginInfo(file, null, false, false);
9478        }
9479
9480        static OriginInfo fromExistingFile(File file) {
9481            return new OriginInfo(file, null, false, true);
9482        }
9483
9484        static OriginInfo fromStagedFile(File file) {
9485            return new OriginInfo(file, null, true, false);
9486        }
9487
9488        static OriginInfo fromStagedContainer(String cid) {
9489            return new OriginInfo(null, cid, true, false);
9490        }
9491
9492        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9493            this.file = file;
9494            this.cid = cid;
9495            this.staged = staged;
9496            this.existing = existing;
9497
9498            if (cid != null) {
9499                resolvedPath = PackageHelper.getSdDir(cid);
9500                resolvedFile = new File(resolvedPath);
9501            } else if (file != null) {
9502                resolvedPath = file.getAbsolutePath();
9503                resolvedFile = file;
9504            } else {
9505                resolvedPath = null;
9506                resolvedFile = null;
9507            }
9508        }
9509    }
9510
9511    class InstallParams extends HandlerParams {
9512        final OriginInfo origin;
9513        final IPackageInstallObserver2 observer;
9514        int installFlags;
9515        final String installerPackageName;
9516        final String volumeUuid;
9517        final VerificationParams verificationParams;
9518        private InstallArgs mArgs;
9519        private int mRet;
9520        final String packageAbiOverride;
9521
9522        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9523                String installerPackageName, String volumeUuid,
9524                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9525            super(user);
9526            this.origin = origin;
9527            this.observer = observer;
9528            this.installFlags = installFlags;
9529            this.installerPackageName = installerPackageName;
9530            this.volumeUuid = volumeUuid;
9531            this.verificationParams = verificationParams;
9532            this.packageAbiOverride = packageAbiOverride;
9533        }
9534
9535        @Override
9536        public String toString() {
9537            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9538                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9539        }
9540
9541        public ManifestDigest getManifestDigest() {
9542            if (verificationParams == null) {
9543                return null;
9544            }
9545            return verificationParams.getManifestDigest();
9546        }
9547
9548        private int installLocationPolicy(PackageInfoLite pkgLite) {
9549            String packageName = pkgLite.packageName;
9550            int installLocation = pkgLite.installLocation;
9551            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9552            // reader
9553            synchronized (mPackages) {
9554                PackageParser.Package pkg = mPackages.get(packageName);
9555                if (pkg != null) {
9556                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9557                        // Check for downgrading.
9558                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9559                            try {
9560                                checkDowngrade(pkg, pkgLite);
9561                            } catch (PackageManagerException e) {
9562                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9563                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9564                            }
9565                        }
9566                        // Check for updated system application.
9567                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9568                            if (onSd) {
9569                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9570                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9571                            }
9572                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9573                        } else {
9574                            if (onSd) {
9575                                // Install flag overrides everything.
9576                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9577                            }
9578                            // If current upgrade specifies particular preference
9579                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9580                                // Application explicitly specified internal.
9581                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9582                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9583                                // App explictly prefers external. Let policy decide
9584                            } else {
9585                                // Prefer previous location
9586                                if (isExternal(pkg)) {
9587                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9588                                }
9589                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9590                            }
9591                        }
9592                    } else {
9593                        // Invalid install. Return error code
9594                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9595                    }
9596                }
9597            }
9598            // All the special cases have been taken care of.
9599            // Return result based on recommended install location.
9600            if (onSd) {
9601                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9602            }
9603            return pkgLite.recommendedInstallLocation;
9604        }
9605
9606        /*
9607         * Invoke remote method to get package information and install
9608         * location values. Override install location based on default
9609         * policy if needed and then create install arguments based
9610         * on the install location.
9611         */
9612        public void handleStartCopy() throws RemoteException {
9613            int ret = PackageManager.INSTALL_SUCCEEDED;
9614
9615            // If we're already staged, we've firmly committed to an install location
9616            if (origin.staged) {
9617                if (origin.file != null) {
9618                    installFlags |= PackageManager.INSTALL_INTERNAL;
9619                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9620                } else if (origin.cid != null) {
9621                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9622                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9623                } else {
9624                    throw new IllegalStateException("Invalid stage location");
9625                }
9626            }
9627
9628            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9629            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9630
9631            PackageInfoLite pkgLite = null;
9632
9633            if (onInt && onSd) {
9634                // Check if both bits are set.
9635                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9636                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9637            } else {
9638                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9639                        packageAbiOverride);
9640
9641                /*
9642                 * If we have too little free space, try to free cache
9643                 * before giving up.
9644                 */
9645                if (!origin.staged && pkgLite.recommendedInstallLocation
9646                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9647                    // TODO: focus freeing disk space on the target device
9648                    final StorageManager storage = StorageManager.from(mContext);
9649                    final long lowThreshold = storage.getStorageLowBytes(
9650                            Environment.getDataDirectory());
9651
9652                    final long sizeBytes = mContainerService.calculateInstalledSize(
9653                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9654
9655                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
9656                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9657                                installFlags, packageAbiOverride);
9658                    }
9659
9660                    /*
9661                     * The cache free must have deleted the file we
9662                     * downloaded to install.
9663                     *
9664                     * TODO: fix the "freeCache" call to not delete
9665                     *       the file we care about.
9666                     */
9667                    if (pkgLite.recommendedInstallLocation
9668                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9669                        pkgLite.recommendedInstallLocation
9670                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9671                    }
9672                }
9673            }
9674
9675            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9676                int loc = pkgLite.recommendedInstallLocation;
9677                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9678                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9679                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9680                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9681                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9682                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9683                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9684                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9685                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9686                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9687                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9688                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9689                } else {
9690                    // Override with defaults if needed.
9691                    loc = installLocationPolicy(pkgLite);
9692                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9693                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9694                    } else if (!onSd && !onInt) {
9695                        // Override install location with flags
9696                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9697                            // Set the flag to install on external media.
9698                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9699                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9700                        } else {
9701                            // Make sure the flag for installing on external
9702                            // media is unset
9703                            installFlags |= PackageManager.INSTALL_INTERNAL;
9704                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9705                        }
9706                    }
9707                }
9708            }
9709
9710            final InstallArgs args = createInstallArgs(this);
9711            mArgs = args;
9712
9713            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9714                 /*
9715                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9716                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9717                 */
9718                int userIdentifier = getUser().getIdentifier();
9719                if (userIdentifier == UserHandle.USER_ALL
9720                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9721                    userIdentifier = UserHandle.USER_OWNER;
9722                }
9723
9724                /*
9725                 * Determine if we have any installed package verifiers. If we
9726                 * do, then we'll defer to them to verify the packages.
9727                 */
9728                final int requiredUid = mRequiredVerifierPackage == null ? -1
9729                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9730                if (!origin.existing && requiredUid != -1
9731                        && isVerificationEnabled(userIdentifier, installFlags)) {
9732                    final Intent verification = new Intent(
9733                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9734                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9735                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9736                            PACKAGE_MIME_TYPE);
9737                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9738
9739                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9740                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9741                            0 /* TODO: Which userId? */);
9742
9743                    if (DEBUG_VERIFY) {
9744                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9745                                + verification.toString() + " with " + pkgLite.verifiers.length
9746                                + " optional verifiers");
9747                    }
9748
9749                    final int verificationId = mPendingVerificationToken++;
9750
9751                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9752
9753                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9754                            installerPackageName);
9755
9756                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9757                            installFlags);
9758
9759                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9760                            pkgLite.packageName);
9761
9762                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9763                            pkgLite.versionCode);
9764
9765                    if (verificationParams != null) {
9766                        if (verificationParams.getVerificationURI() != null) {
9767                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9768                                 verificationParams.getVerificationURI());
9769                        }
9770                        if (verificationParams.getOriginatingURI() != null) {
9771                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9772                                  verificationParams.getOriginatingURI());
9773                        }
9774                        if (verificationParams.getReferrer() != null) {
9775                            verification.putExtra(Intent.EXTRA_REFERRER,
9776                                  verificationParams.getReferrer());
9777                        }
9778                        if (verificationParams.getOriginatingUid() >= 0) {
9779                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9780                                  verificationParams.getOriginatingUid());
9781                        }
9782                        if (verificationParams.getInstallerUid() >= 0) {
9783                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9784                                  verificationParams.getInstallerUid());
9785                        }
9786                    }
9787
9788                    final PackageVerificationState verificationState = new PackageVerificationState(
9789                            requiredUid, args);
9790
9791                    mPendingVerification.append(verificationId, verificationState);
9792
9793                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9794                            receivers, verificationState);
9795
9796                    /*
9797                     * If any sufficient verifiers were listed in the package
9798                     * manifest, attempt to ask them.
9799                     */
9800                    if (sufficientVerifiers != null) {
9801                        final int N = sufficientVerifiers.size();
9802                        if (N == 0) {
9803                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9804                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9805                        } else {
9806                            for (int i = 0; i < N; i++) {
9807                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9808
9809                                final Intent sufficientIntent = new Intent(verification);
9810                                sufficientIntent.setComponent(verifierComponent);
9811
9812                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9813                            }
9814                        }
9815                    }
9816
9817                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9818                            mRequiredVerifierPackage, receivers);
9819                    if (ret == PackageManager.INSTALL_SUCCEEDED
9820                            && mRequiredVerifierPackage != null) {
9821                        /*
9822                         * Send the intent to the required verification agent,
9823                         * but only start the verification timeout after the
9824                         * target BroadcastReceivers have run.
9825                         */
9826                        verification.setComponent(requiredVerifierComponent);
9827                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9828                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9829                                new BroadcastReceiver() {
9830                                    @Override
9831                                    public void onReceive(Context context, Intent intent) {
9832                                        final Message msg = mHandler
9833                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9834                                        msg.arg1 = verificationId;
9835                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9836                                    }
9837                                }, null, 0, null, null);
9838
9839                        /*
9840                         * We don't want the copy to proceed until verification
9841                         * succeeds, so null out this field.
9842                         */
9843                        mArgs = null;
9844                    }
9845                } else {
9846                    /*
9847                     * No package verification is enabled, so immediately start
9848                     * the remote call to initiate copy using temporary file.
9849                     */
9850                    ret = args.copyApk(mContainerService, true);
9851                }
9852            }
9853
9854            mRet = ret;
9855        }
9856
9857        @Override
9858        void handleReturnCode() {
9859            // If mArgs is null, then MCS couldn't be reached. When it
9860            // reconnects, it will try again to install. At that point, this
9861            // will succeed.
9862            if (mArgs != null) {
9863                processPendingInstall(mArgs, mRet);
9864            }
9865        }
9866
9867        @Override
9868        void handleServiceError() {
9869            mArgs = createInstallArgs(this);
9870            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9871        }
9872
9873        public boolean isForwardLocked() {
9874            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9875        }
9876    }
9877
9878    /**
9879     * Used during creation of InstallArgs
9880     *
9881     * @param installFlags package installation flags
9882     * @return true if should be installed on external storage
9883     */
9884    private static boolean installOnExternalAsec(int installFlags) {
9885        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9886            return false;
9887        }
9888        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9889            return true;
9890        }
9891        return false;
9892    }
9893
9894    /**
9895     * Used during creation of InstallArgs
9896     *
9897     * @param installFlags package installation flags
9898     * @return true if should be installed as forward locked
9899     */
9900    private static boolean installForwardLocked(int installFlags) {
9901        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9902    }
9903
9904    private InstallArgs createInstallArgs(InstallParams params) {
9905        if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
9906            return new AsecInstallArgs(params);
9907        } else {
9908            return new FileInstallArgs(params);
9909        }
9910    }
9911
9912    /**
9913     * Create args that describe an existing installed package. Typically used
9914     * when cleaning up old installs, or used as a move source.
9915     */
9916    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9917            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9918        final boolean isInAsec;
9919        if (installOnExternalAsec(installFlags)) {
9920            /* Apps on SD card are always in ASEC containers. */
9921            isInAsec = true;
9922        } else if (installForwardLocked(installFlags)
9923                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9924            /*
9925             * Forward-locked apps are only in ASEC containers if they're the
9926             * new style
9927             */
9928            isInAsec = true;
9929        } else {
9930            isInAsec = false;
9931        }
9932
9933        if (isInAsec) {
9934            return new AsecInstallArgs(codePath, instructionSets,
9935                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
9936        } else {
9937            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9938                    instructionSets);
9939        }
9940    }
9941
9942    static abstract class InstallArgs {
9943        /** @see InstallParams#origin */
9944        final OriginInfo origin;
9945
9946        final IPackageInstallObserver2 observer;
9947        // Always refers to PackageManager flags only
9948        final int installFlags;
9949        final String installerPackageName;
9950        final String volumeUuid;
9951        final ManifestDigest manifestDigest;
9952        final UserHandle user;
9953        final String abiOverride;
9954
9955        // The list of instruction sets supported by this app. This is currently
9956        // only used during the rmdex() phase to clean up resources. We can get rid of this
9957        // if we move dex files under the common app path.
9958        /* nullable */ String[] instructionSets;
9959
9960        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9961                String installerPackageName, String volumeUuid, ManifestDigest manifestDigest,
9962                UserHandle user, String[] instructionSets, String abiOverride) {
9963            this.origin = origin;
9964            this.installFlags = installFlags;
9965            this.observer = observer;
9966            this.installerPackageName = installerPackageName;
9967            this.volumeUuid = volumeUuid;
9968            this.manifestDigest = manifestDigest;
9969            this.user = user;
9970            this.instructionSets = instructionSets;
9971            this.abiOverride = abiOverride;
9972        }
9973
9974        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9975        abstract int doPreInstall(int status);
9976
9977        /**
9978         * Rename package into final resting place. All paths on the given
9979         * scanned package should be updated to reflect the rename.
9980         */
9981        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9982        abstract int doPostInstall(int status, int uid);
9983
9984        /** @see PackageSettingBase#codePathString */
9985        abstract String getCodePath();
9986        /** @see PackageSettingBase#resourcePathString */
9987        abstract String getResourcePath();
9988        abstract String getLegacyNativeLibraryPath();
9989
9990        // Need installer lock especially for dex file removal.
9991        abstract void cleanUpResourcesLI();
9992        abstract boolean doPostDeleteLI(boolean delete);
9993        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9994
9995        /**
9996         * Called before the source arguments are copied. This is used mostly
9997         * for MoveParams when it needs to read the source file to put it in the
9998         * destination.
9999         */
10000        int doPreCopy() {
10001            return PackageManager.INSTALL_SUCCEEDED;
10002        }
10003
10004        /**
10005         * Called after the source arguments are copied. This is used mostly for
10006         * MoveParams when it needs to read the source file to put it in the
10007         * destination.
10008         *
10009         * @return
10010         */
10011        int doPostCopy(int uid) {
10012            return PackageManager.INSTALL_SUCCEEDED;
10013        }
10014
10015        protected boolean isFwdLocked() {
10016            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10017        }
10018
10019        protected boolean isExternalAsec() {
10020            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10021        }
10022
10023        UserHandle getUser() {
10024            return user;
10025        }
10026    }
10027
10028    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10029        if (!allCodePaths.isEmpty()) {
10030            if (instructionSets == null) {
10031                throw new IllegalStateException("instructionSet == null");
10032            }
10033            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10034            for (String codePath : allCodePaths) {
10035                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10036                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10037                    if (retCode < 0) {
10038                        Slog.w(TAG, "Couldn't remove dex file for package: "
10039                                + " at location " + codePath + ", retcode=" + retCode);
10040                        // we don't consider this to be a failure of the core package deletion
10041                    }
10042                }
10043            }
10044        }
10045    }
10046
10047    /**
10048     * Logic to handle installation of non-ASEC applications, including copying
10049     * and renaming logic.
10050     */
10051    class FileInstallArgs extends InstallArgs {
10052        private File codeFile;
10053        private File resourceFile;
10054        private File legacyNativeLibraryPath;
10055
10056        // Example topology:
10057        // /data/app/com.example/base.apk
10058        // /data/app/com.example/split_foo.apk
10059        // /data/app/com.example/lib/arm/libfoo.so
10060        // /data/app/com.example/lib/arm64/libfoo.so
10061        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10062
10063        /** New install */
10064        FileInstallArgs(InstallParams params) {
10065            super(params.origin, params.observer, params.installFlags,
10066                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10067                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10068            if (isFwdLocked()) {
10069                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10070            }
10071        }
10072
10073        /** Existing install */
10074        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
10075                String[] instructionSets) {
10076            super(OriginInfo.fromNothing(), null, 0, null, null, null, null, instructionSets, null);
10077            this.codeFile = (codePath != null) ? new File(codePath) : null;
10078            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10079            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
10080                    new File(legacyNativeLibraryPath) : null;
10081        }
10082
10083        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
10084            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
10085                    isFwdLocked(), abiOverride);
10086
10087            final StorageManager storage = StorageManager.from(mContext);
10088            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
10089        }
10090
10091        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10092            if (origin.staged) {
10093                Slog.d(TAG, origin.file + " already staged; skipping copy");
10094                codeFile = origin.file;
10095                resourceFile = origin.file;
10096                return PackageManager.INSTALL_SUCCEEDED;
10097            }
10098
10099            try {
10100                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10101                codeFile = tempDir;
10102                resourceFile = tempDir;
10103            } catch (IOException e) {
10104                Slog.w(TAG, "Failed to create copy file: " + e);
10105                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10106            }
10107
10108            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10109                @Override
10110                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10111                    if (!FileUtils.isValidExtFilename(name)) {
10112                        throw new IllegalArgumentException("Invalid filename: " + name);
10113                    }
10114                    try {
10115                        final File file = new File(codeFile, name);
10116                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10117                                O_RDWR | O_CREAT, 0644);
10118                        Os.chmod(file.getAbsolutePath(), 0644);
10119                        return new ParcelFileDescriptor(fd);
10120                    } catch (ErrnoException e) {
10121                        throw new RemoteException("Failed to open: " + e.getMessage());
10122                    }
10123                }
10124            };
10125
10126            int ret = PackageManager.INSTALL_SUCCEEDED;
10127            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10128            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10129                Slog.e(TAG, "Failed to copy package");
10130                return ret;
10131            }
10132
10133            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10134            NativeLibraryHelper.Handle handle = null;
10135            try {
10136                handle = NativeLibraryHelper.Handle.create(codeFile);
10137                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10138                        abiOverride);
10139            } catch (IOException e) {
10140                Slog.e(TAG, "Copying native libraries failed", e);
10141                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10142            } finally {
10143                IoUtils.closeQuietly(handle);
10144            }
10145
10146            return ret;
10147        }
10148
10149        int doPreInstall(int status) {
10150            if (status != PackageManager.INSTALL_SUCCEEDED) {
10151                cleanUp();
10152            }
10153            return status;
10154        }
10155
10156        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10157            if (status != PackageManager.INSTALL_SUCCEEDED) {
10158                cleanUp();
10159                return false;
10160            } else {
10161                final File targetDir = codeFile.getParentFile();
10162                final File beforeCodeFile = codeFile;
10163                final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10164
10165                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10166                try {
10167                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10168                } catch (ErrnoException e) {
10169                    Slog.d(TAG, "Failed to rename", e);
10170                    return false;
10171                }
10172
10173                if (!SELinux.restoreconRecursive(afterCodeFile)) {
10174                    Slog.d(TAG, "Failed to restorecon");
10175                    return false;
10176                }
10177
10178                // Reflect the rename internally
10179                codeFile = afterCodeFile;
10180                resourceFile = afterCodeFile;
10181
10182                // Reflect the rename in scanned details
10183                pkg.codePath = afterCodeFile.getAbsolutePath();
10184                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10185                        pkg.baseCodePath);
10186                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10187                        pkg.splitCodePaths);
10188
10189                // Reflect the rename in app info
10190                pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10191                pkg.applicationInfo.setCodePath(pkg.codePath);
10192                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10193                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10194                pkg.applicationInfo.setResourcePath(pkg.codePath);
10195                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10196                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10197
10198                return true;
10199            }
10200        }
10201
10202        int doPostInstall(int status, int uid) {
10203            if (status != PackageManager.INSTALL_SUCCEEDED) {
10204                cleanUp();
10205            }
10206            return status;
10207        }
10208
10209        @Override
10210        String getCodePath() {
10211            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10212        }
10213
10214        @Override
10215        String getResourcePath() {
10216            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10217        }
10218
10219        @Override
10220        String getLegacyNativeLibraryPath() {
10221            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
10222        }
10223
10224        private boolean cleanUp() {
10225            if (codeFile == null || !codeFile.exists()) {
10226                return false;
10227            }
10228
10229            if (codeFile.isDirectory()) {
10230                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10231            } else {
10232                codeFile.delete();
10233            }
10234
10235            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10236                resourceFile.delete();
10237            }
10238
10239            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
10240                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
10241                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
10242                }
10243                legacyNativeLibraryPath.delete();
10244            }
10245
10246            return true;
10247        }
10248
10249        void cleanUpResourcesLI() {
10250            // Try enumerating all code paths before deleting
10251            List<String> allCodePaths = Collections.EMPTY_LIST;
10252            if (codeFile != null && codeFile.exists()) {
10253                try {
10254                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10255                    allCodePaths = pkg.getAllCodePaths();
10256                } catch (PackageParserException e) {
10257                    // Ignored; we tried our best
10258                }
10259            }
10260
10261            cleanUp();
10262            removeDexFiles(allCodePaths, instructionSets);
10263        }
10264
10265        boolean doPostDeleteLI(boolean delete) {
10266            // XXX err, shouldn't we respect the delete flag?
10267            cleanUpResourcesLI();
10268            return true;
10269        }
10270    }
10271
10272    private boolean isAsecExternal(String cid) {
10273        final String asecPath = PackageHelper.getSdFilesystem(cid);
10274        return !asecPath.startsWith(mAsecInternalPath);
10275    }
10276
10277    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10278            PackageManagerException {
10279        if (copyRet < 0) {
10280            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10281                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10282                throw new PackageManagerException(copyRet, message);
10283            }
10284        }
10285    }
10286
10287    /**
10288     * Extract the MountService "container ID" from the full code path of an
10289     * .apk.
10290     */
10291    static String cidFromCodePath(String fullCodePath) {
10292        int eidx = fullCodePath.lastIndexOf("/");
10293        String subStr1 = fullCodePath.substring(0, eidx);
10294        int sidx = subStr1.lastIndexOf("/");
10295        return subStr1.substring(sidx+1, eidx);
10296    }
10297
10298    /**
10299     * Logic to handle installation of ASEC applications, including copying and
10300     * renaming logic.
10301     */
10302    class AsecInstallArgs extends InstallArgs {
10303        static final String RES_FILE_NAME = "pkg.apk";
10304        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10305
10306        String cid;
10307        String packagePath;
10308        String resourcePath;
10309        String legacyNativeLibraryDir;
10310
10311        /** New install */
10312        AsecInstallArgs(InstallParams params) {
10313            super(params.origin, params.observer, params.installFlags,
10314                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10315                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10316        }
10317
10318        /** Existing install */
10319        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10320                        boolean isExternal, boolean isForwardLocked) {
10321            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
10322                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10323                    instructionSets, null);
10324            // Hackily pretend we're still looking at a full code path
10325            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10326                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10327            }
10328
10329            // Extract cid from fullCodePath
10330            int eidx = fullCodePath.lastIndexOf("/");
10331            String subStr1 = fullCodePath.substring(0, eidx);
10332            int sidx = subStr1.lastIndexOf("/");
10333            cid = subStr1.substring(sidx+1, eidx);
10334            setMountPath(subStr1);
10335        }
10336
10337        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10338            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10339                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10340                    instructionSets, null);
10341            this.cid = cid;
10342            setMountPath(PackageHelper.getSdDir(cid));
10343        }
10344
10345        void createCopyFile() {
10346            cid = mInstallerService.allocateExternalStageCidLegacy();
10347        }
10348
10349        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
10350            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
10351                    abiOverride);
10352
10353            final File target;
10354            if (isExternalAsec()) {
10355                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
10356            } else {
10357                target = Environment.getDataDirectory();
10358            }
10359
10360            final StorageManager storage = StorageManager.from(mContext);
10361            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
10362        }
10363
10364        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10365            if (origin.staged) {
10366                Slog.d(TAG, origin.cid + " already staged; skipping copy");
10367                cid = origin.cid;
10368                setMountPath(PackageHelper.getSdDir(cid));
10369                return PackageManager.INSTALL_SUCCEEDED;
10370            }
10371
10372            if (temp) {
10373                createCopyFile();
10374            } else {
10375                /*
10376                 * Pre-emptively destroy the container since it's destroyed if
10377                 * copying fails due to it existing anyway.
10378                 */
10379                PackageHelper.destroySdDir(cid);
10380            }
10381
10382            final String newMountPath = imcs.copyPackageToContainer(
10383                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10384                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10385
10386            if (newMountPath != null) {
10387                setMountPath(newMountPath);
10388                return PackageManager.INSTALL_SUCCEEDED;
10389            } else {
10390                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10391            }
10392        }
10393
10394        @Override
10395        String getCodePath() {
10396            return packagePath;
10397        }
10398
10399        @Override
10400        String getResourcePath() {
10401            return resourcePath;
10402        }
10403
10404        @Override
10405        String getLegacyNativeLibraryPath() {
10406            return legacyNativeLibraryDir;
10407        }
10408
10409        int doPreInstall(int status) {
10410            if (status != PackageManager.INSTALL_SUCCEEDED) {
10411                // Destroy container
10412                PackageHelper.destroySdDir(cid);
10413            } else {
10414                boolean mounted = PackageHelper.isContainerMounted(cid);
10415                if (!mounted) {
10416                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10417                            Process.SYSTEM_UID);
10418                    if (newMountPath != null) {
10419                        setMountPath(newMountPath);
10420                    } else {
10421                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10422                    }
10423                }
10424            }
10425            return status;
10426        }
10427
10428        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10429            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10430            String newMountPath = null;
10431            if (PackageHelper.isContainerMounted(cid)) {
10432                // Unmount the container
10433                if (!PackageHelper.unMountSdDir(cid)) {
10434                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10435                    return false;
10436                }
10437            }
10438            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10439                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10440                        " which might be stale. Will try to clean up.");
10441                // Clean up the stale container and proceed to recreate.
10442                if (!PackageHelper.destroySdDir(newCacheId)) {
10443                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10444                    return false;
10445                }
10446                // Successfully cleaned up stale container. Try to rename again.
10447                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10448                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10449                            + " inspite of cleaning it up.");
10450                    return false;
10451                }
10452            }
10453            if (!PackageHelper.isContainerMounted(newCacheId)) {
10454                Slog.w(TAG, "Mounting container " + newCacheId);
10455                newMountPath = PackageHelper.mountSdDir(newCacheId,
10456                        getEncryptKey(), Process.SYSTEM_UID);
10457            } else {
10458                newMountPath = PackageHelper.getSdDir(newCacheId);
10459            }
10460            if (newMountPath == null) {
10461                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10462                return false;
10463            }
10464            Log.i(TAG, "Succesfully renamed " + cid +
10465                    " to " + newCacheId +
10466                    " at new path: " + newMountPath);
10467            cid = newCacheId;
10468
10469            final File beforeCodeFile = new File(packagePath);
10470            setMountPath(newMountPath);
10471            final File afterCodeFile = new File(packagePath);
10472
10473            // Reflect the rename in scanned details
10474            pkg.codePath = afterCodeFile.getAbsolutePath();
10475            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10476                    pkg.baseCodePath);
10477            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10478                    pkg.splitCodePaths);
10479
10480            // Reflect the rename in app info
10481            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10482            pkg.applicationInfo.setCodePath(pkg.codePath);
10483            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10484            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10485            pkg.applicationInfo.setResourcePath(pkg.codePath);
10486            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10487            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10488
10489            return true;
10490        }
10491
10492        private void setMountPath(String mountPath) {
10493            final File mountFile = new File(mountPath);
10494
10495            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10496            if (monolithicFile.exists()) {
10497                packagePath = monolithicFile.getAbsolutePath();
10498                if (isFwdLocked()) {
10499                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10500                } else {
10501                    resourcePath = packagePath;
10502                }
10503            } else {
10504                packagePath = mountFile.getAbsolutePath();
10505                resourcePath = packagePath;
10506            }
10507
10508            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
10509        }
10510
10511        int doPostInstall(int status, int uid) {
10512            if (status != PackageManager.INSTALL_SUCCEEDED) {
10513                cleanUp();
10514            } else {
10515                final int groupOwner;
10516                final String protectedFile;
10517                if (isFwdLocked()) {
10518                    groupOwner = UserHandle.getSharedAppGid(uid);
10519                    protectedFile = RES_FILE_NAME;
10520                } else {
10521                    groupOwner = -1;
10522                    protectedFile = null;
10523                }
10524
10525                if (uid < Process.FIRST_APPLICATION_UID
10526                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10527                    Slog.e(TAG, "Failed to finalize " + cid);
10528                    PackageHelper.destroySdDir(cid);
10529                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10530                }
10531
10532                boolean mounted = PackageHelper.isContainerMounted(cid);
10533                if (!mounted) {
10534                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10535                }
10536            }
10537            return status;
10538        }
10539
10540        private void cleanUp() {
10541            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10542
10543            // Destroy secure container
10544            PackageHelper.destroySdDir(cid);
10545        }
10546
10547        private List<String> getAllCodePaths() {
10548            final File codeFile = new File(getCodePath());
10549            if (codeFile != null && codeFile.exists()) {
10550                try {
10551                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10552                    return pkg.getAllCodePaths();
10553                } catch (PackageParserException e) {
10554                    // Ignored; we tried our best
10555                }
10556            }
10557            return Collections.EMPTY_LIST;
10558        }
10559
10560        void cleanUpResourcesLI() {
10561            // Enumerate all code paths before deleting
10562            cleanUpResourcesLI(getAllCodePaths());
10563        }
10564
10565        private void cleanUpResourcesLI(List<String> allCodePaths) {
10566            cleanUp();
10567            removeDexFiles(allCodePaths, instructionSets);
10568        }
10569
10570
10571
10572        String getPackageName() {
10573            return getAsecPackageName(cid);
10574        }
10575
10576        boolean doPostDeleteLI(boolean delete) {
10577            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10578            final List<String> allCodePaths = getAllCodePaths();
10579            boolean mounted = PackageHelper.isContainerMounted(cid);
10580            if (mounted) {
10581                // Unmount first
10582                if (PackageHelper.unMountSdDir(cid)) {
10583                    mounted = false;
10584                }
10585            }
10586            if (!mounted && delete) {
10587                cleanUpResourcesLI(allCodePaths);
10588            }
10589            return !mounted;
10590        }
10591
10592        @Override
10593        int doPreCopy() {
10594            if (isFwdLocked()) {
10595                if (!PackageHelper.fixSdPermissions(cid,
10596                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10597                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10598                }
10599            }
10600
10601            return PackageManager.INSTALL_SUCCEEDED;
10602        }
10603
10604        @Override
10605        int doPostCopy(int uid) {
10606            if (isFwdLocked()) {
10607                if (uid < Process.FIRST_APPLICATION_UID
10608                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10609                                RES_FILE_NAME)) {
10610                    Slog.e(TAG, "Failed to finalize " + cid);
10611                    PackageHelper.destroySdDir(cid);
10612                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10613                }
10614            }
10615
10616            return PackageManager.INSTALL_SUCCEEDED;
10617        }
10618    }
10619
10620    static String getAsecPackageName(String packageCid) {
10621        int idx = packageCid.lastIndexOf("-");
10622        if (idx == -1) {
10623            return packageCid;
10624        }
10625        return packageCid.substring(0, idx);
10626    }
10627
10628    // Utility method used to create code paths based on package name and available index.
10629    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
10630        String idxStr = "";
10631        int idx = 1;
10632        // Fall back to default value of idx=1 if prefix is not
10633        // part of oldCodePath
10634        if (oldCodePath != null) {
10635            String subStr = oldCodePath;
10636            // Drop the suffix right away
10637            if (suffix != null && subStr.endsWith(suffix)) {
10638                subStr = subStr.substring(0, subStr.length() - suffix.length());
10639            }
10640            // If oldCodePath already contains prefix find out the
10641            // ending index to either increment or decrement.
10642            int sidx = subStr.lastIndexOf(prefix);
10643            if (sidx != -1) {
10644                subStr = subStr.substring(sidx + prefix.length());
10645                if (subStr != null) {
10646                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10647                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10648                    }
10649                    try {
10650                        idx = Integer.parseInt(subStr);
10651                        if (idx <= 1) {
10652                            idx++;
10653                        } else {
10654                            idx--;
10655                        }
10656                    } catch(NumberFormatException e) {
10657                    }
10658                }
10659            }
10660        }
10661        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10662        return prefix + idxStr;
10663    }
10664
10665    private File getNextCodePath(File targetDir, String packageName) {
10666        int suffix = 1;
10667        File result;
10668        do {
10669            result = new File(targetDir, packageName + "-" + suffix);
10670            suffix++;
10671        } while (result.exists());
10672        return result;
10673    }
10674
10675    // Utility method that returns the relative package path with respect
10676    // to the installation directory. Like say for /data/data/com.test-1.apk
10677    // string com.test-1 is returned.
10678    static String deriveCodePathName(String codePath) {
10679        if (codePath == null) {
10680            return null;
10681        }
10682        final File codeFile = new File(codePath);
10683        final String name = codeFile.getName();
10684        if (codeFile.isDirectory()) {
10685            return name;
10686        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10687            final int lastDot = name.lastIndexOf('.');
10688            return name.substring(0, lastDot);
10689        } else {
10690            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10691            return null;
10692        }
10693    }
10694
10695    class PackageInstalledInfo {
10696        String name;
10697        int uid;
10698        // The set of users that originally had this package installed.
10699        int[] origUsers;
10700        // The set of users that now have this package installed.
10701        int[] newUsers;
10702        PackageParser.Package pkg;
10703        int returnCode;
10704        String returnMsg;
10705        PackageRemovedInfo removedInfo;
10706
10707        public void setError(int code, String msg) {
10708            returnCode = code;
10709            returnMsg = msg;
10710            Slog.w(TAG, msg);
10711        }
10712
10713        public void setError(String msg, PackageParserException e) {
10714            returnCode = e.error;
10715            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10716            Slog.w(TAG, msg, e);
10717        }
10718
10719        public void setError(String msg, PackageManagerException e) {
10720            returnCode = e.error;
10721            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10722            Slog.w(TAG, msg, e);
10723        }
10724
10725        // In some error cases we want to convey more info back to the observer
10726        String origPackage;
10727        String origPermission;
10728    }
10729
10730    /*
10731     * Install a non-existing package.
10732     */
10733    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
10734            UserHandle user, String installerPackageName, String volumeUuid,
10735            PackageInstalledInfo res) {
10736        // Remember this for later, in case we need to rollback this install
10737        String pkgName = pkg.packageName;
10738
10739        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10740        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
10741                UserHandle.USER_OWNER).exists();
10742        synchronized(mPackages) {
10743            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10744                // A package with the same name is already installed, though
10745                // it has been renamed to an older name.  The package we
10746                // are trying to install should be installed as an update to
10747                // the existing one, but that has not been requested, so bail.
10748                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10749                        + " without first uninstalling package running as "
10750                        + mSettings.mRenamedPackages.get(pkgName));
10751                return;
10752            }
10753            if (mPackages.containsKey(pkgName)) {
10754                // Don't allow installation over an existing package with the same name.
10755                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10756                        + " without first uninstalling.");
10757                return;
10758            }
10759        }
10760
10761        try {
10762            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10763                    System.currentTimeMillis(), user);
10764
10765            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
10766            // delete the partially installed application. the data directory will have to be
10767            // restored if it was already existing
10768            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10769                // remove package from internal structures.  Note that we want deletePackageX to
10770                // delete the package data and cache directories that it created in
10771                // scanPackageLocked, unless those directories existed before we even tried to
10772                // install.
10773                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10774                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10775                                res.removedInfo, true);
10776            }
10777
10778        } catch (PackageManagerException e) {
10779            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10780        }
10781    }
10782
10783    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10784        // Upgrade keysets are being used.  Determine if new package has a superset of the
10785        // required keys.
10786        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10787        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10788        for (int i = 0; i < upgradeKeySets.length; i++) {
10789            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10790            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10791                return true;
10792            }
10793        }
10794        return false;
10795    }
10796
10797    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
10798            UserHandle user, String installerPackageName, String volumeUuid,
10799            PackageInstalledInfo res) {
10800        PackageParser.Package oldPackage;
10801        String pkgName = pkg.packageName;
10802        int[] allUsers;
10803        boolean[] perUserInstalled;
10804
10805        // First find the old package info and check signatures
10806        synchronized(mPackages) {
10807            oldPackage = mPackages.get(pkgName);
10808            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10809            PackageSetting ps = mSettings.mPackages.get(pkgName);
10810            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10811                // default to original signature matching
10812                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10813                    != PackageManager.SIGNATURE_MATCH) {
10814                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10815                            "New package has a different signature: " + pkgName);
10816                    return;
10817                }
10818            } else {
10819                if(!checkUpgradeKeySetLP(ps, pkg)) {
10820                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10821                            "New package not signed by keys specified by upgrade-keysets: "
10822                            + pkgName);
10823                    return;
10824                }
10825            }
10826
10827            // In case of rollback, remember per-user/profile install state
10828            allUsers = sUserManager.getUserIds();
10829            perUserInstalled = new boolean[allUsers.length];
10830            for (int i = 0; i < allUsers.length; i++) {
10831                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10832            }
10833        }
10834
10835        boolean sysPkg = (isSystemApp(oldPackage));
10836        if (sysPkg) {
10837            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10838                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
10839        } else {
10840            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10841                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
10842        }
10843    }
10844
10845    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10846            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10847            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
10848            String volumeUuid, PackageInstalledInfo res) {
10849        String pkgName = deletedPackage.packageName;
10850        boolean deletedPkg = true;
10851        boolean updatedSettings = false;
10852
10853        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10854                + deletedPackage);
10855        long origUpdateTime;
10856        if (pkg.mExtras != null) {
10857            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10858        } else {
10859            origUpdateTime = 0;
10860        }
10861
10862        // First delete the existing package while retaining the data directory
10863        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10864                res.removedInfo, true)) {
10865            // If the existing package wasn't successfully deleted
10866            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10867            deletedPkg = false;
10868        } else {
10869            // Successfully deleted the old package; proceed with replace.
10870
10871            // If deleted package lived in a container, give users a chance to
10872            // relinquish resources before killing.
10873            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
10874                if (DEBUG_INSTALL) {
10875                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10876                }
10877                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10878                final ArrayList<String> pkgList = new ArrayList<String>(1);
10879                pkgList.add(deletedPackage.applicationInfo.packageName);
10880                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10881            }
10882
10883            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
10884            try {
10885                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10886                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10887                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
10888                        perUserInstalled, res, user);
10889                updatedSettings = true;
10890            } catch (PackageManagerException e) {
10891                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10892            }
10893        }
10894
10895        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10896            // remove package from internal structures.  Note that we want deletePackageX to
10897            // delete the package data and cache directories that it created in
10898            // scanPackageLocked, unless those directories existed before we even tried to
10899            // install.
10900            if(updatedSettings) {
10901                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10902                deletePackageLI(
10903                        pkgName, null, true, allUsers, perUserInstalled,
10904                        PackageManager.DELETE_KEEP_DATA,
10905                                res.removedInfo, true);
10906            }
10907            // Since we failed to install the new package we need to restore the old
10908            // package that we deleted.
10909            if (deletedPkg) {
10910                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10911                File restoreFile = new File(deletedPackage.codePath);
10912                // Parse old package
10913                boolean oldExternal = isExternal(deletedPackage);
10914                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10915                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10916                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
10917                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10918                try {
10919                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10920                } catch (PackageManagerException e) {
10921                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10922                            + e.getMessage());
10923                    return;
10924                }
10925                // Restore of old package succeeded. Update permissions.
10926                // writer
10927                synchronized (mPackages) {
10928                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10929                            UPDATE_PERMISSIONS_ALL);
10930                    // can downgrade to reader
10931                    mSettings.writeLPr();
10932                }
10933                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10934            }
10935        }
10936    }
10937
10938    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10939            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10940            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
10941            String volumeUuid, PackageInstalledInfo res) {
10942        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10943                + ", old=" + deletedPackage);
10944        boolean disabledSystem = false;
10945        boolean updatedSettings = false;
10946        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10947        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
10948                != 0) {
10949            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10950        }
10951        String packageName = deletedPackage.packageName;
10952        if (packageName == null) {
10953            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10954                    "Attempt to delete null packageName.");
10955            return;
10956        }
10957        PackageParser.Package oldPkg;
10958        PackageSetting oldPkgSetting;
10959        // reader
10960        synchronized (mPackages) {
10961            oldPkg = mPackages.get(packageName);
10962            oldPkgSetting = mSettings.mPackages.get(packageName);
10963            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10964                    (oldPkgSetting == null)) {
10965                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10966                        "Couldn't find package:" + packageName + " information");
10967                return;
10968            }
10969        }
10970
10971        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10972
10973        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10974        res.removedInfo.removedPackage = packageName;
10975        // Remove existing system package
10976        removePackageLI(oldPkgSetting, true);
10977        // writer
10978        synchronized (mPackages) {
10979            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10980            if (!disabledSystem && deletedPackage != null) {
10981                // We didn't need to disable the .apk as a current system package,
10982                // which means we are replacing another update that is already
10983                // installed.  We need to make sure to delete the older one's .apk.
10984                res.removedInfo.args = createInstallArgsForExisting(0,
10985                        deletedPackage.applicationInfo.getCodePath(),
10986                        deletedPackage.applicationInfo.getResourcePath(),
10987                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10988                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10989            } else {
10990                res.removedInfo.args = null;
10991            }
10992        }
10993
10994        // Successfully disabled the old package. Now proceed with re-installation
10995        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
10996
10997        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10998        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10999
11000        PackageParser.Package newPackage = null;
11001        try {
11002            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11003            if (newPackage.mExtras != null) {
11004                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11005                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11006                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11007
11008                // is the update attempting to change shared user? that isn't going to work...
11009                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11010                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11011                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11012                            + " to " + newPkgSetting.sharedUser);
11013                    updatedSettings = true;
11014                }
11015            }
11016
11017            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11018                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11019                        perUserInstalled, res, user);
11020                updatedSettings = true;
11021            }
11022
11023        } catch (PackageManagerException e) {
11024            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11025        }
11026
11027        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11028            // Re installation failed. Restore old information
11029            // Remove new pkg information
11030            if (newPackage != null) {
11031                removeInstalledPackageLI(newPackage, true);
11032            }
11033            // Add back the old system package
11034            try {
11035                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11036            } catch (PackageManagerException e) {
11037                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11038            }
11039            // Restore the old system information in Settings
11040            synchronized (mPackages) {
11041                if (disabledSystem) {
11042                    mSettings.enableSystemPackageLPw(packageName);
11043                }
11044                if (updatedSettings) {
11045                    mSettings.setInstallerPackageName(packageName,
11046                            oldPkgSetting.installerPackageName);
11047                }
11048                mSettings.writeLPr();
11049            }
11050        }
11051    }
11052
11053    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11054            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11055            UserHandle user) {
11056        String pkgName = newPackage.packageName;
11057        synchronized (mPackages) {
11058            //write settings. the installStatus will be incomplete at this stage.
11059            //note that the new package setting would have already been
11060            //added to mPackages. It hasn't been persisted yet.
11061            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11062            mSettings.writeLPr();
11063        }
11064
11065        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11066
11067        synchronized (mPackages) {
11068            updatePermissionsLPw(newPackage.packageName, newPackage,
11069                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11070                            ? UPDATE_PERMISSIONS_ALL : 0));
11071            // For system-bundled packages, we assume that installing an upgraded version
11072            // of the package implies that the user actually wants to run that new code,
11073            // so we enable the package.
11074            PackageSetting ps = mSettings.mPackages.get(pkgName);
11075            if (ps != null) {
11076                if (isSystemApp(newPackage)) {
11077                    // NB: implicit assumption that system package upgrades apply to all users
11078                    if (DEBUG_INSTALL) {
11079                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11080                    }
11081                    if (res.origUsers != null) {
11082                        for (int userHandle : res.origUsers) {
11083                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11084                                    userHandle, installerPackageName);
11085                        }
11086                    }
11087                    // Also convey the prior install/uninstall state
11088                    if (allUsers != null && perUserInstalled != null) {
11089                        for (int i = 0; i < allUsers.length; i++) {
11090                            if (DEBUG_INSTALL) {
11091                                Slog.d(TAG, "    user " + allUsers[i]
11092                                        + " => " + perUserInstalled[i]);
11093                            }
11094                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11095                        }
11096                        // these install state changes will be persisted in the
11097                        // upcoming call to mSettings.writeLPr().
11098                    }
11099                }
11100                // It's implied that when a user requests installation, they want the app to be
11101                // installed and enabled.
11102                int userId = user.getIdentifier();
11103                if (userId != UserHandle.USER_ALL) {
11104                    ps.setInstalled(true, userId);
11105                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11106                }
11107            }
11108            res.name = pkgName;
11109            res.uid = newPackage.applicationInfo.uid;
11110            res.pkg = newPackage;
11111            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11112            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11113            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11114            //to update install status
11115            mSettings.writeLPr();
11116        }
11117    }
11118
11119    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11120        final int installFlags = args.installFlags;
11121        final String installerPackageName = args.installerPackageName;
11122        final String volumeUuid = args.volumeUuid;
11123        final File tmpPackageFile = new File(args.getCodePath());
11124        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11125        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11126                || (args.volumeUuid != null));
11127        boolean replace = false;
11128        int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
11129        // Result object to be returned
11130        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11131
11132        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11133        // Retrieve PackageSettings and parse package
11134        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11135                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11136                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11137        PackageParser pp = new PackageParser();
11138        pp.setSeparateProcesses(mSeparateProcesses);
11139        pp.setDisplayMetrics(mMetrics);
11140
11141        final PackageParser.Package pkg;
11142        try {
11143            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11144        } catch (PackageParserException e) {
11145            res.setError("Failed parse during installPackageLI", e);
11146            return;
11147        }
11148
11149        // Mark that we have an install time CPU ABI override.
11150        pkg.cpuAbiOverride = args.abiOverride;
11151
11152        String pkgName = res.name = pkg.packageName;
11153        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11154            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11155                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11156                return;
11157            }
11158        }
11159
11160        try {
11161            pp.collectCertificates(pkg, parseFlags);
11162            pp.collectManifestDigest(pkg);
11163        } catch (PackageParserException e) {
11164            res.setError("Failed collect during installPackageLI", e);
11165            return;
11166        }
11167
11168        /* If the installer passed in a manifest digest, compare it now. */
11169        if (args.manifestDigest != null) {
11170            if (DEBUG_INSTALL) {
11171                final String parsedManifest = pkg.manifestDigest == null ? "null"
11172                        : pkg.manifestDigest.toString();
11173                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11174                        + parsedManifest);
11175            }
11176
11177            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11178                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11179                return;
11180            }
11181        } else if (DEBUG_INSTALL) {
11182            final String parsedManifest = pkg.manifestDigest == null
11183                    ? "null" : pkg.manifestDigest.toString();
11184            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11185        }
11186
11187        // Get rid of all references to package scan path via parser.
11188        pp = null;
11189        String oldCodePath = null;
11190        boolean systemApp = false;
11191        synchronized (mPackages) {
11192            // Check if installing already existing package
11193            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11194                String oldName = mSettings.mRenamedPackages.get(pkgName);
11195                if (pkg.mOriginalPackages != null
11196                        && pkg.mOriginalPackages.contains(oldName)
11197                        && mPackages.containsKey(oldName)) {
11198                    // This package is derived from an original package,
11199                    // and this device has been updating from that original
11200                    // name.  We must continue using the original name, so
11201                    // rename the new package here.
11202                    pkg.setPackageName(oldName);
11203                    pkgName = pkg.packageName;
11204                    replace = true;
11205                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11206                            + oldName + " pkgName=" + pkgName);
11207                } else if (mPackages.containsKey(pkgName)) {
11208                    // This package, under its official name, already exists
11209                    // on the device; we should replace it.
11210                    replace = true;
11211                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11212                }
11213            }
11214
11215            PackageSetting ps = mSettings.mPackages.get(pkgName);
11216            if (ps != null) {
11217                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11218
11219                // Quick sanity check that we're signed correctly if updating;
11220                // we'll check this again later when scanning, but we want to
11221                // bail early here before tripping over redefined permissions.
11222                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11223                    try {
11224                        verifySignaturesLP(ps, pkg);
11225                    } catch (PackageManagerException e) {
11226                        res.setError(e.error, e.getMessage());
11227                        return;
11228                    }
11229                } else {
11230                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11231                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11232                                + pkg.packageName + " upgrade keys do not match the "
11233                                + "previously installed version");
11234                        return;
11235                    }
11236                }
11237
11238                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11239                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11240                    systemApp = (ps.pkg.applicationInfo.flags &
11241                            ApplicationInfo.FLAG_SYSTEM) != 0;
11242                }
11243                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11244            }
11245
11246            // Check whether the newly-scanned package wants to define an already-defined perm
11247            int N = pkg.permissions.size();
11248            for (int i = N-1; i >= 0; i--) {
11249                PackageParser.Permission perm = pkg.permissions.get(i);
11250                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11251                if (bp != null) {
11252                    // If the defining package is signed with our cert, it's okay.  This
11253                    // also includes the "updating the same package" case, of course.
11254                    // "updating same package" could also involve key-rotation.
11255                    final boolean sigsOk;
11256                    if (!bp.sourcePackage.equals(pkg.packageName)
11257                            || !(bp.packageSetting instanceof PackageSetting)
11258                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
11259                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
11260                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11261                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11262                    } else {
11263                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11264                    }
11265                    if (!sigsOk) {
11266                        // If the owning package is the system itself, we log but allow
11267                        // install to proceed; we fail the install on all other permission
11268                        // redefinitions.
11269                        if (!bp.sourcePackage.equals("android")) {
11270                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11271                                    + pkg.packageName + " attempting to redeclare permission "
11272                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11273                            res.origPermission = perm.info.name;
11274                            res.origPackage = bp.sourcePackage;
11275                            return;
11276                        } else {
11277                            Slog.w(TAG, "Package " + pkg.packageName
11278                                    + " attempting to redeclare system permission "
11279                                    + perm.info.name + "; ignoring new declaration");
11280                            pkg.permissions.remove(i);
11281                        }
11282                    }
11283                }
11284            }
11285
11286        }
11287
11288        if (systemApp && onExternal) {
11289            // Disable updates to system apps on sdcard
11290            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11291                    "Cannot install updates to system apps on sdcard");
11292            return;
11293        }
11294
11295        // If app directory is not writable, dexopt will be called after the rename
11296        if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11297            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11298            scanFlags |= SCAN_NO_DEX;
11299            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11300            int result = mPackageDexOptimizer
11301                    .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */,
11302                            false /* defer */, false /* inclDependencies */);
11303            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11304                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11305                return;
11306            }
11307        }
11308
11309        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11310            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11311            return;
11312        }
11313
11314        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11315
11316        if (replace) {
11317            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
11318                    installerPackageName, volumeUuid, res);
11319        } else {
11320            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11321                    args.user, installerPackageName, volumeUuid, res);
11322        }
11323        synchronized (mPackages) {
11324            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11325            if (ps != null) {
11326                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11327            }
11328        }
11329    }
11330
11331    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11332        if (mIntentFilterVerifierComponent == null) {
11333            Slog.d(TAG, "No IntentFilter verification will not be done as "
11334                    + "there is no IntentFilterVerifier available!");
11335            return;
11336        }
11337
11338        final int verifierUid = getPackageUid(
11339                mIntentFilterVerifierComponent.getPackageName(),
11340                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11341
11342        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11343        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11344        msg.obj = pkg;
11345        msg.arg1 = userId;
11346        msg.arg2 = verifierUid;
11347
11348        mHandler.sendMessage(msg);
11349    }
11350
11351    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11352            PackageParser.Package pkg) {
11353        int size = pkg.activities.size();
11354        if (size == 0) {
11355            Slog.d(TAG, "No activity, so no need to verify any IntentFilter!");
11356            return;
11357        }
11358
11359        final boolean hasDomainURLs = hasDomainURLs(pkg);
11360        if (!hasDomainURLs) {
11361            Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!");
11362            return;
11363        }
11364
11365        Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size
11366                + " Activities needs verification ...");
11367
11368        final int verificationId = mIntentFilterVerificationToken++;
11369        int count = 0;
11370        final String packageName = pkg.packageName;
11371        ArrayList<String> allHosts = new ArrayList<>();
11372
11373        synchronized (mPackages) {
11374            for (PackageParser.Activity a : pkg.activities) {
11375                for (ActivityIntentInfo filter : a.intents) {
11376                    boolean needsFilterVerification = filter.needsVerification();
11377                    if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11378                        Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString());
11379                        mIntentFilterVerifier.addOneIntentFilterVerification(
11380                                verifierUid, userId, verificationId, filter, packageName);
11381                        count++;
11382                    } else if (!needsFilterVerification) {
11383                        Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString());
11384                        if (hasValidDomains(filter)) {
11385                            ArrayList<String> hosts = filter.getHostsList();
11386                            if (hosts.size() > 0) {
11387                                allHosts.addAll(hosts);
11388                            } else {
11389                                if (allHosts.isEmpty()) {
11390                                    allHosts.add("*");
11391                                }
11392                            }
11393                        }
11394                    } else {
11395                        Slog.d(TAG, "Verification already done for IntentFilter:"
11396                                + filter.toString());
11397                    }
11398                }
11399            }
11400        }
11401
11402        if (count > 0) {
11403            mIntentFilterVerifier.startVerifications(userId);
11404            Slog.d(TAG, "Started " + count + " IntentFilter verification"
11405                    + (count > 1 ? "s" : "") +  " for userId:" + userId + "!");
11406        } else {
11407            Slog.d(TAG, "No need to start any IntentFilter verification!");
11408            if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw(
11409                    packageName, allHosts) != null) {
11410                scheduleWriteSettingsLocked();
11411            }
11412        }
11413    }
11414
11415    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11416        final ComponentName cn  = filter.activity.getComponentName();
11417        final String packageName = cn.getPackageName();
11418
11419        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11420                packageName);
11421        if (ivi == null) {
11422            return true;
11423        }
11424        int status = ivi.getStatus();
11425        switch (status) {
11426            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11427            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11428                return true;
11429
11430            default:
11431                // Nothing to do
11432                return false;
11433        }
11434    }
11435
11436    private static boolean isMultiArch(PackageSetting ps) {
11437        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11438    }
11439
11440    private static boolean isMultiArch(ApplicationInfo info) {
11441        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11442    }
11443
11444    private static boolean isExternal(PackageParser.Package pkg) {
11445        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11446    }
11447
11448    private static boolean isExternal(PackageSetting ps) {
11449        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11450    }
11451
11452    private static boolean isExternal(ApplicationInfo info) {
11453        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11454    }
11455
11456    private static boolean isSystemApp(PackageParser.Package pkg) {
11457        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11458    }
11459
11460    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11461        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11462    }
11463
11464    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11465        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11466    }
11467
11468    private static boolean isSystemApp(PackageSetting ps) {
11469        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11470    }
11471
11472    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11473        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11474    }
11475
11476    private int packageFlagsToInstallFlags(PackageSetting ps) {
11477        int installFlags = 0;
11478        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11479            // This existing package was an external ASEC install when we have
11480            // the external flag without a UUID
11481            installFlags |= PackageManager.INSTALL_EXTERNAL;
11482        }
11483        if (ps.isForwardLocked()) {
11484            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11485        }
11486        return installFlags;
11487    }
11488
11489    private void deleteTempPackageFiles() {
11490        final FilenameFilter filter = new FilenameFilter() {
11491            public boolean accept(File dir, String name) {
11492                return name.startsWith("vmdl") && name.endsWith(".tmp");
11493            }
11494        };
11495        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11496            file.delete();
11497        }
11498    }
11499
11500    @Override
11501    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11502            int flags) {
11503        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11504                flags);
11505    }
11506
11507    @Override
11508    public void deletePackage(final String packageName,
11509            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11510        mContext.enforceCallingOrSelfPermission(
11511                android.Manifest.permission.DELETE_PACKAGES, null);
11512        final int uid = Binder.getCallingUid();
11513        if (UserHandle.getUserId(uid) != userId) {
11514            mContext.enforceCallingPermission(
11515                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11516                    "deletePackage for user " + userId);
11517        }
11518        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11519            try {
11520                observer.onPackageDeleted(packageName,
11521                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11522            } catch (RemoteException re) {
11523            }
11524            return;
11525        }
11526
11527        boolean uninstallBlocked = false;
11528        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11529            int[] users = sUserManager.getUserIds();
11530            for (int i = 0; i < users.length; ++i) {
11531                if (getBlockUninstallForUser(packageName, users[i])) {
11532                    uninstallBlocked = true;
11533                    break;
11534                }
11535            }
11536        } else {
11537            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11538        }
11539        if (uninstallBlocked) {
11540            try {
11541                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11542                        null);
11543            } catch (RemoteException re) {
11544            }
11545            return;
11546        }
11547
11548        if (DEBUG_REMOVE) {
11549            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
11550        }
11551        // Queue up an async operation since the package deletion may take a little while.
11552        mHandler.post(new Runnable() {
11553            public void run() {
11554                mHandler.removeCallbacks(this);
11555                final int returnCode = deletePackageX(packageName, userId, flags);
11556                if (observer != null) {
11557                    try {
11558                        observer.onPackageDeleted(packageName, returnCode, null);
11559                    } catch (RemoteException e) {
11560                        Log.i(TAG, "Observer no longer exists.");
11561                    } //end catch
11562                } //end if
11563            } //end run
11564        });
11565    }
11566
11567    private boolean isPackageDeviceAdmin(String packageName, int userId) {
11568        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
11569                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
11570        try {
11571            if (dpm != null) {
11572                if (dpm.isDeviceOwner(packageName)) {
11573                    return true;
11574                }
11575                int[] users;
11576                if (userId == UserHandle.USER_ALL) {
11577                    users = sUserManager.getUserIds();
11578                } else {
11579                    users = new int[]{userId};
11580                }
11581                for (int i = 0; i < users.length; ++i) {
11582                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
11583                        return true;
11584                    }
11585                }
11586            }
11587        } catch (RemoteException e) {
11588        }
11589        return false;
11590    }
11591
11592    /**
11593     *  This method is an internal method that could be get invoked either
11594     *  to delete an installed package or to clean up a failed installation.
11595     *  After deleting an installed package, a broadcast is sent to notify any
11596     *  listeners that the package has been installed. For cleaning up a failed
11597     *  installation, the broadcast is not necessary since the package's
11598     *  installation wouldn't have sent the initial broadcast either
11599     *  The key steps in deleting a package are
11600     *  deleting the package information in internal structures like mPackages,
11601     *  deleting the packages base directories through installd
11602     *  updating mSettings to reflect current status
11603     *  persisting settings for later use
11604     *  sending a broadcast if necessary
11605     */
11606    private int deletePackageX(String packageName, int userId, int flags) {
11607        final PackageRemovedInfo info = new PackageRemovedInfo();
11608        final boolean res;
11609
11610        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
11611                ? UserHandle.ALL : new UserHandle(userId);
11612
11613        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
11614            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
11615            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
11616        }
11617
11618        boolean removedForAllUsers = false;
11619        boolean systemUpdate = false;
11620
11621        // for the uninstall-updates case and restricted profiles, remember the per-
11622        // userhandle installed state
11623        int[] allUsers;
11624        boolean[] perUserInstalled;
11625        synchronized (mPackages) {
11626            PackageSetting ps = mSettings.mPackages.get(packageName);
11627            allUsers = sUserManager.getUserIds();
11628            perUserInstalled = new boolean[allUsers.length];
11629            for (int i = 0; i < allUsers.length; i++) {
11630                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11631            }
11632        }
11633
11634        synchronized (mInstallLock) {
11635            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
11636            res = deletePackageLI(packageName, removeForUser,
11637                    true, allUsers, perUserInstalled,
11638                    flags | REMOVE_CHATTY, info, true);
11639            systemUpdate = info.isRemovedPackageSystemUpdate;
11640            if (res && !systemUpdate && mPackages.get(packageName) == null) {
11641                removedForAllUsers = true;
11642            }
11643            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
11644                    + " removedForAllUsers=" + removedForAllUsers);
11645        }
11646
11647        if (res) {
11648            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
11649
11650            // If the removed package was a system update, the old system package
11651            // was re-enabled; we need to broadcast this information
11652            if (systemUpdate) {
11653                Bundle extras = new Bundle(1);
11654                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
11655                        ? info.removedAppId : info.uid);
11656                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11657
11658                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
11659                        extras, null, null, null);
11660                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
11661                        extras, null, null, null);
11662                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
11663                        null, packageName, null, null);
11664            }
11665        }
11666        // Force a gc here.
11667        Runtime.getRuntime().gc();
11668        // Delete the resources here after sending the broadcast to let
11669        // other processes clean up before deleting resources.
11670        if (info.args != null) {
11671            synchronized (mInstallLock) {
11672                info.args.doPostDeleteLI(true);
11673            }
11674        }
11675
11676        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
11677    }
11678
11679    static class PackageRemovedInfo {
11680        String removedPackage;
11681        int uid = -1;
11682        int removedAppId = -1;
11683        int[] removedUsers = null;
11684        boolean isRemovedPackageSystemUpdate = false;
11685        // Clean up resources deleted packages.
11686        InstallArgs args = null;
11687
11688        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
11689            Bundle extras = new Bundle(1);
11690            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
11691            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
11692            if (replacing) {
11693                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11694            }
11695            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
11696            if (removedPackage != null) {
11697                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
11698                        extras, null, null, removedUsers);
11699                if (fullRemove && !replacing) {
11700                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
11701                            extras, null, null, removedUsers);
11702                }
11703            }
11704            if (removedAppId >= 0) {
11705                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
11706                        removedUsers);
11707            }
11708        }
11709    }
11710
11711    /*
11712     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
11713     * flag is not set, the data directory is removed as well.
11714     * make sure this flag is set for partially installed apps. If not its meaningless to
11715     * delete a partially installed application.
11716     */
11717    private void removePackageDataLI(PackageSetting ps,
11718            int[] allUserHandles, boolean[] perUserInstalled,
11719            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
11720        String packageName = ps.name;
11721        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
11722        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
11723        // Retrieve object to delete permissions for shared user later on
11724        final PackageSetting deletedPs;
11725        // reader
11726        synchronized (mPackages) {
11727            deletedPs = mSettings.mPackages.get(packageName);
11728            if (outInfo != null) {
11729                outInfo.removedPackage = packageName;
11730                outInfo.removedUsers = deletedPs != null
11731                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
11732                        : null;
11733            }
11734        }
11735        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11736            removeDataDirsLI(ps.volumeUuid, packageName);
11737            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
11738        }
11739        // writer
11740        synchronized (mPackages) {
11741            if (deletedPs != null) {
11742                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11743                    if (outInfo != null) {
11744                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
11745                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
11746                    }
11747                    updatePermissionsLPw(deletedPs.name, null, 0);
11748                    if (deletedPs.sharedUser != null) {
11749                        // Remove permissions associated with package. Since runtime
11750                        // permissions are per user we have to kill the removed package
11751                        // or packages running under the shared user of the removed
11752                        // package if revoking the permissions requested only by the removed
11753                        // package is successful and this causes a change in gids.
11754                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11755                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
11756                                    userId);
11757                            if (userIdToKill == UserHandle.USER_ALL
11758                                    || userIdToKill >= UserHandle.USER_OWNER) {
11759                                // If gids changed for this user, kill all affected packages.
11760                                mHandler.post(new Runnable() {
11761                                    @Override
11762                                    public void run() {
11763                                        // This has to happen with no lock held.
11764                                        killSettingPackagesForUser(deletedPs, userIdToKill,
11765                                                KILL_APP_REASON_GIDS_CHANGED);
11766                                    }
11767                                });
11768                            break;
11769                            }
11770                        }
11771                    }
11772                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
11773                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
11774                }
11775                // make sure to preserve per-user disabled state if this removal was just
11776                // a downgrade of a system app to the factory package
11777                if (allUserHandles != null && perUserInstalled != null) {
11778                    if (DEBUG_REMOVE) {
11779                        Slog.d(TAG, "Propagating install state across downgrade");
11780                    }
11781                    for (int i = 0; i < allUserHandles.length; i++) {
11782                        if (DEBUG_REMOVE) {
11783                            Slog.d(TAG, "    user " + allUserHandles[i]
11784                                    + " => " + perUserInstalled[i]);
11785                        }
11786                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11787                    }
11788                }
11789            }
11790            // can downgrade to reader
11791            if (writeSettings) {
11792                // Save settings now
11793                mSettings.writeLPr();
11794            }
11795        }
11796        if (outInfo != null) {
11797            // A user ID was deleted here. Go through all users and remove it
11798            // from KeyStore.
11799            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
11800        }
11801    }
11802
11803    static boolean locationIsPrivileged(File path) {
11804        try {
11805            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
11806                    .getCanonicalPath();
11807            return path.getCanonicalPath().startsWith(privilegedAppDir);
11808        } catch (IOException e) {
11809            Slog.e(TAG, "Unable to access code path " + path);
11810        }
11811        return false;
11812    }
11813
11814    /*
11815     * Tries to delete system package.
11816     */
11817    private boolean deleteSystemPackageLI(PackageSetting newPs,
11818            int[] allUserHandles, boolean[] perUserInstalled,
11819            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
11820        final boolean applyUserRestrictions
11821                = (allUserHandles != null) && (perUserInstalled != null);
11822        PackageSetting disabledPs = null;
11823        // Confirm if the system package has been updated
11824        // An updated system app can be deleted. This will also have to restore
11825        // the system pkg from system partition
11826        // reader
11827        synchronized (mPackages) {
11828            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
11829        }
11830        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
11831                + " disabledPs=" + disabledPs);
11832        if (disabledPs == null) {
11833            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
11834            return false;
11835        } else if (DEBUG_REMOVE) {
11836            Slog.d(TAG, "Deleting system pkg from data partition");
11837        }
11838        if (DEBUG_REMOVE) {
11839            if (applyUserRestrictions) {
11840                Slog.d(TAG, "Remembering install states:");
11841                for (int i = 0; i < allUserHandles.length; i++) {
11842                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
11843                }
11844            }
11845        }
11846        // Delete the updated package
11847        outInfo.isRemovedPackageSystemUpdate = true;
11848        if (disabledPs.versionCode < newPs.versionCode) {
11849            // Delete data for downgrades
11850            flags &= ~PackageManager.DELETE_KEEP_DATA;
11851        } else {
11852            // Preserve data by setting flag
11853            flags |= PackageManager.DELETE_KEEP_DATA;
11854        }
11855        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
11856                allUserHandles, perUserInstalled, outInfo, writeSettings);
11857        if (!ret) {
11858            return false;
11859        }
11860        // writer
11861        synchronized (mPackages) {
11862            // Reinstate the old system package
11863            mSettings.enableSystemPackageLPw(newPs.name);
11864            // Remove any native libraries from the upgraded package.
11865            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
11866        }
11867        // Install the system package
11868        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
11869        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
11870        if (locationIsPrivileged(disabledPs.codePath)) {
11871            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11872        }
11873
11874        final PackageParser.Package newPkg;
11875        try {
11876            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
11877        } catch (PackageManagerException e) {
11878            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
11879            return false;
11880        }
11881
11882        // writer
11883        synchronized (mPackages) {
11884            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
11885            updatePermissionsLPw(newPkg.packageName, newPkg,
11886                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
11887            if (applyUserRestrictions) {
11888                if (DEBUG_REMOVE) {
11889                    Slog.d(TAG, "Propagating install state across reinstall");
11890                }
11891                for (int i = 0; i < allUserHandles.length; i++) {
11892                    if (DEBUG_REMOVE) {
11893                        Slog.d(TAG, "    user " + allUserHandles[i]
11894                                + " => " + perUserInstalled[i]);
11895                    }
11896                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11897                }
11898                // Regardless of writeSettings we need to ensure that this restriction
11899                // state propagation is persisted
11900                mSettings.writeAllUsersPackageRestrictionsLPr();
11901            }
11902            // can downgrade to reader here
11903            if (writeSettings) {
11904                mSettings.writeLPr();
11905            }
11906        }
11907        return true;
11908    }
11909
11910    private boolean deleteInstalledPackageLI(PackageSetting ps,
11911            boolean deleteCodeAndResources, int flags,
11912            int[] allUserHandles, boolean[] perUserInstalled,
11913            PackageRemovedInfo outInfo, boolean writeSettings) {
11914        if (outInfo != null) {
11915            outInfo.uid = ps.appId;
11916        }
11917
11918        // Delete package data from internal structures and also remove data if flag is set
11919        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
11920
11921        // Delete application code and resources
11922        if (deleteCodeAndResources && (outInfo != null)) {
11923            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
11924                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
11925                    getAppDexInstructionSets(ps));
11926            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
11927        }
11928        return true;
11929    }
11930
11931    @Override
11932    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
11933            int userId) {
11934        mContext.enforceCallingOrSelfPermission(
11935                android.Manifest.permission.DELETE_PACKAGES, null);
11936        synchronized (mPackages) {
11937            PackageSetting ps = mSettings.mPackages.get(packageName);
11938            if (ps == null) {
11939                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
11940                return false;
11941            }
11942            if (!ps.getInstalled(userId)) {
11943                // Can't block uninstall for an app that is not installed or enabled.
11944                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11945                return false;
11946            }
11947            ps.setBlockUninstall(blockUninstall, userId);
11948            mSettings.writePackageRestrictionsLPr(userId);
11949        }
11950        return true;
11951    }
11952
11953    @Override
11954    public boolean getBlockUninstallForUser(String packageName, int userId) {
11955        synchronized (mPackages) {
11956            PackageSetting ps = mSettings.mPackages.get(packageName);
11957            if (ps == null) {
11958                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11959                return false;
11960            }
11961            return ps.getBlockUninstall(userId);
11962        }
11963    }
11964
11965    /*
11966     * This method handles package deletion in general
11967     */
11968    private boolean deletePackageLI(String packageName, UserHandle user,
11969            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11970            int flags, PackageRemovedInfo outInfo,
11971            boolean writeSettings) {
11972        if (packageName == null) {
11973            Slog.w(TAG, "Attempt to delete null packageName.");
11974            return false;
11975        }
11976        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11977        PackageSetting ps;
11978        boolean dataOnly = false;
11979        int removeUser = -1;
11980        int appId = -1;
11981        synchronized (mPackages) {
11982            ps = mSettings.mPackages.get(packageName);
11983            if (ps == null) {
11984                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11985                return false;
11986            }
11987            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11988                    && user.getIdentifier() != UserHandle.USER_ALL) {
11989                // The caller is asking that the package only be deleted for a single
11990                // user.  To do this, we just mark its uninstalled state and delete
11991                // its data.  If this is a system app, we only allow this to happen if
11992                // they have set the special DELETE_SYSTEM_APP which requests different
11993                // semantics than normal for uninstalling system apps.
11994                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11995                ps.setUserState(user.getIdentifier(),
11996                        COMPONENT_ENABLED_STATE_DEFAULT,
11997                        false, //installed
11998                        true,  //stopped
11999                        true,  //notLaunched
12000                        false, //hidden
12001                        null, null, null,
12002                        false, // blockUninstall
12003                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12004                if (!isSystemApp(ps)) {
12005                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12006                        // Other user still have this package installed, so all
12007                        // we need to do is clear this user's data and save that
12008                        // it is uninstalled.
12009                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12010                        removeUser = user.getIdentifier();
12011                        appId = ps.appId;
12012                        scheduleWritePackageRestrictionsLocked(removeUser);
12013                    } else {
12014                        // We need to set it back to 'installed' so the uninstall
12015                        // broadcasts will be sent correctly.
12016                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12017                        ps.setInstalled(true, user.getIdentifier());
12018                    }
12019                } else {
12020                    // This is a system app, so we assume that the
12021                    // other users still have this package installed, so all
12022                    // we need to do is clear this user's data and save that
12023                    // it is uninstalled.
12024                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12025                    removeUser = user.getIdentifier();
12026                    appId = ps.appId;
12027                    scheduleWritePackageRestrictionsLocked(removeUser);
12028                }
12029            }
12030        }
12031
12032        if (removeUser >= 0) {
12033            // From above, we determined that we are deleting this only
12034            // for a single user.  Continue the work here.
12035            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12036            if (outInfo != null) {
12037                outInfo.removedPackage = packageName;
12038                outInfo.removedAppId = appId;
12039                outInfo.removedUsers = new int[] {removeUser};
12040            }
12041            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12042            removeKeystoreDataIfNeeded(removeUser, appId);
12043            schedulePackageCleaning(packageName, removeUser, false);
12044            synchronized (mPackages) {
12045                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12046                    scheduleWritePackageRestrictionsLocked(removeUser);
12047                }
12048            }
12049            return true;
12050        }
12051
12052        if (dataOnly) {
12053            // Delete application data first
12054            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12055            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12056            return true;
12057        }
12058
12059        boolean ret = false;
12060        if (isSystemApp(ps)) {
12061            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12062            // When an updated system application is deleted we delete the existing resources as well and
12063            // fall back to existing code in system partition
12064            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12065                    flags, outInfo, writeSettings);
12066        } else {
12067            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12068            // Kill application pre-emptively especially for apps on sd.
12069            killApplication(packageName, ps.appId, "uninstall pkg");
12070            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12071                    allUserHandles, perUserInstalled,
12072                    outInfo, writeSettings);
12073        }
12074
12075        return ret;
12076    }
12077
12078    private final class ClearStorageConnection implements ServiceConnection {
12079        IMediaContainerService mContainerService;
12080
12081        @Override
12082        public void onServiceConnected(ComponentName name, IBinder service) {
12083            synchronized (this) {
12084                mContainerService = IMediaContainerService.Stub.asInterface(service);
12085                notifyAll();
12086            }
12087        }
12088
12089        @Override
12090        public void onServiceDisconnected(ComponentName name) {
12091        }
12092    }
12093
12094    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12095        final boolean mounted;
12096        if (Environment.isExternalStorageEmulated()) {
12097            mounted = true;
12098        } else {
12099            final String status = Environment.getExternalStorageState();
12100
12101            mounted = status.equals(Environment.MEDIA_MOUNTED)
12102                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12103        }
12104
12105        if (!mounted) {
12106            return;
12107        }
12108
12109        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12110        int[] users;
12111        if (userId == UserHandle.USER_ALL) {
12112            users = sUserManager.getUserIds();
12113        } else {
12114            users = new int[] { userId };
12115        }
12116        final ClearStorageConnection conn = new ClearStorageConnection();
12117        if (mContext.bindServiceAsUser(
12118                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12119            try {
12120                for (int curUser : users) {
12121                    long timeout = SystemClock.uptimeMillis() + 5000;
12122                    synchronized (conn) {
12123                        long now = SystemClock.uptimeMillis();
12124                        while (conn.mContainerService == null && now < timeout) {
12125                            try {
12126                                conn.wait(timeout - now);
12127                            } catch (InterruptedException e) {
12128                            }
12129                        }
12130                    }
12131                    if (conn.mContainerService == null) {
12132                        return;
12133                    }
12134
12135                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12136                    clearDirectory(conn.mContainerService,
12137                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12138                    if (allData) {
12139                        clearDirectory(conn.mContainerService,
12140                                userEnv.buildExternalStorageAppDataDirs(packageName));
12141                        clearDirectory(conn.mContainerService,
12142                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12143                    }
12144                }
12145            } finally {
12146                mContext.unbindService(conn);
12147            }
12148        }
12149    }
12150
12151    @Override
12152    public void clearApplicationUserData(final String packageName,
12153            final IPackageDataObserver observer, final int userId) {
12154        mContext.enforceCallingOrSelfPermission(
12155                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12156        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12157        // Queue up an async operation since the package deletion may take a little while.
12158        mHandler.post(new Runnable() {
12159            public void run() {
12160                mHandler.removeCallbacks(this);
12161                final boolean succeeded;
12162                synchronized (mInstallLock) {
12163                    succeeded = clearApplicationUserDataLI(packageName, userId);
12164                }
12165                clearExternalStorageDataSync(packageName, userId, true);
12166                if (succeeded) {
12167                    // invoke DeviceStorageMonitor's update method to clear any notifications
12168                    DeviceStorageMonitorInternal
12169                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12170                    if (dsm != null) {
12171                        dsm.checkMemory();
12172                    }
12173                }
12174                if(observer != null) {
12175                    try {
12176                        observer.onRemoveCompleted(packageName, succeeded);
12177                    } catch (RemoteException e) {
12178                        Log.i(TAG, "Observer no longer exists.");
12179                    }
12180                } //end if observer
12181            } //end run
12182        });
12183    }
12184
12185    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12186        if (packageName == null) {
12187            Slog.w(TAG, "Attempt to delete null packageName.");
12188            return false;
12189        }
12190
12191        // Try finding details about the requested package
12192        PackageParser.Package pkg;
12193        synchronized (mPackages) {
12194            pkg = mPackages.get(packageName);
12195            if (pkg == null) {
12196                final PackageSetting ps = mSettings.mPackages.get(packageName);
12197                if (ps != null) {
12198                    pkg = ps.pkg;
12199                }
12200            }
12201        }
12202
12203        if (pkg == null) {
12204            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12205        }
12206
12207        // Always delete data directories for package, even if we found no other
12208        // record of app. This helps users recover from UID mismatches without
12209        // resorting to a full data wipe.
12210        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12211        if (retCode < 0) {
12212            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12213            return false;
12214        }
12215
12216        if (pkg == null) {
12217            return false;
12218        }
12219
12220        if (pkg != null && pkg.applicationInfo != null) {
12221            final int appId = pkg.applicationInfo.uid;
12222            removeKeystoreDataIfNeeded(userId, appId);
12223        }
12224
12225        // Create a native library symlink only if we have native libraries
12226        // and if the native libraries are 32 bit libraries. We do not provide
12227        // this symlink for 64 bit libraries.
12228        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
12229                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12230            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12231            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12232                    nativeLibPath, userId) < 0) {
12233                Slog.w(TAG, "Failed linking native library dir");
12234                return false;
12235            }
12236        }
12237
12238        return true;
12239    }
12240
12241    /**
12242     * Remove entries from the keystore daemon. Will only remove it if the
12243     * {@code appId} is valid.
12244     */
12245    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12246        if (appId < 0) {
12247            return;
12248        }
12249
12250        final KeyStore keyStore = KeyStore.getInstance();
12251        if (keyStore != null) {
12252            if (userId == UserHandle.USER_ALL) {
12253                for (final int individual : sUserManager.getUserIds()) {
12254                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12255                }
12256            } else {
12257                keyStore.clearUid(UserHandle.getUid(userId, appId));
12258            }
12259        } else {
12260            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12261        }
12262    }
12263
12264    @Override
12265    public void deleteApplicationCacheFiles(final String packageName,
12266            final IPackageDataObserver observer) {
12267        mContext.enforceCallingOrSelfPermission(
12268                android.Manifest.permission.DELETE_CACHE_FILES, null);
12269        // Queue up an async operation since the package deletion may take a little while.
12270        final int userId = UserHandle.getCallingUserId();
12271        mHandler.post(new Runnable() {
12272            public void run() {
12273                mHandler.removeCallbacks(this);
12274                final boolean succeded;
12275                synchronized (mInstallLock) {
12276                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12277                }
12278                clearExternalStorageDataSync(packageName, userId, false);
12279                if(observer != null) {
12280                    try {
12281                        observer.onRemoveCompleted(packageName, succeded);
12282                    } catch (RemoteException e) {
12283                        Log.i(TAG, "Observer no longer exists.");
12284                    }
12285                } //end if observer
12286            } //end run
12287        });
12288    }
12289
12290    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12291        if (packageName == null) {
12292            Slog.w(TAG, "Attempt to delete null packageName.");
12293            return false;
12294        }
12295        PackageParser.Package p;
12296        synchronized (mPackages) {
12297            p = mPackages.get(packageName);
12298        }
12299        if (p == null) {
12300            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12301            return false;
12302        }
12303        final ApplicationInfo applicationInfo = p.applicationInfo;
12304        if (applicationInfo == null) {
12305            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12306            return false;
12307        }
12308        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12309        if (retCode < 0) {
12310            Slog.w(TAG, "Couldn't remove cache files for package: "
12311                       + packageName + " u" + userId);
12312            return false;
12313        }
12314        return true;
12315    }
12316
12317    @Override
12318    public void getPackageSizeInfo(final String packageName, int userHandle,
12319            final IPackageStatsObserver observer) {
12320        mContext.enforceCallingOrSelfPermission(
12321                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12322        if (packageName == null) {
12323            throw new IllegalArgumentException("Attempt to get size of null packageName");
12324        }
12325
12326        PackageStats stats = new PackageStats(packageName, userHandle);
12327
12328        /*
12329         * Queue up an async operation since the package measurement may take a
12330         * little while.
12331         */
12332        Message msg = mHandler.obtainMessage(INIT_COPY);
12333        msg.obj = new MeasureParams(stats, observer);
12334        mHandler.sendMessage(msg);
12335    }
12336
12337    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12338            PackageStats pStats) {
12339        if (packageName == null) {
12340            Slog.w(TAG, "Attempt to get size of null packageName.");
12341            return false;
12342        }
12343        PackageParser.Package p;
12344        boolean dataOnly = false;
12345        String libDirRoot = null;
12346        String asecPath = null;
12347        PackageSetting ps = null;
12348        synchronized (mPackages) {
12349            p = mPackages.get(packageName);
12350            ps = mSettings.mPackages.get(packageName);
12351            if(p == null) {
12352                dataOnly = true;
12353                if((ps == null) || (ps.pkg == null)) {
12354                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12355                    return false;
12356                }
12357                p = ps.pkg;
12358            }
12359            if (ps != null) {
12360                libDirRoot = ps.legacyNativeLibraryPathString;
12361            }
12362            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12363                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12364                if (secureContainerId != null) {
12365                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12366                }
12367            }
12368        }
12369        String publicSrcDir = null;
12370        if(!dataOnly) {
12371            final ApplicationInfo applicationInfo = p.applicationInfo;
12372            if (applicationInfo == null) {
12373                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12374                return false;
12375            }
12376            if (p.isForwardLocked()) {
12377                publicSrcDir = applicationInfo.getBaseResourcePath();
12378            }
12379        }
12380        // TODO: extend to measure size of split APKs
12381        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12382        // not just the first level.
12383        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12384        // just the primary.
12385        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12386        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
12387                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12388        if (res < 0) {
12389            return false;
12390        }
12391
12392        // Fix-up for forward-locked applications in ASEC containers.
12393        if (!isExternal(p)) {
12394            pStats.codeSize += pStats.externalCodeSize;
12395            pStats.externalCodeSize = 0L;
12396        }
12397
12398        return true;
12399    }
12400
12401
12402    @Override
12403    public void addPackageToPreferred(String packageName) {
12404        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12405    }
12406
12407    @Override
12408    public void removePackageFromPreferred(String packageName) {
12409        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12410    }
12411
12412    @Override
12413    public List<PackageInfo> getPreferredPackages(int flags) {
12414        return new ArrayList<PackageInfo>();
12415    }
12416
12417    private int getUidTargetSdkVersionLockedLPr(int uid) {
12418        Object obj = mSettings.getUserIdLPr(uid);
12419        if (obj instanceof SharedUserSetting) {
12420            final SharedUserSetting sus = (SharedUserSetting) obj;
12421            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12422            final Iterator<PackageSetting> it = sus.packages.iterator();
12423            while (it.hasNext()) {
12424                final PackageSetting ps = it.next();
12425                if (ps.pkg != null) {
12426                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12427                    if (v < vers) vers = v;
12428                }
12429            }
12430            return vers;
12431        } else if (obj instanceof PackageSetting) {
12432            final PackageSetting ps = (PackageSetting) obj;
12433            if (ps.pkg != null) {
12434                return ps.pkg.applicationInfo.targetSdkVersion;
12435            }
12436        }
12437        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12438    }
12439
12440    @Override
12441    public void addPreferredActivity(IntentFilter filter, int match,
12442            ComponentName[] set, ComponentName activity, int userId) {
12443        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12444                "Adding preferred");
12445    }
12446
12447    private void addPreferredActivityInternal(IntentFilter filter, int match,
12448            ComponentName[] set, ComponentName activity, boolean always, int userId,
12449            String opname) {
12450        // writer
12451        int callingUid = Binder.getCallingUid();
12452        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12453        if (filter.countActions() == 0) {
12454            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12455            return;
12456        }
12457        synchronized (mPackages) {
12458            if (mContext.checkCallingOrSelfPermission(
12459                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12460                    != PackageManager.PERMISSION_GRANTED) {
12461                if (getUidTargetSdkVersionLockedLPr(callingUid)
12462                        < Build.VERSION_CODES.FROYO) {
12463                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12464                            + callingUid);
12465                    return;
12466                }
12467                mContext.enforceCallingOrSelfPermission(
12468                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12469            }
12470
12471            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12472            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12473                    + userId + ":");
12474            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12475            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12476            scheduleWritePackageRestrictionsLocked(userId);
12477        }
12478    }
12479
12480    @Override
12481    public void replacePreferredActivity(IntentFilter filter, int match,
12482            ComponentName[] set, ComponentName activity, int userId) {
12483        if (filter.countActions() != 1) {
12484            throw new IllegalArgumentException(
12485                    "replacePreferredActivity expects filter to have only 1 action.");
12486        }
12487        if (filter.countDataAuthorities() != 0
12488                || filter.countDataPaths() != 0
12489                || filter.countDataSchemes() > 1
12490                || filter.countDataTypes() != 0) {
12491            throw new IllegalArgumentException(
12492                    "replacePreferredActivity expects filter to have no data authorities, " +
12493                    "paths, or types; and at most one scheme.");
12494        }
12495
12496        final int callingUid = Binder.getCallingUid();
12497        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12498        synchronized (mPackages) {
12499            if (mContext.checkCallingOrSelfPermission(
12500                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12501                    != PackageManager.PERMISSION_GRANTED) {
12502                if (getUidTargetSdkVersionLockedLPr(callingUid)
12503                        < Build.VERSION_CODES.FROYO) {
12504                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12505                            + Binder.getCallingUid());
12506                    return;
12507                }
12508                mContext.enforceCallingOrSelfPermission(
12509                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12510            }
12511
12512            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12513            if (pir != null) {
12514                // Get all of the existing entries that exactly match this filter.
12515                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
12516                if (existing != null && existing.size() == 1) {
12517                    PreferredActivity cur = existing.get(0);
12518                    if (DEBUG_PREFERRED) {
12519                        Slog.i(TAG, "Checking replace of preferred:");
12520                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12521                        if (!cur.mPref.mAlways) {
12522                            Slog.i(TAG, "  -- CUR; not mAlways!");
12523                        } else {
12524                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
12525                            Slog.i(TAG, "  -- CUR: mSet="
12526                                    + Arrays.toString(cur.mPref.mSetComponents));
12527                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
12528                            Slog.i(TAG, "  -- NEW: mMatch="
12529                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
12530                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
12531                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
12532                        }
12533                    }
12534                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
12535                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
12536                            && cur.mPref.sameSet(set)) {
12537                        // Setting the preferred activity to what it happens to be already
12538                        if (DEBUG_PREFERRED) {
12539                            Slog.i(TAG, "Replacing with same preferred activity "
12540                                    + cur.mPref.mShortComponent + " for user "
12541                                    + userId + ":");
12542                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12543                        }
12544                        return;
12545                    }
12546                }
12547
12548                if (existing != null) {
12549                    if (DEBUG_PREFERRED) {
12550                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
12551                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12552                    }
12553                    for (int i = 0; i < existing.size(); i++) {
12554                        PreferredActivity pa = existing.get(i);
12555                        if (DEBUG_PREFERRED) {
12556                            Slog.i(TAG, "Removing existing preferred activity "
12557                                    + pa.mPref.mComponent + ":");
12558                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
12559                        }
12560                        pir.removeFilter(pa);
12561                    }
12562                }
12563            }
12564            addPreferredActivityInternal(filter, match, set, activity, true, userId,
12565                    "Replacing preferred");
12566        }
12567    }
12568
12569    @Override
12570    public void clearPackagePreferredActivities(String packageName) {
12571        final int uid = Binder.getCallingUid();
12572        // writer
12573        synchronized (mPackages) {
12574            PackageParser.Package pkg = mPackages.get(packageName);
12575            if (pkg == null || pkg.applicationInfo.uid != uid) {
12576                if (mContext.checkCallingOrSelfPermission(
12577                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12578                        != PackageManager.PERMISSION_GRANTED) {
12579                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
12580                            < Build.VERSION_CODES.FROYO) {
12581                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
12582                                + Binder.getCallingUid());
12583                        return;
12584                    }
12585                    mContext.enforceCallingOrSelfPermission(
12586                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12587                }
12588            }
12589
12590            int user = UserHandle.getCallingUserId();
12591            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
12592                scheduleWritePackageRestrictionsLocked(user);
12593            }
12594        }
12595    }
12596
12597    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12598    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
12599        ArrayList<PreferredActivity> removed = null;
12600        boolean changed = false;
12601        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12602            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
12603            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12604            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
12605                continue;
12606            }
12607            Iterator<PreferredActivity> it = pir.filterIterator();
12608            while (it.hasNext()) {
12609                PreferredActivity pa = it.next();
12610                // Mark entry for removal only if it matches the package name
12611                // and the entry is of type "always".
12612                if (packageName == null ||
12613                        (pa.mPref.mComponent.getPackageName().equals(packageName)
12614                                && pa.mPref.mAlways)) {
12615                    if (removed == null) {
12616                        removed = new ArrayList<PreferredActivity>();
12617                    }
12618                    removed.add(pa);
12619                }
12620            }
12621            if (removed != null) {
12622                for (int j=0; j<removed.size(); j++) {
12623                    PreferredActivity pa = removed.get(j);
12624                    pir.removeFilter(pa);
12625                }
12626                changed = true;
12627            }
12628        }
12629        return changed;
12630    }
12631
12632    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12633    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
12634        if (userId == UserHandle.USER_ALL) {
12635            mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds());
12636            for (int oneUserId : sUserManager.getUserIds()) {
12637                scheduleWritePackageRestrictionsLocked(oneUserId);
12638            }
12639        } else {
12640            mSettings.removeIntentFilterVerificationLPw(packageName, userId);
12641            scheduleWritePackageRestrictionsLocked(userId);
12642        }
12643    }
12644
12645    @Override
12646    public void resetPreferredActivities(int userId) {
12647        /* TODO: Actually use userId. Why is it being passed in? */
12648        mContext.enforceCallingOrSelfPermission(
12649                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12650        // writer
12651        synchronized (mPackages) {
12652            int user = UserHandle.getCallingUserId();
12653            clearPackagePreferredActivitiesLPw(null, user);
12654            mSettings.readDefaultPreferredAppsLPw(this, user);
12655            scheduleWritePackageRestrictionsLocked(user);
12656        }
12657    }
12658
12659    @Override
12660    public int getPreferredActivities(List<IntentFilter> outFilters,
12661            List<ComponentName> outActivities, String packageName) {
12662
12663        int num = 0;
12664        final int userId = UserHandle.getCallingUserId();
12665        // reader
12666        synchronized (mPackages) {
12667            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12668            if (pir != null) {
12669                final Iterator<PreferredActivity> it = pir.filterIterator();
12670                while (it.hasNext()) {
12671                    final PreferredActivity pa = it.next();
12672                    if (packageName == null
12673                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
12674                                    && pa.mPref.mAlways)) {
12675                        if (outFilters != null) {
12676                            outFilters.add(new IntentFilter(pa));
12677                        }
12678                        if (outActivities != null) {
12679                            outActivities.add(pa.mPref.mComponent);
12680                        }
12681                    }
12682                }
12683            }
12684        }
12685
12686        return num;
12687    }
12688
12689    @Override
12690    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
12691            int userId) {
12692        int callingUid = Binder.getCallingUid();
12693        if (callingUid != Process.SYSTEM_UID) {
12694            throw new SecurityException(
12695                    "addPersistentPreferredActivity can only be run by the system");
12696        }
12697        if (filter.countActions() == 0) {
12698            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12699            return;
12700        }
12701        synchronized (mPackages) {
12702            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
12703                    " :");
12704            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12705            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
12706                    new PersistentPreferredActivity(filter, activity));
12707            scheduleWritePackageRestrictionsLocked(userId);
12708        }
12709    }
12710
12711    @Override
12712    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
12713        int callingUid = Binder.getCallingUid();
12714        if (callingUid != Process.SYSTEM_UID) {
12715            throw new SecurityException(
12716                    "clearPackagePersistentPreferredActivities can only be run by the system");
12717        }
12718        ArrayList<PersistentPreferredActivity> removed = null;
12719        boolean changed = false;
12720        synchronized (mPackages) {
12721            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
12722                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
12723                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
12724                        .valueAt(i);
12725                if (userId != thisUserId) {
12726                    continue;
12727                }
12728                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
12729                while (it.hasNext()) {
12730                    PersistentPreferredActivity ppa = it.next();
12731                    // Mark entry for removal only if it matches the package name.
12732                    if (ppa.mComponent.getPackageName().equals(packageName)) {
12733                        if (removed == null) {
12734                            removed = new ArrayList<PersistentPreferredActivity>();
12735                        }
12736                        removed.add(ppa);
12737                    }
12738                }
12739                if (removed != null) {
12740                    for (int j=0; j<removed.size(); j++) {
12741                        PersistentPreferredActivity ppa = removed.get(j);
12742                        ppir.removeFilter(ppa);
12743                    }
12744                    changed = true;
12745                }
12746            }
12747
12748            if (changed) {
12749                scheduleWritePackageRestrictionsLocked(userId);
12750            }
12751        }
12752    }
12753
12754    /**
12755     * Non-Binder method, support for the backup/restore mechanism: write the
12756     * full set of preferred activities in its canonical XML format.  Returns true
12757     * on success; false otherwise.
12758     */
12759    @Override
12760    public byte[] getPreferredActivityBackup(int userId) {
12761        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
12762            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
12763        }
12764
12765        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
12766        try {
12767            final XmlSerializer serializer = new FastXmlSerializer();
12768            serializer.setOutput(dataStream, "utf-8");
12769            serializer.startDocument(null, true);
12770            serializer.startTag(null, TAG_PREFERRED_BACKUP);
12771
12772            synchronized (mPackages) {
12773                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
12774            }
12775
12776            serializer.endTag(null, TAG_PREFERRED_BACKUP);
12777            serializer.endDocument();
12778            serializer.flush();
12779        } catch (Exception e) {
12780            if (DEBUG_BACKUP) {
12781                Slog.e(TAG, "Unable to write preferred activities for backup", e);
12782            }
12783            return null;
12784        }
12785
12786        return dataStream.toByteArray();
12787    }
12788
12789    @Override
12790    public void restorePreferredActivities(byte[] backup, int userId) {
12791        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
12792            throw new SecurityException("Only the system may call restorePreferredActivities()");
12793        }
12794
12795        try {
12796            final XmlPullParser parser = Xml.newPullParser();
12797            parser.setInput(new ByteArrayInputStream(backup), null);
12798
12799            int type;
12800            while ((type = parser.next()) != XmlPullParser.START_TAG
12801                    && type != XmlPullParser.END_DOCUMENT) {
12802            }
12803            if (type != XmlPullParser.START_TAG) {
12804                // oops didn't find a start tag?!
12805                if (DEBUG_BACKUP) {
12806                    Slog.e(TAG, "Didn't find start tag during restore");
12807                }
12808                return;
12809            }
12810
12811            // this is supposed to be TAG_PREFERRED_BACKUP
12812            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
12813                if (DEBUG_BACKUP) {
12814                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
12815                }
12816                return;
12817            }
12818
12819            // skip interfering stuff, then we're aligned with the backing implementation
12820            while ((type = parser.next()) == XmlPullParser.TEXT) { }
12821            synchronized (mPackages) {
12822                mSettings.readPreferredActivitiesLPw(parser, userId);
12823            }
12824        } catch (Exception e) {
12825            if (DEBUG_BACKUP) {
12826                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
12827            }
12828        }
12829    }
12830
12831    @Override
12832    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
12833            int sourceUserId, int targetUserId, int flags) {
12834        mContext.enforceCallingOrSelfPermission(
12835                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12836        int callingUid = Binder.getCallingUid();
12837        enforceOwnerRights(ownerPackage, callingUid);
12838        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12839        if (intentFilter.countActions() == 0) {
12840            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
12841            return;
12842        }
12843        synchronized (mPackages) {
12844            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
12845                    ownerPackage, targetUserId, flags);
12846            CrossProfileIntentResolver resolver =
12847                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12848            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
12849            // We have all those whose filter is equal. Now checking if the rest is equal as well.
12850            if (existing != null) {
12851                int size = existing.size();
12852                for (int i = 0; i < size; i++) {
12853                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
12854                        return;
12855                    }
12856                }
12857            }
12858            resolver.addFilter(newFilter);
12859            scheduleWritePackageRestrictionsLocked(sourceUserId);
12860        }
12861    }
12862
12863    @Override
12864    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
12865        mContext.enforceCallingOrSelfPermission(
12866                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12867        int callingUid = Binder.getCallingUid();
12868        enforceOwnerRights(ownerPackage, callingUid);
12869        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12870        synchronized (mPackages) {
12871            CrossProfileIntentResolver resolver =
12872                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12873            ArraySet<CrossProfileIntentFilter> set =
12874                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
12875            for (CrossProfileIntentFilter filter : set) {
12876                if (filter.getOwnerPackage().equals(ownerPackage)) {
12877                    resolver.removeFilter(filter);
12878                }
12879            }
12880            scheduleWritePackageRestrictionsLocked(sourceUserId);
12881        }
12882    }
12883
12884    // Enforcing that callingUid is owning pkg on userId
12885    private void enforceOwnerRights(String pkg, int callingUid) {
12886        // The system owns everything.
12887        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
12888            return;
12889        }
12890        int callingUserId = UserHandle.getUserId(callingUid);
12891        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
12892        if (pi == null) {
12893            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
12894                    + callingUserId);
12895        }
12896        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
12897            throw new SecurityException("Calling uid " + callingUid
12898                    + " does not own package " + pkg);
12899        }
12900    }
12901
12902    @Override
12903    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
12904        Intent intent = new Intent(Intent.ACTION_MAIN);
12905        intent.addCategory(Intent.CATEGORY_HOME);
12906
12907        final int callingUserId = UserHandle.getCallingUserId();
12908        List<ResolveInfo> list = queryIntentActivities(intent, null,
12909                PackageManager.GET_META_DATA, callingUserId);
12910        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
12911                true, false, false, callingUserId);
12912
12913        allHomeCandidates.clear();
12914        if (list != null) {
12915            for (ResolveInfo ri : list) {
12916                allHomeCandidates.add(ri);
12917            }
12918        }
12919        return (preferred == null || preferred.activityInfo == null)
12920                ? null
12921                : new ComponentName(preferred.activityInfo.packageName,
12922                        preferred.activityInfo.name);
12923    }
12924
12925    @Override
12926    public void setApplicationEnabledSetting(String appPackageName,
12927            int newState, int flags, int userId, String callingPackage) {
12928        if (!sUserManager.exists(userId)) return;
12929        if (callingPackage == null) {
12930            callingPackage = Integer.toString(Binder.getCallingUid());
12931        }
12932        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
12933    }
12934
12935    @Override
12936    public void setComponentEnabledSetting(ComponentName componentName,
12937            int newState, int flags, int userId) {
12938        if (!sUserManager.exists(userId)) return;
12939        setEnabledSetting(componentName.getPackageName(),
12940                componentName.getClassName(), newState, flags, userId, null);
12941    }
12942
12943    private void setEnabledSetting(final String packageName, String className, int newState,
12944            final int flags, int userId, String callingPackage) {
12945        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
12946              || newState == COMPONENT_ENABLED_STATE_ENABLED
12947              || newState == COMPONENT_ENABLED_STATE_DISABLED
12948              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
12949              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
12950            throw new IllegalArgumentException("Invalid new component state: "
12951                    + newState);
12952        }
12953        PackageSetting pkgSetting;
12954        final int uid = Binder.getCallingUid();
12955        final int permission = mContext.checkCallingOrSelfPermission(
12956                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12957        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
12958        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12959        boolean sendNow = false;
12960        boolean isApp = (className == null);
12961        String componentName = isApp ? packageName : className;
12962        int packageUid = -1;
12963        ArrayList<String> components;
12964
12965        // writer
12966        synchronized (mPackages) {
12967            pkgSetting = mSettings.mPackages.get(packageName);
12968            if (pkgSetting == null) {
12969                if (className == null) {
12970                    throw new IllegalArgumentException(
12971                            "Unknown package: " + packageName);
12972                }
12973                throw new IllegalArgumentException(
12974                        "Unknown component: " + packageName
12975                        + "/" + className);
12976            }
12977            // Allow root and verify that userId is not being specified by a different user
12978            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
12979                throw new SecurityException(
12980                        "Permission Denial: attempt to change component state from pid="
12981                        + Binder.getCallingPid()
12982                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
12983            }
12984            if (className == null) {
12985                // We're dealing with an application/package level state change
12986                if (pkgSetting.getEnabled(userId) == newState) {
12987                    // Nothing to do
12988                    return;
12989                }
12990                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
12991                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
12992                    // Don't care about who enables an app.
12993                    callingPackage = null;
12994                }
12995                pkgSetting.setEnabled(newState, userId, callingPackage);
12996                // pkgSetting.pkg.mSetEnabled = newState;
12997            } else {
12998                // We're dealing with a component level state change
12999                // First, verify that this is a valid class name.
13000                PackageParser.Package pkg = pkgSetting.pkg;
13001                if (pkg == null || !pkg.hasComponentClassName(className)) {
13002                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13003                        throw new IllegalArgumentException("Component class " + className
13004                                + " does not exist in " + packageName);
13005                    } else {
13006                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13007                                + className + " does not exist in " + packageName);
13008                    }
13009                }
13010                switch (newState) {
13011                case COMPONENT_ENABLED_STATE_ENABLED:
13012                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13013                        return;
13014                    }
13015                    break;
13016                case COMPONENT_ENABLED_STATE_DISABLED:
13017                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13018                        return;
13019                    }
13020                    break;
13021                case COMPONENT_ENABLED_STATE_DEFAULT:
13022                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13023                        return;
13024                    }
13025                    break;
13026                default:
13027                    Slog.e(TAG, "Invalid new component state: " + newState);
13028                    return;
13029                }
13030            }
13031            scheduleWritePackageRestrictionsLocked(userId);
13032            components = mPendingBroadcasts.get(userId, packageName);
13033            final boolean newPackage = components == null;
13034            if (newPackage) {
13035                components = new ArrayList<String>();
13036            }
13037            if (!components.contains(componentName)) {
13038                components.add(componentName);
13039            }
13040            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13041                sendNow = true;
13042                // Purge entry from pending broadcast list if another one exists already
13043                // since we are sending one right away.
13044                mPendingBroadcasts.remove(userId, packageName);
13045            } else {
13046                if (newPackage) {
13047                    mPendingBroadcasts.put(userId, packageName, components);
13048                }
13049                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13050                    // Schedule a message
13051                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13052                }
13053            }
13054        }
13055
13056        long callingId = Binder.clearCallingIdentity();
13057        try {
13058            if (sendNow) {
13059                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13060                sendPackageChangedBroadcast(packageName,
13061                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13062            }
13063        } finally {
13064            Binder.restoreCallingIdentity(callingId);
13065        }
13066    }
13067
13068    private void sendPackageChangedBroadcast(String packageName,
13069            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13070        if (DEBUG_INSTALL)
13071            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13072                    + componentNames);
13073        Bundle extras = new Bundle(4);
13074        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13075        String nameList[] = new String[componentNames.size()];
13076        componentNames.toArray(nameList);
13077        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13078        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13079        extras.putInt(Intent.EXTRA_UID, packageUid);
13080        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13081                new int[] {UserHandle.getUserId(packageUid)});
13082    }
13083
13084    @Override
13085    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13086        if (!sUserManager.exists(userId)) return;
13087        final int uid = Binder.getCallingUid();
13088        final int permission = mContext.checkCallingOrSelfPermission(
13089                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13090        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13091        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13092        // writer
13093        synchronized (mPackages) {
13094            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
13095                    uid, userId)) {
13096                scheduleWritePackageRestrictionsLocked(userId);
13097            }
13098        }
13099    }
13100
13101    @Override
13102    public String getInstallerPackageName(String packageName) {
13103        // reader
13104        synchronized (mPackages) {
13105            return mSettings.getInstallerPackageNameLPr(packageName);
13106        }
13107    }
13108
13109    @Override
13110    public int getApplicationEnabledSetting(String packageName, int userId) {
13111        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13112        int uid = Binder.getCallingUid();
13113        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13114        // reader
13115        synchronized (mPackages) {
13116            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13117        }
13118    }
13119
13120    @Override
13121    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13122        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13123        int uid = Binder.getCallingUid();
13124        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13125        // reader
13126        synchronized (mPackages) {
13127            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13128        }
13129    }
13130
13131    @Override
13132    public void enterSafeMode() {
13133        enforceSystemOrRoot("Only the system can request entering safe mode");
13134
13135        if (!mSystemReady) {
13136            mSafeMode = true;
13137        }
13138    }
13139
13140    @Override
13141    public void systemReady() {
13142        mSystemReady = true;
13143
13144        // Read the compatibilty setting when the system is ready.
13145        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13146                mContext.getContentResolver(),
13147                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13148        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13149        if (DEBUG_SETTINGS) {
13150            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13151        }
13152
13153        synchronized (mPackages) {
13154            // Verify that all of the preferred activity components actually
13155            // exist.  It is possible for applications to be updated and at
13156            // that point remove a previously declared activity component that
13157            // had been set as a preferred activity.  We try to clean this up
13158            // the next time we encounter that preferred activity, but it is
13159            // possible for the user flow to never be able to return to that
13160            // situation so here we do a sanity check to make sure we haven't
13161            // left any junk around.
13162            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13163            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13164                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13165                removed.clear();
13166                for (PreferredActivity pa : pir.filterSet()) {
13167                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13168                        removed.add(pa);
13169                    }
13170                }
13171                if (removed.size() > 0) {
13172                    for (int r=0; r<removed.size(); r++) {
13173                        PreferredActivity pa = removed.get(r);
13174                        Slog.w(TAG, "Removing dangling preferred activity: "
13175                                + pa.mPref.mComponent);
13176                        pir.removeFilter(pa);
13177                    }
13178                    mSettings.writePackageRestrictionsLPr(
13179                            mSettings.mPreferredActivities.keyAt(i));
13180                }
13181            }
13182        }
13183        sUserManager.systemReady();
13184
13185        // Kick off any messages waiting for system ready
13186        if (mPostSystemReadyMessages != null) {
13187            for (Message msg : mPostSystemReadyMessages) {
13188                msg.sendToTarget();
13189            }
13190            mPostSystemReadyMessages = null;
13191        }
13192
13193        // Watch for external volumes that come and go over time
13194        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13195        storage.registerListener(mStorageListener);
13196
13197        mInstallerService.systemReady();
13198    }
13199
13200    @Override
13201    public boolean isSafeMode() {
13202        return mSafeMode;
13203    }
13204
13205    @Override
13206    public boolean hasSystemUidErrors() {
13207        return mHasSystemUidErrors;
13208    }
13209
13210    static String arrayToString(int[] array) {
13211        StringBuffer buf = new StringBuffer(128);
13212        buf.append('[');
13213        if (array != null) {
13214            for (int i=0; i<array.length; i++) {
13215                if (i > 0) buf.append(", ");
13216                buf.append(array[i]);
13217            }
13218        }
13219        buf.append(']');
13220        return buf.toString();
13221    }
13222
13223    static class DumpState {
13224        public static final int DUMP_LIBS = 1 << 0;
13225        public static final int DUMP_FEATURES = 1 << 1;
13226        public static final int DUMP_RESOLVERS = 1 << 2;
13227        public static final int DUMP_PERMISSIONS = 1 << 3;
13228        public static final int DUMP_PACKAGES = 1 << 4;
13229        public static final int DUMP_SHARED_USERS = 1 << 5;
13230        public static final int DUMP_MESSAGES = 1 << 6;
13231        public static final int DUMP_PROVIDERS = 1 << 7;
13232        public static final int DUMP_VERIFIERS = 1 << 8;
13233        public static final int DUMP_PREFERRED = 1 << 9;
13234        public static final int DUMP_PREFERRED_XML = 1 << 10;
13235        public static final int DUMP_KEYSETS = 1 << 11;
13236        public static final int DUMP_VERSION = 1 << 12;
13237        public static final int DUMP_INSTALLS = 1 << 13;
13238        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13239        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13240
13241        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13242
13243        private int mTypes;
13244
13245        private int mOptions;
13246
13247        private boolean mTitlePrinted;
13248
13249        private SharedUserSetting mSharedUser;
13250
13251        public boolean isDumping(int type) {
13252            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13253                return true;
13254            }
13255
13256            return (mTypes & type) != 0;
13257        }
13258
13259        public void setDump(int type) {
13260            mTypes |= type;
13261        }
13262
13263        public boolean isOptionEnabled(int option) {
13264            return (mOptions & option) != 0;
13265        }
13266
13267        public void setOptionEnabled(int option) {
13268            mOptions |= option;
13269        }
13270
13271        public boolean onTitlePrinted() {
13272            final boolean printed = mTitlePrinted;
13273            mTitlePrinted = true;
13274            return printed;
13275        }
13276
13277        public boolean getTitlePrinted() {
13278            return mTitlePrinted;
13279        }
13280
13281        public void setTitlePrinted(boolean enabled) {
13282            mTitlePrinted = enabled;
13283        }
13284
13285        public SharedUserSetting getSharedUser() {
13286            return mSharedUser;
13287        }
13288
13289        public void setSharedUser(SharedUserSetting user) {
13290            mSharedUser = user;
13291        }
13292    }
13293
13294    @Override
13295    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13296        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13297                != PackageManager.PERMISSION_GRANTED) {
13298            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13299                    + Binder.getCallingPid()
13300                    + ", uid=" + Binder.getCallingUid()
13301                    + " without permission "
13302                    + android.Manifest.permission.DUMP);
13303            return;
13304        }
13305
13306        DumpState dumpState = new DumpState();
13307        boolean fullPreferred = false;
13308        boolean checkin = false;
13309
13310        String packageName = null;
13311
13312        int opti = 0;
13313        while (opti < args.length) {
13314            String opt = args[opti];
13315            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13316                break;
13317            }
13318            opti++;
13319
13320            if ("-a".equals(opt)) {
13321                // Right now we only know how to print all.
13322            } else if ("-h".equals(opt)) {
13323                pw.println("Package manager dump options:");
13324                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13325                pw.println("    --checkin: dump for a checkin");
13326                pw.println("    -f: print details of intent filters");
13327                pw.println("    -h: print this help");
13328                pw.println("  cmd may be one of:");
13329                pw.println("    l[ibraries]: list known shared libraries");
13330                pw.println("    f[ibraries]: list device features");
13331                pw.println("    k[eysets]: print known keysets");
13332                pw.println("    r[esolvers]: dump intent resolvers");
13333                pw.println("    perm[issions]: dump permissions");
13334                pw.println("    pref[erred]: print preferred package settings");
13335                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13336                pw.println("    prov[iders]: dump content providers");
13337                pw.println("    p[ackages]: dump installed packages");
13338                pw.println("    s[hared-users]: dump shared user IDs");
13339                pw.println("    m[essages]: print collected runtime messages");
13340                pw.println("    v[erifiers]: print package verifier info");
13341                pw.println("    version: print database version info");
13342                pw.println("    write: write current settings now");
13343                pw.println("    <package.name>: info about given package");
13344                pw.println("    installs: details about install sessions");
13345                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13346                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13347                return;
13348            } else if ("--checkin".equals(opt)) {
13349                checkin = true;
13350            } else if ("-f".equals(opt)) {
13351                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13352            } else {
13353                pw.println("Unknown argument: " + opt + "; use -h for help");
13354            }
13355        }
13356
13357        // Is the caller requesting to dump a particular piece of data?
13358        if (opti < args.length) {
13359            String cmd = args[opti];
13360            opti++;
13361            // Is this a package name?
13362            if ("android".equals(cmd) || cmd.contains(".")) {
13363                packageName = cmd;
13364                // When dumping a single package, we always dump all of its
13365                // filter information since the amount of data will be reasonable.
13366                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13367            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13368                dumpState.setDump(DumpState.DUMP_LIBS);
13369            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13370                dumpState.setDump(DumpState.DUMP_FEATURES);
13371            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13372                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13373            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13374                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13375            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13376                dumpState.setDump(DumpState.DUMP_PREFERRED);
13377            } else if ("preferred-xml".equals(cmd)) {
13378                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13379                if (opti < args.length && "--full".equals(args[opti])) {
13380                    fullPreferred = true;
13381                    opti++;
13382                }
13383            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13384                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13385            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13386                dumpState.setDump(DumpState.DUMP_PACKAGES);
13387            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13388                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13389            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13390                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13391            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13392                dumpState.setDump(DumpState.DUMP_MESSAGES);
13393            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13394                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13395            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13396                    || "intent-filter-verifiers".equals(cmd)) {
13397                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13398            } else if ("version".equals(cmd)) {
13399                dumpState.setDump(DumpState.DUMP_VERSION);
13400            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13401                dumpState.setDump(DumpState.DUMP_KEYSETS);
13402            } else if ("installs".equals(cmd)) {
13403                dumpState.setDump(DumpState.DUMP_INSTALLS);
13404            } else if ("write".equals(cmd)) {
13405                synchronized (mPackages) {
13406                    mSettings.writeLPr();
13407                    pw.println("Settings written.");
13408                    return;
13409                }
13410            }
13411        }
13412
13413        if (checkin) {
13414            pw.println("vers,1");
13415        }
13416
13417        // reader
13418        synchronized (mPackages) {
13419            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13420                if (!checkin) {
13421                    if (dumpState.onTitlePrinted())
13422                        pw.println();
13423                    pw.println("Database versions:");
13424                    pw.print("  SDK Version:");
13425                    pw.print(" internal=");
13426                    pw.print(mSettings.mInternalSdkPlatform);
13427                    pw.print(" external=");
13428                    pw.println(mSettings.mExternalSdkPlatform);
13429                    pw.print("  DB Version:");
13430                    pw.print(" internal=");
13431                    pw.print(mSettings.mInternalDatabaseVersion);
13432                    pw.print(" external=");
13433                    pw.println(mSettings.mExternalDatabaseVersion);
13434                }
13435            }
13436
13437            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13438                if (!checkin) {
13439                    if (dumpState.onTitlePrinted())
13440                        pw.println();
13441                    pw.println("Verifiers:");
13442                    pw.print("  Required: ");
13443                    pw.print(mRequiredVerifierPackage);
13444                    pw.print(" (uid=");
13445                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13446                    pw.println(")");
13447                } else if (mRequiredVerifierPackage != null) {
13448                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13449                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13450                }
13451            }
13452
13453            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13454                    packageName == null) {
13455                if (mIntentFilterVerifierComponent != null) {
13456                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13457                    if (!checkin) {
13458                        if (dumpState.onTitlePrinted())
13459                            pw.println();
13460                        pw.println("Intent Filter Verifier:");
13461                        pw.print("  Using: ");
13462                        pw.print(verifierPackageName);
13463                        pw.print(" (uid=");
13464                        pw.print(getPackageUid(verifierPackageName, 0));
13465                        pw.println(")");
13466                    } else if (verifierPackageName != null) {
13467                        pw.print("ifv,"); pw.print(verifierPackageName);
13468                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13469                    }
13470                } else {
13471                    pw.println();
13472                    pw.println("No Intent Filter Verifier available!");
13473                }
13474            }
13475
13476            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13477                boolean printedHeader = false;
13478                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13479                while (it.hasNext()) {
13480                    String name = it.next();
13481                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13482                    if (!checkin) {
13483                        if (!printedHeader) {
13484                            if (dumpState.onTitlePrinted())
13485                                pw.println();
13486                            pw.println("Libraries:");
13487                            printedHeader = true;
13488                        }
13489                        pw.print("  ");
13490                    } else {
13491                        pw.print("lib,");
13492                    }
13493                    pw.print(name);
13494                    if (!checkin) {
13495                        pw.print(" -> ");
13496                    }
13497                    if (ent.path != null) {
13498                        if (!checkin) {
13499                            pw.print("(jar) ");
13500                            pw.print(ent.path);
13501                        } else {
13502                            pw.print(",jar,");
13503                            pw.print(ent.path);
13504                        }
13505                    } else {
13506                        if (!checkin) {
13507                            pw.print("(apk) ");
13508                            pw.print(ent.apk);
13509                        } else {
13510                            pw.print(",apk,");
13511                            pw.print(ent.apk);
13512                        }
13513                    }
13514                    pw.println();
13515                }
13516            }
13517
13518            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
13519                if (dumpState.onTitlePrinted())
13520                    pw.println();
13521                if (!checkin) {
13522                    pw.println("Features:");
13523                }
13524                Iterator<String> it = mAvailableFeatures.keySet().iterator();
13525                while (it.hasNext()) {
13526                    String name = it.next();
13527                    if (!checkin) {
13528                        pw.print("  ");
13529                    } else {
13530                        pw.print("feat,");
13531                    }
13532                    pw.println(name);
13533                }
13534            }
13535
13536            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
13537                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
13538                        : "Activity Resolver Table:", "  ", packageName,
13539                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13540                    dumpState.setTitlePrinted(true);
13541                }
13542                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
13543                        : "Receiver Resolver Table:", "  ", packageName,
13544                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13545                    dumpState.setTitlePrinted(true);
13546                }
13547                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
13548                        : "Service Resolver Table:", "  ", packageName,
13549                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13550                    dumpState.setTitlePrinted(true);
13551                }
13552                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
13553                        : "Provider Resolver Table:", "  ", packageName,
13554                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13555                    dumpState.setTitlePrinted(true);
13556                }
13557            }
13558
13559            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
13560                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13561                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13562                    int user = mSettings.mPreferredActivities.keyAt(i);
13563                    if (pir.dump(pw,
13564                            dumpState.getTitlePrinted()
13565                                ? "\nPreferred Activities User " + user + ":"
13566                                : "Preferred Activities User " + user + ":", "  ",
13567                            packageName, true, false)) {
13568                        dumpState.setTitlePrinted(true);
13569                    }
13570                }
13571            }
13572
13573            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
13574                pw.flush();
13575                FileOutputStream fout = new FileOutputStream(fd);
13576                BufferedOutputStream str = new BufferedOutputStream(fout);
13577                XmlSerializer serializer = new FastXmlSerializer();
13578                try {
13579                    serializer.setOutput(str, "utf-8");
13580                    serializer.startDocument(null, true);
13581                    serializer.setFeature(
13582                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
13583                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
13584                    serializer.endDocument();
13585                    serializer.flush();
13586                } catch (IllegalArgumentException e) {
13587                    pw.println("Failed writing: " + e);
13588                } catch (IllegalStateException e) {
13589                    pw.println("Failed writing: " + e);
13590                } catch (IOException e) {
13591                    pw.println("Failed writing: " + e);
13592                }
13593            }
13594
13595            if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) {
13596                pw.println();
13597                int count = mSettings.mPackages.size();
13598                if (count == 0) {
13599                    pw.println("No domain preferred apps!");
13600                    pw.println();
13601                } else {
13602                    final String prefix = "  ";
13603                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
13604                    if (allPackageSettings.size() == 0) {
13605                        pw.println("No domain preferred apps!");
13606                        pw.println();
13607                    } else {
13608                        pw.println("Domain preferred apps status:");
13609                        pw.println();
13610                        count = 0;
13611                        for (PackageSetting ps : allPackageSettings) {
13612                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13613                            if (ivi == null || ivi.getPackageName() == null) continue;
13614                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
13615                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
13616                            pw.println(prefix + "Status: " + ivi.getStatusString());
13617                            pw.println();
13618                            count++;
13619                        }
13620                        if (count == 0) {
13621                            pw.println(prefix + "No domain preferred app status!");
13622                            pw.println();
13623                        }
13624                        for (int userId : sUserManager.getUserIds()) {
13625                            pw.println("Domain preferred apps for User " + userId + ":");
13626                            pw.println();
13627                            count = 0;
13628                            for (PackageSetting ps : allPackageSettings) {
13629                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13630                                if (ivi == null || ivi.getPackageName() == null) {
13631                                    continue;
13632                                }
13633                                final int status = ps.getDomainVerificationStatusForUser(userId);
13634                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
13635                                    continue;
13636                                }
13637                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
13638                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
13639                                String statusStr = IntentFilterVerificationInfo.
13640                                        getStatusStringFromValue(status);
13641                                pw.println(prefix + "Status: " + statusStr);
13642                                pw.println();
13643                                count++;
13644                            }
13645                            if (count == 0) {
13646                                pw.println(prefix + "No domain preferred apps!");
13647                                pw.println();
13648                            }
13649                        }
13650                    }
13651                }
13652            }
13653
13654            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
13655                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
13656                if (packageName == null) {
13657                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
13658                        if (iperm == 0) {
13659                            if (dumpState.onTitlePrinted())
13660                                pw.println();
13661                            pw.println("AppOp Permissions:");
13662                        }
13663                        pw.print("  AppOp Permission ");
13664                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
13665                        pw.println(":");
13666                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
13667                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
13668                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
13669                        }
13670                    }
13671                }
13672            }
13673
13674            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
13675                boolean printedSomething = false;
13676                for (PackageParser.Provider p : mProviders.mProviders.values()) {
13677                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13678                        continue;
13679                    }
13680                    if (!printedSomething) {
13681                        if (dumpState.onTitlePrinted())
13682                            pw.println();
13683                        pw.println("Registered ContentProviders:");
13684                        printedSomething = true;
13685                    }
13686                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
13687                    pw.print("    "); pw.println(p.toString());
13688                }
13689                printedSomething = false;
13690                for (Map.Entry<String, PackageParser.Provider> entry :
13691                        mProvidersByAuthority.entrySet()) {
13692                    PackageParser.Provider p = entry.getValue();
13693                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13694                        continue;
13695                    }
13696                    if (!printedSomething) {
13697                        if (dumpState.onTitlePrinted())
13698                            pw.println();
13699                        pw.println("ContentProvider Authorities:");
13700                        printedSomething = true;
13701                    }
13702                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
13703                    pw.print("    "); pw.println(p.toString());
13704                    if (p.info != null && p.info.applicationInfo != null) {
13705                        final String appInfo = p.info.applicationInfo.toString();
13706                        pw.print("      applicationInfo="); pw.println(appInfo);
13707                    }
13708                }
13709            }
13710
13711            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
13712                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
13713            }
13714
13715            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
13716                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
13717            }
13718
13719            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
13720                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
13721            }
13722
13723            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
13724                // XXX should handle packageName != null by dumping only install data that
13725                // the given package is involved with.
13726                if (dumpState.onTitlePrinted()) pw.println();
13727                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
13728            }
13729
13730            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
13731                if (dumpState.onTitlePrinted()) pw.println();
13732                mSettings.dumpReadMessagesLPr(pw, dumpState);
13733
13734                pw.println();
13735                pw.println("Package warning messages:");
13736                BufferedReader in = null;
13737                String line = null;
13738                try {
13739                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
13740                    while ((line = in.readLine()) != null) {
13741                        if (line.contains("ignored: updated version")) continue;
13742                        pw.println(line);
13743                    }
13744                } catch (IOException ignored) {
13745                } finally {
13746                    IoUtils.closeQuietly(in);
13747                }
13748            }
13749
13750            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
13751                BufferedReader in = null;
13752                String line = null;
13753                try {
13754                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
13755                    while ((line = in.readLine()) != null) {
13756                        if (line.contains("ignored: updated version")) continue;
13757                        pw.print("msg,");
13758                        pw.println(line);
13759                    }
13760                } catch (IOException ignored) {
13761                } finally {
13762                    IoUtils.closeQuietly(in);
13763                }
13764            }
13765        }
13766    }
13767
13768    // ------- apps on sdcard specific code -------
13769    static final boolean DEBUG_SD_INSTALL = false;
13770
13771    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
13772
13773    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
13774
13775    private boolean mMediaMounted = false;
13776
13777    static String getEncryptKey() {
13778        try {
13779            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
13780                    SD_ENCRYPTION_KEYSTORE_NAME);
13781            if (sdEncKey == null) {
13782                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
13783                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
13784                if (sdEncKey == null) {
13785                    Slog.e(TAG, "Failed to create encryption keys");
13786                    return null;
13787                }
13788            }
13789            return sdEncKey;
13790        } catch (NoSuchAlgorithmException nsae) {
13791            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
13792            return null;
13793        } catch (IOException ioe) {
13794            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
13795            return null;
13796        }
13797    }
13798
13799    /*
13800     * Update media status on PackageManager.
13801     */
13802    @Override
13803    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
13804        int callingUid = Binder.getCallingUid();
13805        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
13806            throw new SecurityException("Media status can only be updated by the system");
13807        }
13808        // reader; this apparently protects mMediaMounted, but should probably
13809        // be a different lock in that case.
13810        synchronized (mPackages) {
13811            Log.i(TAG, "Updating external media status from "
13812                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
13813                    + (mediaStatus ? "mounted" : "unmounted"));
13814            if (DEBUG_SD_INSTALL)
13815                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
13816                        + ", mMediaMounted=" + mMediaMounted);
13817            if (mediaStatus == mMediaMounted) {
13818                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
13819                        : 0, -1);
13820                mHandler.sendMessage(msg);
13821                return;
13822            }
13823            mMediaMounted = mediaStatus;
13824        }
13825        // Queue up an async operation since the package installation may take a
13826        // little while.
13827        mHandler.post(new Runnable() {
13828            public void run() {
13829                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
13830            }
13831        });
13832    }
13833
13834    /**
13835     * Called by MountService when the initial ASECs to scan are available.
13836     * Should block until all the ASEC containers are finished being scanned.
13837     */
13838    public void scanAvailableAsecs() {
13839        updateExternalMediaStatusInner(true, false, false);
13840        if (mShouldRestoreconData) {
13841            SELinuxMMAC.setRestoreconDone();
13842            mShouldRestoreconData = false;
13843        }
13844    }
13845
13846    /*
13847     * Collect information of applications on external media, map them against
13848     * existing containers and update information based on current mount status.
13849     * Please note that we always have to report status if reportStatus has been
13850     * set to true especially when unloading packages.
13851     */
13852    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
13853            boolean externalStorage) {
13854        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
13855        int[] uidArr = EmptyArray.INT;
13856
13857        final String[] list = PackageHelper.getSecureContainerList();
13858        if (ArrayUtils.isEmpty(list)) {
13859            Log.i(TAG, "No secure containers found");
13860        } else {
13861            // Process list of secure containers and categorize them
13862            // as active or stale based on their package internal state.
13863
13864            // reader
13865            synchronized (mPackages) {
13866                for (String cid : list) {
13867                    // Leave stages untouched for now; installer service owns them
13868                    if (PackageInstallerService.isStageName(cid)) continue;
13869
13870                    if (DEBUG_SD_INSTALL)
13871                        Log.i(TAG, "Processing container " + cid);
13872                    String pkgName = getAsecPackageName(cid);
13873                    if (pkgName == null) {
13874                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
13875                        continue;
13876                    }
13877                    if (DEBUG_SD_INSTALL)
13878                        Log.i(TAG, "Looking for pkg : " + pkgName);
13879
13880                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
13881                    if (ps == null) {
13882                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
13883                        continue;
13884                    }
13885
13886                    /*
13887                     * Skip packages that are not external if we're unmounting
13888                     * external storage.
13889                     */
13890                    if (externalStorage && !isMounted && !isExternal(ps)) {
13891                        continue;
13892                    }
13893
13894                    final AsecInstallArgs args = new AsecInstallArgs(cid,
13895                            getAppDexInstructionSets(ps), ps.isForwardLocked());
13896                    // The package status is changed only if the code path
13897                    // matches between settings and the container id.
13898                    if (ps.codePathString != null
13899                            && ps.codePathString.startsWith(args.getCodePath())) {
13900                        if (DEBUG_SD_INSTALL) {
13901                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
13902                                    + " at code path: " + ps.codePathString);
13903                        }
13904
13905                        // We do have a valid package installed on sdcard
13906                        processCids.put(args, ps.codePathString);
13907                        final int uid = ps.appId;
13908                        if (uid != -1) {
13909                            uidArr = ArrayUtils.appendInt(uidArr, uid);
13910                        }
13911                    } else {
13912                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
13913                                + ps.codePathString);
13914                    }
13915                }
13916            }
13917
13918            Arrays.sort(uidArr);
13919        }
13920
13921        // Process packages with valid entries.
13922        if (isMounted) {
13923            if (DEBUG_SD_INSTALL)
13924                Log.i(TAG, "Loading packages");
13925            loadMediaPackages(processCids, uidArr);
13926            startCleaningPackages();
13927            mInstallerService.onSecureContainersAvailable();
13928        } else {
13929            if (DEBUG_SD_INSTALL)
13930                Log.i(TAG, "Unloading packages");
13931            unloadMediaPackages(processCids, uidArr, reportStatus);
13932        }
13933    }
13934
13935    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13936            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
13937        final int size = infos.size();
13938        final String[] packageNames = new String[size];
13939        final int[] packageUids = new int[size];
13940        for (int i = 0; i < size; i++) {
13941            final ApplicationInfo info = infos.get(i);
13942            packageNames[i] = info.packageName;
13943            packageUids[i] = info.uid;
13944        }
13945        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
13946                finishedReceiver);
13947    }
13948
13949    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13950            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
13951        sendResourcesChangedBroadcast(mediaStatus, replacing,
13952                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
13953    }
13954
13955    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13956            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
13957        int size = pkgList.length;
13958        if (size > 0) {
13959            // Send broadcasts here
13960            Bundle extras = new Bundle();
13961            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13962            if (uidArr != null) {
13963                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
13964            }
13965            if (replacing) {
13966                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
13967            }
13968            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
13969                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
13970            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
13971        }
13972    }
13973
13974   /*
13975     * Look at potentially valid container ids from processCids If package
13976     * information doesn't match the one on record or package scanning fails,
13977     * the cid is added to list of removeCids. We currently don't delete stale
13978     * containers.
13979     */
13980    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
13981        ArrayList<String> pkgList = new ArrayList<String>();
13982        Set<AsecInstallArgs> keys = processCids.keySet();
13983
13984        for (AsecInstallArgs args : keys) {
13985            String codePath = processCids.get(args);
13986            if (DEBUG_SD_INSTALL)
13987                Log.i(TAG, "Loading container : " + args.cid);
13988            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13989            try {
13990                // Make sure there are no container errors first.
13991                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
13992                    Slog.e(TAG, "Failed to mount cid : " + args.cid
13993                            + " when installing from sdcard");
13994                    continue;
13995                }
13996                // Check code path here.
13997                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
13998                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
13999                            + " does not match one in settings " + codePath);
14000                    continue;
14001                }
14002                // Parse package
14003                int parseFlags = mDefParseFlags;
14004                if (args.isExternalAsec()) {
14005                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14006                }
14007                if (args.isFwdLocked()) {
14008                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14009                }
14010
14011                synchronized (mInstallLock) {
14012                    PackageParser.Package pkg = null;
14013                    try {
14014                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14015                    } catch (PackageManagerException e) {
14016                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14017                    }
14018                    // Scan the package
14019                    if (pkg != null) {
14020                        /*
14021                         * TODO why is the lock being held? doPostInstall is
14022                         * called in other places without the lock. This needs
14023                         * to be straightened out.
14024                         */
14025                        // writer
14026                        synchronized (mPackages) {
14027                            retCode = PackageManager.INSTALL_SUCCEEDED;
14028                            pkgList.add(pkg.packageName);
14029                            // Post process args
14030                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14031                                    pkg.applicationInfo.uid);
14032                        }
14033                    } else {
14034                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14035                    }
14036                }
14037
14038            } finally {
14039                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14040                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14041                }
14042            }
14043        }
14044        // writer
14045        synchronized (mPackages) {
14046            // If the platform SDK has changed since the last time we booted,
14047            // we need to re-grant app permission to catch any new ones that
14048            // appear. This is really a hack, and means that apps can in some
14049            // cases get permissions that the user didn't initially explicitly
14050            // allow... it would be nice to have some better way to handle
14051            // this situation.
14052            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14053            if (regrantPermissions)
14054                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14055                        + mSdkVersion + "; regranting permissions for external storage");
14056            mSettings.mExternalSdkPlatform = mSdkVersion;
14057
14058            // Make sure group IDs have been assigned, and any permission
14059            // changes in other apps are accounted for
14060            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14061                    | (regrantPermissions
14062                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14063                            : 0));
14064
14065            mSettings.updateExternalDatabaseVersion();
14066
14067            // can downgrade to reader
14068            // Persist settings
14069            mSettings.writeLPr();
14070        }
14071        // Send a broadcast to let everyone know we are done processing
14072        if (pkgList.size() > 0) {
14073            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14074        }
14075    }
14076
14077   /*
14078     * Utility method to unload a list of specified containers
14079     */
14080    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14081        // Just unmount all valid containers.
14082        for (AsecInstallArgs arg : cidArgs) {
14083            synchronized (mInstallLock) {
14084                arg.doPostDeleteLI(false);
14085           }
14086       }
14087   }
14088
14089    /*
14090     * Unload packages mounted on external media. This involves deleting package
14091     * data from internal structures, sending broadcasts about diabled packages,
14092     * gc'ing to free up references, unmounting all secure containers
14093     * corresponding to packages on external media, and posting a
14094     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14095     * that we always have to post this message if status has been requested no
14096     * matter what.
14097     */
14098    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14099            final boolean reportStatus) {
14100        if (DEBUG_SD_INSTALL)
14101            Log.i(TAG, "unloading media packages");
14102        ArrayList<String> pkgList = new ArrayList<String>();
14103        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14104        final Set<AsecInstallArgs> keys = processCids.keySet();
14105        for (AsecInstallArgs args : keys) {
14106            String pkgName = args.getPackageName();
14107            if (DEBUG_SD_INSTALL)
14108                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14109            // Delete package internally
14110            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14111            synchronized (mInstallLock) {
14112                boolean res = deletePackageLI(pkgName, null, false, null, null,
14113                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14114                if (res) {
14115                    pkgList.add(pkgName);
14116                } else {
14117                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14118                    failedList.add(args);
14119                }
14120            }
14121        }
14122
14123        // reader
14124        synchronized (mPackages) {
14125            // We didn't update the settings after removing each package;
14126            // write them now for all packages.
14127            mSettings.writeLPr();
14128        }
14129
14130        // We have to absolutely send UPDATED_MEDIA_STATUS only
14131        // after confirming that all the receivers processed the ordered
14132        // broadcast when packages get disabled, force a gc to clean things up.
14133        // and unload all the containers.
14134        if (pkgList.size() > 0) {
14135            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14136                    new IIntentReceiver.Stub() {
14137                public void performReceive(Intent intent, int resultCode, String data,
14138                        Bundle extras, boolean ordered, boolean sticky,
14139                        int sendingUser) throws RemoteException {
14140                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14141                            reportStatus ? 1 : 0, 1, keys);
14142                    mHandler.sendMessage(msg);
14143                }
14144            });
14145        } else {
14146            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14147                    keys);
14148            mHandler.sendMessage(msg);
14149        }
14150    }
14151
14152    private void loadPrivatePackages(VolumeInfo vol) {
14153        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14154        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14155        synchronized (mPackages) {
14156            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14157            for (PackageSetting ps : packages) {
14158                synchronized (mInstallLock) {
14159                    final PackageParser.Package pkg;
14160                    try {
14161                        pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14162                        loaded.add(pkg.applicationInfo);
14163                    } catch (PackageManagerException e) {
14164                        Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14165                    }
14166                }
14167            }
14168
14169            // TODO: regrant any permissions that changed based since original install
14170
14171            mSettings.writeLPr();
14172        }
14173
14174        Slog.d(TAG, "Loaded packages " + loaded);
14175        sendResourcesChangedBroadcast(true, false, loaded, null);
14176    }
14177
14178    private void unloadPrivatePackages(VolumeInfo vol) {
14179        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14180        synchronized (mPackages) {
14181            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14182            for (PackageSetting ps : packages) {
14183                if (ps.pkg == null) continue;
14184                synchronized (mInstallLock) {
14185                    final ApplicationInfo info = ps.pkg.applicationInfo;
14186                    final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14187                    if (deletePackageLI(ps.name, null, false, null, null,
14188                            PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14189                        unloaded.add(info);
14190                    } else {
14191                        Slog.w(TAG, "Failed to unload " + ps.codePath);
14192                    }
14193                }
14194            }
14195
14196            mSettings.writeLPr();
14197        }
14198
14199        Slog.d(TAG, "Unloaded packages " + unloaded);
14200        sendResourcesChangedBroadcast(false, false, unloaded, null);
14201    }
14202
14203    @Override
14204    public int movePackage(final String packageName, final String volumeUuid) {
14205        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14206
14207        final int moveId = mNextMoveId.getAndIncrement();
14208        try {
14209            movePackageInternal(packageName, volumeUuid, moveId);
14210        } catch (PackageManagerException e) {
14211            Slog.d(TAG, "Failed to move " + packageName, e);
14212            mMoveCallbacks.notifyStatusChanged(moveId,
14213                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14214        }
14215        return moveId;
14216    }
14217
14218    private void movePackageInternal(final String packageName, final String volumeUuid,
14219            final int moveId) throws PackageManagerException {
14220        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14221        final PackageManager pm = mContext.getPackageManager();
14222
14223        final boolean currentAsec;
14224        final String currentVolumeUuid;
14225        final File codeFile;
14226        final String installerPackageName;
14227        final String packageAbiOverride;
14228        final int appId;
14229        final String seinfo;
14230        final String label;
14231
14232        // reader
14233        synchronized (mPackages) {
14234            final PackageParser.Package pkg = mPackages.get(packageName);
14235            final PackageSetting ps = mSettings.mPackages.get(packageName);
14236            if (pkg == null || ps == null) {
14237                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14238            }
14239
14240            if (pkg.applicationInfo.isSystemApp()) {
14241                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14242                        "Cannot move system application");
14243            } else if (pkg.mOperationPending) {
14244                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14245                        "Attempt to move package which has pending operations");
14246            }
14247
14248            // TODO: yell if already in desired location
14249
14250            pkg.mOperationPending = true;
14251
14252            currentAsec = pkg.applicationInfo.isForwardLocked()
14253                    || pkg.applicationInfo.isExternalAsec();
14254            currentVolumeUuid = ps.volumeUuid;
14255            codeFile = new File(pkg.codePath);
14256            installerPackageName = ps.installerPackageName;
14257            packageAbiOverride = ps.cpuAbiOverrideString;
14258            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14259            seinfo = pkg.applicationInfo.seinfo;
14260            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
14261        }
14262
14263        final Bundle extras = new Bundle();
14264        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
14265        extras.putString(Intent.EXTRA_TITLE, label);
14266        mMoveCallbacks.notifyCreated(moveId, extras);
14267
14268        int installFlags;
14269        final boolean moveData;
14270
14271        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
14272            installFlags = INSTALL_INTERNAL;
14273            moveData = !currentAsec;
14274        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
14275            installFlags = INSTALL_EXTERNAL;
14276            moveData = false;
14277        } else {
14278            final StorageManager storage = mContext.getSystemService(StorageManager.class);
14279            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
14280            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
14281                    || !volume.isMountedWritable()) {
14282                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14283                        "Move location not mounted private volume");
14284            }
14285
14286            Preconditions.checkState(!currentAsec);
14287
14288            installFlags = INSTALL_INTERNAL;
14289            moveData = true;
14290        }
14291
14292        Slog.d(TAG, "Moving " + packageName + " from " + currentVolumeUuid + " to " + volumeUuid);
14293        mMoveCallbacks.notifyStatusChanged(moveId, 10);
14294
14295        if (moveData) {
14296            synchronized (mInstallLock) {
14297                // TODO: split this into separate copy and delete operations
14298                if (mInstaller.moveUserDataDirs(currentVolumeUuid, volumeUuid, packageName, appId,
14299                        seinfo) != 0) {
14300                    synchronized (mPackages) {
14301                        final PackageParser.Package pkg = mPackages.get(packageName);
14302                        if (pkg != null) {
14303                            pkg.mOperationPending = false;
14304                        }
14305                    }
14306
14307                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14308                            "Failed to move private data");
14309                }
14310            }
14311        }
14312
14313        mMoveCallbacks.notifyStatusChanged(moveId, 50);
14314
14315        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14316            @Override
14317            public void onUserActionRequired(Intent intent) throws RemoteException {
14318                throw new IllegalStateException();
14319            }
14320
14321            @Override
14322            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14323                    Bundle extras) throws RemoteException {
14324                Slog.d(TAG, "Install result for move: "
14325                        + PackageManager.installStatusToString(returnCode, msg));
14326
14327                // We usually have a new package now after the install, but if
14328                // we failed we need to clear the pending flag on the original
14329                // package object.
14330                synchronized (mPackages) {
14331                    final PackageParser.Package pkg = mPackages.get(packageName);
14332                    if (pkg != null) {
14333                        pkg.mOperationPending = false;
14334                    }
14335                }
14336
14337                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14338                switch (status) {
14339                    case PackageInstaller.STATUS_SUCCESS:
14340                        mMoveCallbacks.notifyStatusChanged(moveId,
14341                                PackageManager.MOVE_SUCCEEDED);
14342                        break;
14343                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14344                        mMoveCallbacks.notifyStatusChanged(moveId,
14345                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14346                        break;
14347                    default:
14348                        mMoveCallbacks.notifyStatusChanged(moveId,
14349                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14350                        break;
14351                }
14352            }
14353        };
14354
14355        // Treat a move like reinstalling an existing app, which ensures that we
14356        // process everythign uniformly, like unpacking native libraries.
14357        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14358
14359        final Message msg = mHandler.obtainMessage(INIT_COPY);
14360        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14361        msg.obj = new InstallParams(origin, installObserver, installFlags,
14362                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14363        mHandler.sendMessage(msg);
14364    }
14365
14366    @Override
14367    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
14368        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14369
14370        final int realMoveId = mNextMoveId.getAndIncrement();
14371        final Bundle extras = new Bundle();
14372        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
14373        mMoveCallbacks.notifyCreated(realMoveId, extras);
14374
14375        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
14376            @Override
14377            public void onCreated(int moveId, Bundle extras) {
14378                // Ignored
14379            }
14380
14381            @Override
14382            public void onStatusChanged(int moveId, int status, long estMillis) {
14383                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
14384            }
14385        };
14386
14387        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14388        storage.setPrimaryStorageUuid(volumeUuid, callback);
14389        return realMoveId;
14390    }
14391
14392    @Override
14393    public int getMoveStatus(int moveId) {
14394        mContext.enforceCallingOrSelfPermission(
14395                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14396        return mMoveCallbacks.mLastStatus.get(moveId);
14397    }
14398
14399    @Override
14400    public void registerMoveCallback(IPackageMoveObserver callback) {
14401        mContext.enforceCallingOrSelfPermission(
14402                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14403        mMoveCallbacks.register(callback);
14404    }
14405
14406    @Override
14407    public void unregisterMoveCallback(IPackageMoveObserver callback) {
14408        mContext.enforceCallingOrSelfPermission(
14409                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14410        mMoveCallbacks.unregister(callback);
14411    }
14412
14413    @Override
14414    public boolean setInstallLocation(int loc) {
14415        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14416                null);
14417        if (getInstallLocation() == loc) {
14418            return true;
14419        }
14420        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14421                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14422            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14423                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14424            return true;
14425        }
14426        return false;
14427   }
14428
14429    @Override
14430    public int getInstallLocation() {
14431        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14432                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14433                PackageHelper.APP_INSTALL_AUTO);
14434    }
14435
14436    /** Called by UserManagerService */
14437    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14438        mDirtyUsers.remove(userHandle);
14439        mSettings.removeUserLPw(userHandle);
14440        mPendingBroadcasts.remove(userHandle);
14441        if (mInstaller != null) {
14442            // Technically, we shouldn't be doing this with the package lock
14443            // held.  However, this is very rare, and there is already so much
14444            // other disk I/O going on, that we'll let it slide for now.
14445            final StorageManager storage = StorageManager.from(mContext);
14446            final List<VolumeInfo> vols = storage.getVolumes();
14447            for (VolumeInfo vol : vols) {
14448                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
14449                    final String volumeUuid = vol.getFsUuid();
14450                    Slog.d(TAG, "Removing user data on volume " + volumeUuid);
14451                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
14452                }
14453            }
14454        }
14455        mUserNeedsBadging.delete(userHandle);
14456        removeUnusedPackagesLILPw(userManager, userHandle);
14457    }
14458
14459    /**
14460     * We're removing userHandle and would like to remove any downloaded packages
14461     * that are no longer in use by any other user.
14462     * @param userHandle the user being removed
14463     */
14464    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
14465        final boolean DEBUG_CLEAN_APKS = false;
14466        int [] users = userManager.getUserIdsLPr();
14467        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
14468        while (psit.hasNext()) {
14469            PackageSetting ps = psit.next();
14470            if (ps.pkg == null) {
14471                continue;
14472            }
14473            final String packageName = ps.pkg.packageName;
14474            // Skip over if system app
14475            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14476                continue;
14477            }
14478            if (DEBUG_CLEAN_APKS) {
14479                Slog.i(TAG, "Checking package " + packageName);
14480            }
14481            boolean keep = false;
14482            for (int i = 0; i < users.length; i++) {
14483                if (users[i] != userHandle && ps.getInstalled(users[i])) {
14484                    keep = true;
14485                    if (DEBUG_CLEAN_APKS) {
14486                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
14487                                + users[i]);
14488                    }
14489                    break;
14490                }
14491            }
14492            if (!keep) {
14493                if (DEBUG_CLEAN_APKS) {
14494                    Slog.i(TAG, "  Removing package " + packageName);
14495                }
14496                mHandler.post(new Runnable() {
14497                    public void run() {
14498                        deletePackageX(packageName, userHandle, 0);
14499                    } //end run
14500                });
14501            }
14502        }
14503    }
14504
14505    /** Called by UserManagerService */
14506    void createNewUserLILPw(int userHandle, File path) {
14507        if (mInstaller != null) {
14508            mInstaller.createUserConfig(userHandle);
14509            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
14510        }
14511    }
14512
14513    void newUserCreatedLILPw(int userHandle) {
14514        // Adding a user requires updating runtime permissions for system apps.
14515        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
14516    }
14517
14518    @Override
14519    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
14520        mContext.enforceCallingOrSelfPermission(
14521                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14522                "Only package verification agents can read the verifier device identity");
14523
14524        synchronized (mPackages) {
14525            return mSettings.getVerifierDeviceIdentityLPw();
14526        }
14527    }
14528
14529    @Override
14530    public void setPermissionEnforced(String permission, boolean enforced) {
14531        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
14532        if (READ_EXTERNAL_STORAGE.equals(permission)) {
14533            synchronized (mPackages) {
14534                if (mSettings.mReadExternalStorageEnforced == null
14535                        || mSettings.mReadExternalStorageEnforced != enforced) {
14536                    mSettings.mReadExternalStorageEnforced = enforced;
14537                    mSettings.writeLPr();
14538                }
14539            }
14540            // kill any non-foreground processes so we restart them and
14541            // grant/revoke the GID.
14542            final IActivityManager am = ActivityManagerNative.getDefault();
14543            if (am != null) {
14544                final long token = Binder.clearCallingIdentity();
14545                try {
14546                    am.killProcessesBelowForeground("setPermissionEnforcement");
14547                } catch (RemoteException e) {
14548                } finally {
14549                    Binder.restoreCallingIdentity(token);
14550                }
14551            }
14552        } else {
14553            throw new IllegalArgumentException("No selective enforcement for " + permission);
14554        }
14555    }
14556
14557    @Override
14558    @Deprecated
14559    public boolean isPermissionEnforced(String permission) {
14560        return true;
14561    }
14562
14563    @Override
14564    public boolean isStorageLow() {
14565        final long token = Binder.clearCallingIdentity();
14566        try {
14567            final DeviceStorageMonitorInternal
14568                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14569            if (dsm != null) {
14570                return dsm.isMemoryLow();
14571            } else {
14572                return false;
14573            }
14574        } finally {
14575            Binder.restoreCallingIdentity(token);
14576        }
14577    }
14578
14579    @Override
14580    public IPackageInstaller getPackageInstaller() {
14581        return mInstallerService;
14582    }
14583
14584    private boolean userNeedsBadging(int userId) {
14585        int index = mUserNeedsBadging.indexOfKey(userId);
14586        if (index < 0) {
14587            final UserInfo userInfo;
14588            final long token = Binder.clearCallingIdentity();
14589            try {
14590                userInfo = sUserManager.getUserInfo(userId);
14591            } finally {
14592                Binder.restoreCallingIdentity(token);
14593            }
14594            final boolean b;
14595            if (userInfo != null && userInfo.isManagedProfile()) {
14596                b = true;
14597            } else {
14598                b = false;
14599            }
14600            mUserNeedsBadging.put(userId, b);
14601            return b;
14602        }
14603        return mUserNeedsBadging.valueAt(index);
14604    }
14605
14606    @Override
14607    public KeySet getKeySetByAlias(String packageName, String alias) {
14608        if (packageName == null || alias == null) {
14609            return null;
14610        }
14611        synchronized(mPackages) {
14612            final PackageParser.Package pkg = mPackages.get(packageName);
14613            if (pkg == null) {
14614                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14615                throw new IllegalArgumentException("Unknown package: " + packageName);
14616            }
14617            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14618            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
14619        }
14620    }
14621
14622    @Override
14623    public KeySet getSigningKeySet(String packageName) {
14624        if (packageName == null) {
14625            return null;
14626        }
14627        synchronized(mPackages) {
14628            final PackageParser.Package pkg = mPackages.get(packageName);
14629            if (pkg == null) {
14630                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14631                throw new IllegalArgumentException("Unknown package: " + packageName);
14632            }
14633            if (pkg.applicationInfo.uid != Binder.getCallingUid()
14634                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
14635                throw new SecurityException("May not access signing KeySet of other apps.");
14636            }
14637            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14638            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
14639        }
14640    }
14641
14642    @Override
14643    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
14644        if (packageName == null || ks == null) {
14645            return false;
14646        }
14647        synchronized(mPackages) {
14648            final PackageParser.Package pkg = mPackages.get(packageName);
14649            if (pkg == null) {
14650                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14651                throw new IllegalArgumentException("Unknown package: " + packageName);
14652            }
14653            IBinder ksh = ks.getToken();
14654            if (ksh instanceof KeySetHandle) {
14655                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14656                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
14657            }
14658            return false;
14659        }
14660    }
14661
14662    @Override
14663    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
14664        if (packageName == null || ks == null) {
14665            return false;
14666        }
14667        synchronized(mPackages) {
14668            final PackageParser.Package pkg = mPackages.get(packageName);
14669            if (pkg == null) {
14670                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14671                throw new IllegalArgumentException("Unknown package: " + packageName);
14672            }
14673            IBinder ksh = ks.getToken();
14674            if (ksh instanceof KeySetHandle) {
14675                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14676                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
14677            }
14678            return false;
14679        }
14680    }
14681
14682    public void getUsageStatsIfNoPackageUsageInfo() {
14683        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
14684            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
14685            if (usm == null) {
14686                throw new IllegalStateException("UsageStatsManager must be initialized");
14687            }
14688            long now = System.currentTimeMillis();
14689            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
14690            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
14691                String packageName = entry.getKey();
14692                PackageParser.Package pkg = mPackages.get(packageName);
14693                if (pkg == null) {
14694                    continue;
14695                }
14696                UsageStats usage = entry.getValue();
14697                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
14698                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
14699            }
14700        }
14701    }
14702
14703    /**
14704     * Check and throw if the given before/after packages would be considered a
14705     * downgrade.
14706     */
14707    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
14708            throws PackageManagerException {
14709        if (after.versionCode < before.mVersionCode) {
14710            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14711                    "Update version code " + after.versionCode + " is older than current "
14712                    + before.mVersionCode);
14713        } else if (after.versionCode == before.mVersionCode) {
14714            if (after.baseRevisionCode < before.baseRevisionCode) {
14715                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14716                        "Update base revision code " + after.baseRevisionCode
14717                        + " is older than current " + before.baseRevisionCode);
14718            }
14719
14720            if (!ArrayUtils.isEmpty(after.splitNames)) {
14721                for (int i = 0; i < after.splitNames.length; i++) {
14722                    final String splitName = after.splitNames[i];
14723                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
14724                    if (j != -1) {
14725                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
14726                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14727                                    "Update split " + splitName + " revision code "
14728                                    + after.splitRevisionCodes[i] + " is older than current "
14729                                    + before.splitRevisionCodes[j]);
14730                        }
14731                    }
14732                }
14733            }
14734        }
14735    }
14736
14737    private static class MoveCallbacks extends Handler {
14738        private static final int MSG_CREATED = 1;
14739        private static final int MSG_STATUS_CHANGED = 2;
14740
14741        private final RemoteCallbackList<IPackageMoveObserver>
14742                mCallbacks = new RemoteCallbackList<>();
14743
14744        private final SparseIntArray mLastStatus = new SparseIntArray();
14745
14746        public MoveCallbacks(Looper looper) {
14747            super(looper);
14748        }
14749
14750        public void register(IPackageMoveObserver callback) {
14751            mCallbacks.register(callback);
14752        }
14753
14754        public void unregister(IPackageMoveObserver callback) {
14755            mCallbacks.unregister(callback);
14756        }
14757
14758        @Override
14759        public void handleMessage(Message msg) {
14760            final SomeArgs args = (SomeArgs) msg.obj;
14761            final int n = mCallbacks.beginBroadcast();
14762            for (int i = 0; i < n; i++) {
14763                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
14764                try {
14765                    invokeCallback(callback, msg.what, args);
14766                } catch (RemoteException ignored) {
14767                }
14768            }
14769            mCallbacks.finishBroadcast();
14770            args.recycle();
14771        }
14772
14773        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
14774                throws RemoteException {
14775            switch (what) {
14776                case MSG_CREATED: {
14777                    callback.onCreated(args.argi1, (Bundle) args.arg2);
14778                    break;
14779                }
14780                case MSG_STATUS_CHANGED: {
14781                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
14782                    break;
14783                }
14784            }
14785        }
14786
14787        private void notifyCreated(int moveId, Bundle extras) {
14788            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
14789
14790            final SomeArgs args = SomeArgs.obtain();
14791            args.argi1 = moveId;
14792            args.arg2 = extras;
14793            obtainMessage(MSG_CREATED, args).sendToTarget();
14794        }
14795
14796        private void notifyStatusChanged(int moveId, int status) {
14797            notifyStatusChanged(moveId, status, -1);
14798        }
14799
14800        private void notifyStatusChanged(int moveId, int status, long estMillis) {
14801            Slog.v(TAG, "Move " + moveId + " status " + status);
14802
14803            final SomeArgs args = SomeArgs.obtain();
14804            args.argi1 = moveId;
14805            args.argi2 = status;
14806            args.arg3 = estMillis;
14807            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
14808
14809            synchronized (mLastStatus) {
14810                mLastStatus.put(moveId, status);
14811            }
14812        }
14813    }
14814}
14815