PackageManagerService.java revision 7e92ef3a1146102806fa0543ef12e09231c55639
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.MOVE_EXTERNAL_MEDIA;
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.PackageManager.MOVE_INTERNAL;
58import static android.content.pm.PackageParser.isApkFile;
59import static android.os.Process.PACKAGE_INFO_GID;
60import static android.os.Process.SYSTEM_UID;
61import static android.system.OsConstants.O_CREAT;
62import static android.system.OsConstants.O_RDWR;
63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
65import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
66import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
67import static com.android.internal.util.ArrayUtils.appendInt;
68import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
71import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
72import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
73
74import android.Manifest;
75import android.app.ActivityManager;
76import android.app.ActivityManagerNative;
77import android.app.AppGlobals;
78import android.app.IActivityManager;
79import android.app.admin.IDevicePolicyManager;
80import android.app.backup.IBackupManager;
81import android.app.usage.UsageStats;
82import android.app.usage.UsageStatsManager;
83import android.content.BroadcastReceiver;
84import android.content.ComponentName;
85import android.content.Context;
86import android.content.IIntentReceiver;
87import android.content.Intent;
88import android.content.IntentFilter;
89import android.content.IntentSender;
90import android.content.IntentSender.SendIntentException;
91import android.content.ServiceConnection;
92import android.content.pm.ActivityInfo;
93import android.content.pm.ApplicationInfo;
94import android.content.pm.FeatureInfo;
95import android.content.pm.IPackageDataObserver;
96import android.content.pm.IPackageDeleteObserver;
97import android.content.pm.IPackageDeleteObserver2;
98import android.content.pm.IPackageInstallObserver2;
99import android.content.pm.IPackageInstaller;
100import android.content.pm.IPackageManager;
101import android.content.pm.IPackageMoveObserver;
102import android.content.pm.IPackageStatsObserver;
103import android.content.pm.InstrumentationInfo;
104import android.content.pm.IntentFilterVerificationInfo;
105import android.content.pm.KeySet;
106import android.content.pm.ManifestDigest;
107import android.content.pm.PackageCleanItem;
108import android.content.pm.PackageInfo;
109import android.content.pm.PackageInfoLite;
110import android.content.pm.PackageInstaller;
111import android.content.pm.PackageManager;
112import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
113import android.content.pm.PackageParser;
114import android.content.pm.PackageParser.ActivityIntentInfo;
115import android.content.pm.PackageParser.PackageLite;
116import android.content.pm.PackageParser.PackageParserException;
117import android.content.pm.PackageStats;
118import android.content.pm.PackageUserState;
119import android.content.pm.ParceledListSlice;
120import android.content.pm.PermissionGroupInfo;
121import android.content.pm.PermissionInfo;
122import android.content.pm.ProviderInfo;
123import android.content.pm.ResolveInfo;
124import android.content.pm.ServiceInfo;
125import android.content.pm.Signature;
126import android.content.pm.UserInfo;
127import android.content.pm.VerificationParams;
128import android.content.pm.VerifierDeviceIdentity;
129import android.content.pm.VerifierInfo;
130import android.content.res.Resources;
131import android.hardware.display.DisplayManager;
132import android.net.Uri;
133import android.os.Binder;
134import android.os.Build;
135import android.os.Bundle;
136import android.os.Debug;
137import android.os.Environment;
138import android.os.Environment.UserEnvironment;
139import android.os.FileUtils;
140import android.os.Handler;
141import android.os.IBinder;
142import android.os.Looper;
143import android.os.Message;
144import android.os.Parcel;
145import android.os.ParcelFileDescriptor;
146import android.os.Process;
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.security.KeyStore;
159import android.security.SystemKeyStore;
160import android.system.ErrnoException;
161import android.system.Os;
162import android.system.StructStat;
163import android.text.TextUtils;
164import android.text.format.DateUtils;
165import android.util.ArrayMap;
166import android.util.ArraySet;
167import android.util.AtomicFile;
168import android.util.DisplayMetrics;
169import android.util.EventLog;
170import android.util.ExceptionUtils;
171import android.util.Log;
172import android.util.LogPrinter;
173import android.util.PrintStreamPrinter;
174import android.util.Slog;
175import android.util.SparseArray;
176import android.util.SparseBooleanArray;
177import android.util.Xml;
178import android.view.Display;
179
180import dalvik.system.DexFile;
181import dalvik.system.VMRuntime;
182
183import libcore.io.IoUtils;
184import libcore.util.EmptyArray;
185
186import com.android.internal.R;
187import com.android.internal.app.IMediaContainerService;
188import com.android.internal.app.ResolverActivity;
189import com.android.internal.content.NativeLibraryHelper;
190import com.android.internal.content.PackageHelper;
191import com.android.internal.os.IParcelFileDescriptorFactory;
192import com.android.internal.util.ArrayUtils;
193import com.android.internal.util.FastPrintWriter;
194import com.android.internal.util.FastXmlSerializer;
195import com.android.internal.util.IndentingPrintWriter;
196import com.android.server.EventLogTags;
197import com.android.server.IntentResolver;
198import com.android.server.LocalServices;
199import com.android.server.ServiceThread;
200import com.android.server.SystemConfig;
201import com.android.server.Watchdog;
202import com.android.server.pm.Settings.DatabaseVersion;
203import com.android.server.storage.DeviceStorageMonitorInternal;
204
205import org.xmlpull.v1.XmlPullParser;
206import org.xmlpull.v1.XmlSerializer;
207
208import java.io.BufferedInputStream;
209import java.io.BufferedOutputStream;
210import java.io.BufferedReader;
211import java.io.ByteArrayInputStream;
212import java.io.ByteArrayOutputStream;
213import java.io.File;
214import java.io.FileDescriptor;
215import java.io.FileNotFoundException;
216import java.io.FileOutputStream;
217import java.io.FileReader;
218import java.io.FilenameFilter;
219import java.io.IOException;
220import java.io.InputStream;
221import java.io.PrintWriter;
222import java.nio.charset.StandardCharsets;
223import java.security.NoSuchAlgorithmException;
224import java.security.PublicKey;
225import java.security.cert.CertificateEncodingException;
226import java.security.cert.CertificateException;
227import java.text.SimpleDateFormat;
228import java.util.ArrayList;
229import java.util.Arrays;
230import java.util.Collection;
231import java.util.Collections;
232import java.util.Comparator;
233import java.util.Date;
234import java.util.Iterator;
235import java.util.List;
236import java.util.Map;
237import java.util.Objects;
238import java.util.Set;
239import java.util.concurrent.atomic.AtomicBoolean;
240import java.util.concurrent.atomic.AtomicLong;
241
242/**
243 * Keep track of all those .apks everywhere.
244 *
245 * This is very central to the platform's security; please run the unit
246 * tests whenever making modifications here:
247 *
248mmm frameworks/base/tests/AndroidTests
249adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
250adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
251 *
252 * {@hide}
253 */
254public class PackageManagerService extends IPackageManager.Stub {
255    static final String TAG = "PackageManager";
256    static final boolean DEBUG_SETTINGS = false;
257    static final boolean DEBUG_PREFERRED = false;
258    static final boolean DEBUG_UPGRADE = false;
259    private static final boolean DEBUG_BACKUP = true;
260    private static final boolean DEBUG_INSTALL = false;
261    private static final boolean DEBUG_REMOVE = false;
262    private static final boolean DEBUG_BROADCASTS = false;
263    private static final boolean DEBUG_SHOW_INFO = false;
264    private static final boolean DEBUG_PACKAGE_INFO = false;
265    private static final boolean DEBUG_INTENT_MATCHING = false;
266    private static final boolean DEBUG_PACKAGE_SCANNING = false;
267    private static final boolean DEBUG_VERIFY = false;
268    private static final boolean DEBUG_DEXOPT = false;
269    private static final boolean DEBUG_ABI_SELECTION = false;
270
271    static final boolean RUNTIME_PERMISSIONS_ENABLED = true;
272
273    private static final int RADIO_UID = Process.PHONE_UID;
274    private static final int LOG_UID = Process.LOG_UID;
275    private static final int NFC_UID = Process.NFC_UID;
276    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
277    private static final int SHELL_UID = Process.SHELL_UID;
278
279    // Cap the size of permission trees that 3rd party apps can define
280    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
281
282    // Suffix used during package installation when copying/moving
283    // package apks to install directory.
284    private static final String INSTALL_PACKAGE_SUFFIX = "-";
285
286    static final int SCAN_NO_DEX = 1<<1;
287    static final int SCAN_FORCE_DEX = 1<<2;
288    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
289    static final int SCAN_NEW_INSTALL = 1<<4;
290    static final int SCAN_NO_PATHS = 1<<5;
291    static final int SCAN_UPDATE_TIME = 1<<6;
292    static final int SCAN_DEFER_DEX = 1<<7;
293    static final int SCAN_BOOTING = 1<<8;
294    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
295    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
296    static final int SCAN_REPLACING = 1<<11;
297    static final int SCAN_REQUIRE_KNOWN = 1<<12;
298
299    static final int REMOVE_CHATTY = 1<<16;
300
301    /**
302     * Timeout (in milliseconds) after which the watchdog should declare that
303     * our handler thread is wedged.  The usual default for such things is one
304     * minute but we sometimes do very lengthy I/O operations on this thread,
305     * such as installing multi-gigabyte applications, so ours needs to be longer.
306     */
307    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
308
309    /**
310     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
311     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
312     * settings entry if available, otherwise we use the hardcoded default.  If it's been
313     * more than this long since the last fstrim, we force one during the boot sequence.
314     *
315     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
316     * one gets run at the next available charging+idle time.  This final mandatory
317     * no-fstrim check kicks in only of the other scheduling criteria is never met.
318     */
319    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
320
321    /**
322     * Whether verification is enabled by default.
323     */
324    private static final boolean DEFAULT_VERIFY_ENABLE = true;
325
326    /**
327     * The default maximum time to wait for the verification agent to return in
328     * milliseconds.
329     */
330    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
331
332    /**
333     * The default response for package verification timeout.
334     *
335     * This can be either PackageManager.VERIFICATION_ALLOW or
336     * PackageManager.VERIFICATION_REJECT.
337     */
338    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
339
340    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
341
342    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
343            DEFAULT_CONTAINER_PACKAGE,
344            "com.android.defcontainer.DefaultContainerService");
345
346    private static final String KILL_APP_REASON_GIDS_CHANGED =
347            "permission grant or revoke changed gids";
348
349    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
350            "permissions revoked";
351
352    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
353
354    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
355
356    /** Permission grant: not grant the permission. */
357    private static final int GRANT_DENIED = 1;
358
359    /** Permission grant: grant the permission as an install permission. */
360    private static final int GRANT_INSTALL = 2;
361
362    /** Permission grant: grant the permission as a runtime one. */
363    private static final int GRANT_RUNTIME = 3;
364
365    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
366    private static final int GRANT_UPGRADE = 4;
367
368    final ServiceThread mHandlerThread;
369
370    final PackageHandler mHandler;
371
372    /**
373     * Messages for {@link #mHandler} that need to wait for system ready before
374     * being dispatched.
375     */
376    private ArrayList<Message> mPostSystemReadyMessages;
377
378    final int mSdkVersion = Build.VERSION.SDK_INT;
379
380    final Context mContext;
381    final boolean mFactoryTest;
382    final boolean mOnlyCore;
383    final boolean mLazyDexOpt;
384    final long mDexOptLRUThresholdInMills;
385    final DisplayMetrics mMetrics;
386    final int mDefParseFlags;
387    final String[] mSeparateProcesses;
388    final boolean mIsUpgrade;
389
390    // This is where all application persistent data goes.
391    final File mAppDataDir;
392
393    // This is where all application persistent data goes for secondary users.
394    final File mUserAppDataDir;
395
396    /** The location for ASEC container files on internal storage. */
397    final String mAsecInternalPath;
398
399    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
400    // LOCK HELD.  Can be called with mInstallLock held.
401    final Installer mInstaller;
402
403    /** Directory where installed third-party apps stored */
404    final File mAppInstallDir;
405
406    /**
407     * Directory to which applications installed internally have their
408     * 32 bit native libraries copied.
409     */
410    private File mAppLib32InstallDir;
411
412    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
413    // apps.
414    final File mDrmAppPrivateInstallDir;
415
416    // ----------------------------------------------------------------
417
418    // Lock for state used when installing and doing other long running
419    // operations.  Methods that must be called with this lock held have
420    // the suffix "LI".
421    final Object mInstallLock = new Object();
422
423    // ----------------------------------------------------------------
424
425    // Keys are String (package name), values are Package.  This also serves
426    // as the lock for the global state.  Methods that must be called with
427    // this lock held have the prefix "LP".
428    final ArrayMap<String, PackageParser.Package> mPackages =
429            new ArrayMap<String, PackageParser.Package>();
430
431    // Tracks available target package names -> overlay package paths.
432    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
433        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
434
435    final Settings mSettings;
436    boolean mRestoredSettings;
437
438    // System configuration read by SystemConfig.
439    final int[] mGlobalGids;
440    final SparseArray<ArraySet<String>> mSystemPermissions;
441    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
442
443    // If mac_permissions.xml was found for seinfo labeling.
444    boolean mFoundPolicyFile;
445
446    // If a recursive restorecon of /data/data/<pkg> is needed.
447    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
448
449    public static final class SharedLibraryEntry {
450        public final String path;
451        public final String apk;
452
453        SharedLibraryEntry(String _path, String _apk) {
454            path = _path;
455            apk = _apk;
456        }
457    }
458
459    // Currently known shared libraries.
460    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
461            new ArrayMap<String, SharedLibraryEntry>();
462
463    // All available activities, for your resolving pleasure.
464    final ActivityIntentResolver mActivities =
465            new ActivityIntentResolver();
466
467    // All available receivers, for your resolving pleasure.
468    final ActivityIntentResolver mReceivers =
469            new ActivityIntentResolver();
470
471    // All available services, for your resolving pleasure.
472    final ServiceIntentResolver mServices = new ServiceIntentResolver();
473
474    // All available providers, for your resolving pleasure.
475    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
476
477    // Mapping from provider base names (first directory in content URI codePath)
478    // to the provider information.
479    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
480            new ArrayMap<String, PackageParser.Provider>();
481
482    // Mapping from instrumentation class names to info about them.
483    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
484            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
485
486    // Mapping from permission names to info about them.
487    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
488            new ArrayMap<String, PackageParser.PermissionGroup>();
489
490    // Packages whose data we have transfered into another package, thus
491    // should no longer exist.
492    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
493
494    // Broadcast actions that are only available to the system.
495    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
496
497    /** List of packages waiting for verification. */
498    final SparseArray<PackageVerificationState> mPendingVerification
499            = new SparseArray<PackageVerificationState>();
500
501    /** Set of packages associated with each app op permission. */
502    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
503
504    final PackageInstallerService mInstallerService;
505
506    private final PackageDexOptimizer mPackageDexOptimizer;
507    // Cache of users who need badging.
508    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
509
510    /** Token for keys in mPendingVerification. */
511    private int mPendingVerificationToken = 0;
512
513    volatile boolean mSystemReady;
514    volatile boolean mSafeMode;
515    volatile boolean mHasSystemUidErrors;
516
517    ApplicationInfo mAndroidApplication;
518    final ActivityInfo mResolveActivity = new ActivityInfo();
519    final ResolveInfo mResolveInfo = new ResolveInfo();
520    ComponentName mResolveComponentName;
521    PackageParser.Package mPlatformPackage;
522    ComponentName mCustomResolverComponentName;
523
524    boolean mResolverReplaced = false;
525
526    private final ComponentName mIntentFilterVerifierComponent;
527    private int mIntentFilterVerificationToken = 0;
528
529    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
530            = new SparseArray<IntentFilterVerificationState>();
531
532    private interface IntentFilterVerifier<T extends IntentFilter> {
533        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
534                                               T filter, String packageName);
535        void startVerifications(int userId);
536        void receiveVerificationResponse(int verificationId);
537    }
538
539    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
540        private Context mContext;
541        private ComponentName mIntentFilterVerifierComponent;
542        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
543
544        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
545            mContext = context;
546            mIntentFilterVerifierComponent = verifierComponent;
547        }
548
549        private String getDefaultScheme() {
550            // TODO: replace SCHEME_HTTP with SCHEME_HTTPS
551            return IntentFilter.SCHEME_HTTP;
552        }
553
554        @Override
555        public void startVerifications(int userId) {
556            // Launch verifications requests
557            int count = mCurrentIntentFilterVerifications.size();
558            for (int n=0; n<count; n++) {
559                int verificationId = mCurrentIntentFilterVerifications.get(n);
560                final IntentFilterVerificationState ivs =
561                        mIntentFilterVerificationStates.get(verificationId);
562
563                String packageName = ivs.getPackageName();
564
565                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
566                final int filterCount = filters.size();
567                ArraySet<String> domainsSet = new ArraySet<>();
568                for (int m=0; m<filterCount; m++) {
569                    PackageParser.ActivityIntentInfo filter = filters.get(m);
570                    domainsSet.addAll(filter.getHostsList());
571                }
572                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
573                synchronized (mPackages) {
574                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
575                            packageName, domainsList) != null) {
576                        scheduleWriteSettingsLocked();
577                    }
578                }
579                sendVerificationRequest(userId, verificationId, ivs);
580            }
581            mCurrentIntentFilterVerifications.clear();
582        }
583
584        private void sendVerificationRequest(int userId, int verificationId,
585                IntentFilterVerificationState ivs) {
586
587            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
588            verificationIntent.putExtra(
589                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
590                    verificationId);
591            verificationIntent.putExtra(
592                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
593                    getDefaultScheme());
594            verificationIntent.putExtra(
595                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
596                    ivs.getHostsString());
597            verificationIntent.putExtra(
598                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
599                    ivs.getPackageName());
600            verificationIntent.setComponent(mIntentFilterVerifierComponent);
601            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
602
603            UserHandle user = new UserHandle(userId);
604            mContext.sendBroadcastAsUser(verificationIntent, user);
605            Slog.d(TAG, "Sending IntenFilter verification broadcast");
606        }
607
608        public void receiveVerificationResponse(int verificationId) {
609            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
610
611            final boolean verified = ivs.isVerified();
612
613            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
614            final int count = filters.size();
615            for (int n=0; n<count; n++) {
616                PackageParser.ActivityIntentInfo filter = filters.get(n);
617                filter.setVerified(verified);
618
619                Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:"
620                        + verified + " and hosts:" + ivs.getHostsString());
621            }
622
623            mIntentFilterVerificationStates.remove(verificationId);
624
625            final String packageName = ivs.getPackageName();
626            IntentFilterVerificationInfo ivi = null;
627
628            synchronized (mPackages) {
629                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
630            }
631            if (ivi == null) {
632                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
633                        + verificationId + " packageName:" + packageName);
634                return;
635            }
636            Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:"
637                    + verificationId);
638
639            synchronized (mPackages) {
640                if (verified) {
641                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
642                } else {
643                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
644                }
645                scheduleWriteSettingsLocked();
646
647                final int userId = ivs.getUserId();
648                if (userId != UserHandle.USER_ALL) {
649                    final int userStatus =
650                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
651
652                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
653                    boolean needUpdate = false;
654
655                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
656                    // already been set by the User thru the Disambiguation dialog
657                    switch (userStatus) {
658                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
659                            if (verified) {
660                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
661                            } else {
662                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
663                            }
664                            needUpdate = true;
665                            break;
666
667                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
668                            if (verified) {
669                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
670                                needUpdate = true;
671                            }
672                            break;
673
674                        default:
675                            // Nothing to do
676                    }
677
678                    if (needUpdate) {
679                        mSettings.updateIntentFilterVerificationStatusLPw(
680                                packageName, updatedStatus, userId);
681                        scheduleWritePackageRestrictionsLocked(userId);
682                    }
683                }
684            }
685        }
686
687        @Override
688        public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
689                    ActivityIntentInfo filter, String packageName) {
690            if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
691                    filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
692                Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme");
693                return false;
694            }
695            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
696            if (ivs == null) {
697                ivs = createDomainVerificationState(verifierId, userId, verificationId,
698                        packageName);
699            }
700            if (!hasValidDomains(filter)) {
701                return false;
702            }
703            ivs.addFilter(filter);
704            return true;
705        }
706
707        private IntentFilterVerificationState createDomainVerificationState(int verifierId,
708                int userId, int verificationId, String packageName) {
709            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
710                    verifierId, userId, packageName);
711            ivs.setPendingState();
712            synchronized (mPackages) {
713                mIntentFilterVerificationStates.append(verificationId, ivs);
714                mCurrentIntentFilterVerifications.add(verificationId);
715            }
716            return ivs;
717        }
718    }
719
720    private static boolean hasValidDomains(ActivityIntentInfo filter) {
721        return hasValidDomains(filter, true);
722    }
723
724    private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) {
725        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
726                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
727        if (!hasHTTPorHTTPS) {
728            if (logging) {
729                Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme");
730            }
731            return false;
732        }
733        return true;
734    }
735
736    private IntentFilterVerifier mIntentFilterVerifier;
737
738    // Set of pending broadcasts for aggregating enable/disable of components.
739    static class PendingPackageBroadcasts {
740        // for each user id, a map of <package name -> components within that package>
741        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
742
743        public PendingPackageBroadcasts() {
744            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
745        }
746
747        public ArrayList<String> get(int userId, String packageName) {
748            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
749            return packages.get(packageName);
750        }
751
752        public void put(int userId, String packageName, ArrayList<String> components) {
753            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
754            packages.put(packageName, components);
755        }
756
757        public void remove(int userId, String packageName) {
758            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
759            if (packages != null) {
760                packages.remove(packageName);
761            }
762        }
763
764        public void remove(int userId) {
765            mUidMap.remove(userId);
766        }
767
768        public int userIdCount() {
769            return mUidMap.size();
770        }
771
772        public int userIdAt(int n) {
773            return mUidMap.keyAt(n);
774        }
775
776        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
777            return mUidMap.get(userId);
778        }
779
780        public int size() {
781            // total number of pending broadcast entries across all userIds
782            int num = 0;
783            for (int i = 0; i< mUidMap.size(); i++) {
784                num += mUidMap.valueAt(i).size();
785            }
786            return num;
787        }
788
789        public void clear() {
790            mUidMap.clear();
791        }
792
793        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
794            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
795            if (map == null) {
796                map = new ArrayMap<String, ArrayList<String>>();
797                mUidMap.put(userId, map);
798            }
799            return map;
800        }
801    }
802    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
803
804    // Service Connection to remote media container service to copy
805    // package uri's from external media onto secure containers
806    // or internal storage.
807    private IMediaContainerService mContainerService = null;
808
809    static final int SEND_PENDING_BROADCAST = 1;
810    static final int MCS_BOUND = 3;
811    static final int END_COPY = 4;
812    static final int INIT_COPY = 5;
813    static final int MCS_UNBIND = 6;
814    static final int START_CLEANING_PACKAGE = 7;
815    static final int FIND_INSTALL_LOC = 8;
816    static final int POST_INSTALL = 9;
817    static final int MCS_RECONNECT = 10;
818    static final int MCS_GIVE_UP = 11;
819    static final int UPDATED_MEDIA_STATUS = 12;
820    static final int WRITE_SETTINGS = 13;
821    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
822    static final int PACKAGE_VERIFIED = 15;
823    static final int CHECK_PENDING_VERIFICATION = 16;
824    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
825    static final int INTENT_FILTER_VERIFIED = 18;
826
827    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
828
829    // Delay time in millisecs
830    static final int BROADCAST_DELAY = 10 * 1000;
831
832    static UserManagerService sUserManager;
833
834    // Stores a list of users whose package restrictions file needs to be updated
835    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
836
837    final private DefaultContainerConnection mDefContainerConn =
838            new DefaultContainerConnection();
839    class DefaultContainerConnection implements ServiceConnection {
840        public void onServiceConnected(ComponentName name, IBinder service) {
841            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
842            IMediaContainerService imcs =
843                IMediaContainerService.Stub.asInterface(service);
844            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
845        }
846
847        public void onServiceDisconnected(ComponentName name) {
848            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
849        }
850    };
851
852    // Recordkeeping of restore-after-install operations that are currently in flight
853    // between the Package Manager and the Backup Manager
854    class PostInstallData {
855        public InstallArgs args;
856        public PackageInstalledInfo res;
857
858        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
859            args = _a;
860            res = _r;
861        }
862    };
863    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
864    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
865
866    // backup/restore of preferred activity state
867    private static final String TAG_PREFERRED_BACKUP = "pa";
868
869    private final String mRequiredVerifierPackage;
870
871    private final PackageUsage mPackageUsage = new PackageUsage();
872
873    private class PackageUsage {
874        private static final int WRITE_INTERVAL
875            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
876
877        private final Object mFileLock = new Object();
878        private final AtomicLong mLastWritten = new AtomicLong(0);
879        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
880
881        private boolean mIsHistoricalPackageUsageAvailable = true;
882
883        boolean isHistoricalPackageUsageAvailable() {
884            return mIsHistoricalPackageUsageAvailable;
885        }
886
887        void write(boolean force) {
888            if (force) {
889                writeInternal();
890                return;
891            }
892            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
893                && !DEBUG_DEXOPT) {
894                return;
895            }
896            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
897                new Thread("PackageUsage_DiskWriter") {
898                    @Override
899                    public void run() {
900                        try {
901                            writeInternal();
902                        } finally {
903                            mBackgroundWriteRunning.set(false);
904                        }
905                    }
906                }.start();
907            }
908        }
909
910        private void writeInternal() {
911            synchronized (mPackages) {
912                synchronized (mFileLock) {
913                    AtomicFile file = getFile();
914                    FileOutputStream f = null;
915                    try {
916                        f = file.startWrite();
917                        BufferedOutputStream out = new BufferedOutputStream(f);
918                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
919                        StringBuilder sb = new StringBuilder();
920                        for (PackageParser.Package pkg : mPackages.values()) {
921                            if (pkg.mLastPackageUsageTimeInMills == 0) {
922                                continue;
923                            }
924                            sb.setLength(0);
925                            sb.append(pkg.packageName);
926                            sb.append(' ');
927                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
928                            sb.append('\n');
929                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
930                        }
931                        out.flush();
932                        file.finishWrite(f);
933                    } catch (IOException e) {
934                        if (f != null) {
935                            file.failWrite(f);
936                        }
937                        Log.e(TAG, "Failed to write package usage times", e);
938                    }
939                }
940            }
941            mLastWritten.set(SystemClock.elapsedRealtime());
942        }
943
944        void readLP() {
945            synchronized (mFileLock) {
946                AtomicFile file = getFile();
947                BufferedInputStream in = null;
948                try {
949                    in = new BufferedInputStream(file.openRead());
950                    StringBuffer sb = new StringBuffer();
951                    while (true) {
952                        String packageName = readToken(in, sb, ' ');
953                        if (packageName == null) {
954                            break;
955                        }
956                        String timeInMillisString = readToken(in, sb, '\n');
957                        if (timeInMillisString == null) {
958                            throw new IOException("Failed to find last usage time for package "
959                                                  + packageName);
960                        }
961                        PackageParser.Package pkg = mPackages.get(packageName);
962                        if (pkg == null) {
963                            continue;
964                        }
965                        long timeInMillis;
966                        try {
967                            timeInMillis = Long.parseLong(timeInMillisString.toString());
968                        } catch (NumberFormatException e) {
969                            throw new IOException("Failed to parse " + timeInMillisString
970                                                  + " as a long.", e);
971                        }
972                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
973                    }
974                } catch (FileNotFoundException expected) {
975                    mIsHistoricalPackageUsageAvailable = false;
976                } catch (IOException e) {
977                    Log.w(TAG, "Failed to read package usage times", e);
978                } finally {
979                    IoUtils.closeQuietly(in);
980                }
981            }
982            mLastWritten.set(SystemClock.elapsedRealtime());
983        }
984
985        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
986                throws IOException {
987            sb.setLength(0);
988            while (true) {
989                int ch = in.read();
990                if (ch == -1) {
991                    if (sb.length() == 0) {
992                        return null;
993                    }
994                    throw new IOException("Unexpected EOF");
995                }
996                if (ch == endOfToken) {
997                    return sb.toString();
998                }
999                sb.append((char)ch);
1000            }
1001        }
1002
1003        private AtomicFile getFile() {
1004            File dataDir = Environment.getDataDirectory();
1005            File systemDir = new File(dataDir, "system");
1006            File fname = new File(systemDir, "package-usage.list");
1007            return new AtomicFile(fname);
1008        }
1009    }
1010
1011    class PackageHandler extends Handler {
1012        private boolean mBound = false;
1013        final ArrayList<HandlerParams> mPendingInstalls =
1014            new ArrayList<HandlerParams>();
1015
1016        private boolean connectToService() {
1017            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1018                    " DefaultContainerService");
1019            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1020            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1021            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1022                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1023                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1024                mBound = true;
1025                return true;
1026            }
1027            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1028            return false;
1029        }
1030
1031        private void disconnectService() {
1032            mContainerService = null;
1033            mBound = false;
1034            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1035            mContext.unbindService(mDefContainerConn);
1036            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1037        }
1038
1039        PackageHandler(Looper looper) {
1040            super(looper);
1041        }
1042
1043        public void handleMessage(Message msg) {
1044            try {
1045                doHandleMessage(msg);
1046            } finally {
1047                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1048            }
1049        }
1050
1051        void doHandleMessage(Message msg) {
1052            switch (msg.what) {
1053                case INIT_COPY: {
1054                    HandlerParams params = (HandlerParams) msg.obj;
1055                    int idx = mPendingInstalls.size();
1056                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1057                    // If a bind was already initiated we dont really
1058                    // need to do anything. The pending install
1059                    // will be processed later on.
1060                    if (!mBound) {
1061                        // If this is the only one pending we might
1062                        // have to bind to the service again.
1063                        if (!connectToService()) {
1064                            Slog.e(TAG, "Failed to bind to media container service");
1065                            params.serviceError();
1066                            return;
1067                        } else {
1068                            // Once we bind to the service, the first
1069                            // pending request will be processed.
1070                            mPendingInstalls.add(idx, params);
1071                        }
1072                    } else {
1073                        mPendingInstalls.add(idx, params);
1074                        // Already bound to the service. Just make
1075                        // sure we trigger off processing the first request.
1076                        if (idx == 0) {
1077                            mHandler.sendEmptyMessage(MCS_BOUND);
1078                        }
1079                    }
1080                    break;
1081                }
1082                case MCS_BOUND: {
1083                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1084                    if (msg.obj != null) {
1085                        mContainerService = (IMediaContainerService) msg.obj;
1086                    }
1087                    if (mContainerService == null) {
1088                        // Something seriously wrong. Bail out
1089                        Slog.e(TAG, "Cannot bind to media container service");
1090                        for (HandlerParams params : mPendingInstalls) {
1091                            // Indicate service bind error
1092                            params.serviceError();
1093                        }
1094                        mPendingInstalls.clear();
1095                    } else if (mPendingInstalls.size() > 0) {
1096                        HandlerParams params = mPendingInstalls.get(0);
1097                        if (params != null) {
1098                            if (params.startCopy()) {
1099                                // We are done...  look for more work or to
1100                                // go idle.
1101                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1102                                        "Checking for more work or unbind...");
1103                                // Delete pending install
1104                                if (mPendingInstalls.size() > 0) {
1105                                    mPendingInstalls.remove(0);
1106                                }
1107                                if (mPendingInstalls.size() == 0) {
1108                                    if (mBound) {
1109                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1110                                                "Posting delayed MCS_UNBIND");
1111                                        removeMessages(MCS_UNBIND);
1112                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1113                                        // Unbind after a little delay, to avoid
1114                                        // continual thrashing.
1115                                        sendMessageDelayed(ubmsg, 10000);
1116                                    }
1117                                } else {
1118                                    // There are more pending requests in queue.
1119                                    // Just post MCS_BOUND message to trigger processing
1120                                    // of next pending install.
1121                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1122                                            "Posting MCS_BOUND for next work");
1123                                    mHandler.sendEmptyMessage(MCS_BOUND);
1124                                }
1125                            }
1126                        }
1127                    } else {
1128                        // Should never happen ideally.
1129                        Slog.w(TAG, "Empty queue");
1130                    }
1131                    break;
1132                }
1133                case MCS_RECONNECT: {
1134                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1135                    if (mPendingInstalls.size() > 0) {
1136                        if (mBound) {
1137                            disconnectService();
1138                        }
1139                        if (!connectToService()) {
1140                            Slog.e(TAG, "Failed to bind to media container service");
1141                            for (HandlerParams params : mPendingInstalls) {
1142                                // Indicate service bind error
1143                                params.serviceError();
1144                            }
1145                            mPendingInstalls.clear();
1146                        }
1147                    }
1148                    break;
1149                }
1150                case MCS_UNBIND: {
1151                    // If there is no actual work left, then time to unbind.
1152                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1153
1154                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1155                        if (mBound) {
1156                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1157
1158                            disconnectService();
1159                        }
1160                    } else if (mPendingInstalls.size() > 0) {
1161                        // There are more pending requests in queue.
1162                        // Just post MCS_BOUND message to trigger processing
1163                        // of next pending install.
1164                        mHandler.sendEmptyMessage(MCS_BOUND);
1165                    }
1166
1167                    break;
1168                }
1169                case MCS_GIVE_UP: {
1170                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1171                    mPendingInstalls.remove(0);
1172                    break;
1173                }
1174                case SEND_PENDING_BROADCAST: {
1175                    String packages[];
1176                    ArrayList<String> components[];
1177                    int size = 0;
1178                    int uids[];
1179                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1180                    synchronized (mPackages) {
1181                        if (mPendingBroadcasts == null) {
1182                            return;
1183                        }
1184                        size = mPendingBroadcasts.size();
1185                        if (size <= 0) {
1186                            // Nothing to be done. Just return
1187                            return;
1188                        }
1189                        packages = new String[size];
1190                        components = new ArrayList[size];
1191                        uids = new int[size];
1192                        int i = 0;  // filling out the above arrays
1193
1194                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1195                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1196                            Iterator<Map.Entry<String, ArrayList<String>>> it
1197                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1198                                            .entrySet().iterator();
1199                            while (it.hasNext() && i < size) {
1200                                Map.Entry<String, ArrayList<String>> ent = it.next();
1201                                packages[i] = ent.getKey();
1202                                components[i] = ent.getValue();
1203                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1204                                uids[i] = (ps != null)
1205                                        ? UserHandle.getUid(packageUserId, ps.appId)
1206                                        : -1;
1207                                i++;
1208                            }
1209                        }
1210                        size = i;
1211                        mPendingBroadcasts.clear();
1212                    }
1213                    // Send broadcasts
1214                    for (int i = 0; i < size; i++) {
1215                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1216                    }
1217                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1218                    break;
1219                }
1220                case START_CLEANING_PACKAGE: {
1221                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1222                    final String packageName = (String)msg.obj;
1223                    final int userId = msg.arg1;
1224                    final boolean andCode = msg.arg2 != 0;
1225                    synchronized (mPackages) {
1226                        if (userId == UserHandle.USER_ALL) {
1227                            int[] users = sUserManager.getUserIds();
1228                            for (int user : users) {
1229                                mSettings.addPackageToCleanLPw(
1230                                        new PackageCleanItem(user, packageName, andCode));
1231                            }
1232                        } else {
1233                            mSettings.addPackageToCleanLPw(
1234                                    new PackageCleanItem(userId, packageName, andCode));
1235                        }
1236                    }
1237                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1238                    startCleaningPackages();
1239                } break;
1240                case POST_INSTALL: {
1241                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1242                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1243                    mRunningInstalls.delete(msg.arg1);
1244                    boolean deleteOld = false;
1245
1246                    if (data != null) {
1247                        InstallArgs args = data.args;
1248                        PackageInstalledInfo res = data.res;
1249
1250                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1251                            res.removedInfo.sendBroadcast(false, true, false);
1252                            Bundle extras = new Bundle(1);
1253                            extras.putInt(Intent.EXTRA_UID, res.uid);
1254
1255                            // Now that we successfully installed the package, grant runtime
1256                            // permissions if requested before broadcasting the install.
1257                            if ((args.installFlags
1258                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1259                                grantRequestedRuntimePermissions(res.pkg,
1260                                        args.user.getIdentifier());
1261                            }
1262
1263                            // Determine the set of users who are adding this
1264                            // package for the first time vs. those who are seeing
1265                            // an update.
1266                            int[] firstUsers;
1267                            int[] updateUsers = new int[0];
1268                            if (res.origUsers == null || res.origUsers.length == 0) {
1269                                firstUsers = res.newUsers;
1270                            } else {
1271                                firstUsers = new int[0];
1272                                for (int i=0; i<res.newUsers.length; i++) {
1273                                    int user = res.newUsers[i];
1274                                    boolean isNew = true;
1275                                    for (int j=0; j<res.origUsers.length; j++) {
1276                                        if (res.origUsers[j] == user) {
1277                                            isNew = false;
1278                                            break;
1279                                        }
1280                                    }
1281                                    if (isNew) {
1282                                        int[] newFirst = new int[firstUsers.length+1];
1283                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1284                                                firstUsers.length);
1285                                        newFirst[firstUsers.length] = user;
1286                                        firstUsers = newFirst;
1287                                    } else {
1288                                        int[] newUpdate = new int[updateUsers.length+1];
1289                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1290                                                updateUsers.length);
1291                                        newUpdate[updateUsers.length] = user;
1292                                        updateUsers = newUpdate;
1293                                    }
1294                                }
1295                            }
1296                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1297                                    res.pkg.applicationInfo.packageName,
1298                                    extras, null, null, firstUsers);
1299                            final boolean update = res.removedInfo.removedPackage != null;
1300                            if (update) {
1301                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1302                            }
1303                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1304                                    res.pkg.applicationInfo.packageName,
1305                                    extras, null, null, updateUsers);
1306                            if (update) {
1307                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1308                                        res.pkg.applicationInfo.packageName,
1309                                        extras, null, null, updateUsers);
1310                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1311                                        null, null,
1312                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1313
1314                                // treat asec-hosted packages like removable media on upgrade
1315                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1316                                    if (DEBUG_INSTALL) {
1317                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1318                                                + " is ASEC-hosted -> AVAILABLE");
1319                                    }
1320                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1321                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1322                                    pkgList.add(res.pkg.applicationInfo.packageName);
1323                                    sendResourcesChangedBroadcast(true, true,
1324                                            pkgList,uidArray, null);
1325                                }
1326                            }
1327                            if (res.removedInfo.args != null) {
1328                                // Remove the replaced package's older resources safely now
1329                                deleteOld = true;
1330                            }
1331
1332                            // Log current value of "unknown sources" setting
1333                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1334                                getUnknownSourcesSettings());
1335                        }
1336                        // Force a gc to clear up things
1337                        Runtime.getRuntime().gc();
1338                        // We delete after a gc for applications  on sdcard.
1339                        if (deleteOld) {
1340                            synchronized (mInstallLock) {
1341                                res.removedInfo.args.doPostDeleteLI(true);
1342                            }
1343                        }
1344                        if (args.observer != null) {
1345                            try {
1346                                Bundle extras = extrasForInstallResult(res);
1347                                args.observer.onPackageInstalled(res.name, res.returnCode,
1348                                        res.returnMsg, extras);
1349                            } catch (RemoteException e) {
1350                                Slog.i(TAG, "Observer no longer exists.");
1351                            }
1352                        }
1353                    } else {
1354                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1355                    }
1356                } break;
1357                case UPDATED_MEDIA_STATUS: {
1358                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1359                    boolean reportStatus = msg.arg1 == 1;
1360                    boolean doGc = msg.arg2 == 1;
1361                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1362                    if (doGc) {
1363                        // Force a gc to clear up stale containers.
1364                        Runtime.getRuntime().gc();
1365                    }
1366                    if (msg.obj != null) {
1367                        @SuppressWarnings("unchecked")
1368                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1369                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1370                        // Unload containers
1371                        unloadAllContainers(args);
1372                    }
1373                    if (reportStatus) {
1374                        try {
1375                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1376                            PackageHelper.getMountService().finishMediaUpdate();
1377                        } catch (RemoteException e) {
1378                            Log.e(TAG, "MountService not running?");
1379                        }
1380                    }
1381                } break;
1382                case WRITE_SETTINGS: {
1383                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1384                    synchronized (mPackages) {
1385                        removeMessages(WRITE_SETTINGS);
1386                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1387                        mSettings.writeLPr();
1388                        mDirtyUsers.clear();
1389                    }
1390                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1391                } break;
1392                case WRITE_PACKAGE_RESTRICTIONS: {
1393                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1394                    synchronized (mPackages) {
1395                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1396                        for (int userId : mDirtyUsers) {
1397                            mSettings.writePackageRestrictionsLPr(userId);
1398                        }
1399                        mDirtyUsers.clear();
1400                    }
1401                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1402                } break;
1403                case CHECK_PENDING_VERIFICATION: {
1404                    final int verificationId = msg.arg1;
1405                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1406
1407                    if ((state != null) && !state.timeoutExtended()) {
1408                        final InstallArgs args = state.getInstallArgs();
1409                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1410
1411                        Slog.i(TAG, "Verification timed out for " + originUri);
1412                        mPendingVerification.remove(verificationId);
1413
1414                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1415
1416                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1417                            Slog.i(TAG, "Continuing with installation of " + originUri);
1418                            state.setVerifierResponse(Binder.getCallingUid(),
1419                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1420                            broadcastPackageVerified(verificationId, originUri,
1421                                    PackageManager.VERIFICATION_ALLOW,
1422                                    state.getInstallArgs().getUser());
1423                            try {
1424                                ret = args.copyApk(mContainerService, true);
1425                            } catch (RemoteException e) {
1426                                Slog.e(TAG, "Could not contact the ContainerService");
1427                            }
1428                        } else {
1429                            broadcastPackageVerified(verificationId, originUri,
1430                                    PackageManager.VERIFICATION_REJECT,
1431                                    state.getInstallArgs().getUser());
1432                        }
1433
1434                        processPendingInstall(args, ret);
1435                        mHandler.sendEmptyMessage(MCS_UNBIND);
1436                    }
1437                    break;
1438                }
1439                case PACKAGE_VERIFIED: {
1440                    final int verificationId = msg.arg1;
1441
1442                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1443                    if (state == null) {
1444                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1445                        break;
1446                    }
1447
1448                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1449
1450                    state.setVerifierResponse(response.callerUid, response.code);
1451
1452                    if (state.isVerificationComplete()) {
1453                        mPendingVerification.remove(verificationId);
1454
1455                        final InstallArgs args = state.getInstallArgs();
1456                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1457
1458                        int ret;
1459                        if (state.isInstallAllowed()) {
1460                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1461                            broadcastPackageVerified(verificationId, originUri,
1462                                    response.code, state.getInstallArgs().getUser());
1463                            try {
1464                                ret = args.copyApk(mContainerService, true);
1465                            } catch (RemoteException e) {
1466                                Slog.e(TAG, "Could not contact the ContainerService");
1467                            }
1468                        } else {
1469                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1470                        }
1471
1472                        processPendingInstall(args, ret);
1473
1474                        mHandler.sendEmptyMessage(MCS_UNBIND);
1475                    }
1476
1477                    break;
1478                }
1479                case START_INTENT_FILTER_VERIFICATIONS: {
1480                    int userId = msg.arg1;
1481                    int verifierUid = msg.arg2;
1482                    PackageParser.Package pkg = (PackageParser.Package)msg.obj;
1483
1484                    verifyIntentFiltersIfNeeded(userId, verifierUid, pkg);
1485                    break;
1486                }
1487                case INTENT_FILTER_VERIFIED: {
1488                    final int verificationId = msg.arg1;
1489
1490                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1491                            verificationId);
1492                    if (state == null) {
1493                        Slog.w(TAG, "Invalid IntentFilter verification token "
1494                                + verificationId + " received");
1495                        break;
1496                    }
1497
1498                    final int userId = state.getUserId();
1499
1500                    Slog.d(TAG, "Processing IntentFilter verification with token:"
1501                            + verificationId + " and userId:" + userId);
1502
1503                    final IntentFilterVerificationResponse response =
1504                            (IntentFilterVerificationResponse) msg.obj;
1505
1506                    state.setVerifierResponse(response.callerUid, response.code);
1507
1508                    Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1509                            + " and userId:" + userId
1510                            + " is settings verifier response with response code:"
1511                            + response.code);
1512
1513                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1514                        Slog.d(TAG, "Domains failing verification: "
1515                                + response.getFailedDomainsString());
1516                    }
1517
1518                    if (state.isVerificationComplete()) {
1519                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1520                    } else {
1521                        Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1522                                + " was not said to be complete");
1523                    }
1524
1525                    break;
1526                }
1527            }
1528        }
1529    }
1530
1531    private StorageEventListener mStorageListener = new StorageEventListener() {
1532        @Override
1533        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1534            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1535                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1536                    loadPrivatePackages(vol);
1537                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1538                    unloadPrivatePackages(vol);
1539                }
1540            }
1541
1542            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1543                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1544                    updateExternalMediaStatus(true, false);
1545                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1546                    updateExternalMediaStatus(false, false);
1547                }
1548            }
1549        }
1550    };
1551
1552    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1553        if (userId >= UserHandle.USER_OWNER) {
1554            grantRequestedRuntimePermissionsForUser(pkg, userId);
1555        } else if (userId == UserHandle.USER_ALL) {
1556            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1557                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1558            }
1559        }
1560    }
1561
1562    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1563        SettingBase sb = (SettingBase) pkg.mExtras;
1564        if (sb == null) {
1565            return;
1566        }
1567
1568        PermissionsState permissionsState = sb.getPermissionsState();
1569
1570        for (String permission : pkg.requestedPermissions) {
1571            BasePermission bp = mSettings.mPermissions.get(permission);
1572            if (bp != null && bp.isRuntime()) {
1573                permissionsState.grantRuntimePermission(bp, userId);
1574            }
1575        }
1576    }
1577
1578    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1579        Bundle extras = null;
1580        switch (res.returnCode) {
1581            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1582                extras = new Bundle();
1583                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1584                        res.origPermission);
1585                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1586                        res.origPackage);
1587                break;
1588            }
1589        }
1590        return extras;
1591    }
1592
1593    void scheduleWriteSettingsLocked() {
1594        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1595            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1596        }
1597    }
1598
1599    void scheduleWritePackageRestrictionsLocked(int userId) {
1600        if (!sUserManager.exists(userId)) return;
1601        mDirtyUsers.add(userId);
1602        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1603            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1604        }
1605    }
1606
1607    public static PackageManagerService main(Context context, Installer installer,
1608            boolean factoryTest, boolean onlyCore) {
1609        PackageManagerService m = new PackageManagerService(context, installer,
1610                factoryTest, onlyCore);
1611        ServiceManager.addService("package", m);
1612        return m;
1613    }
1614
1615    static String[] splitString(String str, char sep) {
1616        int count = 1;
1617        int i = 0;
1618        while ((i=str.indexOf(sep, i)) >= 0) {
1619            count++;
1620            i++;
1621        }
1622
1623        String[] res = new String[count];
1624        i=0;
1625        count = 0;
1626        int lastI=0;
1627        while ((i=str.indexOf(sep, i)) >= 0) {
1628            res[count] = str.substring(lastI, i);
1629            count++;
1630            i++;
1631            lastI = i;
1632        }
1633        res[count] = str.substring(lastI, str.length());
1634        return res;
1635    }
1636
1637    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1638        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1639                Context.DISPLAY_SERVICE);
1640        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1641    }
1642
1643    public PackageManagerService(Context context, Installer installer,
1644            boolean factoryTest, boolean onlyCore) {
1645        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1646                SystemClock.uptimeMillis());
1647
1648        if (mSdkVersion <= 0) {
1649            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1650        }
1651
1652        mContext = context;
1653        mFactoryTest = factoryTest;
1654        mOnlyCore = onlyCore;
1655        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1656        mMetrics = new DisplayMetrics();
1657        mSettings = new Settings(mPackages);
1658        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1659                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1660        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1661                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1662        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1663                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1664        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1665                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1666        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1667                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1668        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1669                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1670
1671        // TODO: add a property to control this?
1672        long dexOptLRUThresholdInMinutes;
1673        if (mLazyDexOpt) {
1674            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1675        } else {
1676            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1677        }
1678        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1679
1680        String separateProcesses = SystemProperties.get("debug.separate_processes");
1681        if (separateProcesses != null && separateProcesses.length() > 0) {
1682            if ("*".equals(separateProcesses)) {
1683                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1684                mSeparateProcesses = null;
1685                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1686            } else {
1687                mDefParseFlags = 0;
1688                mSeparateProcesses = separateProcesses.split(",");
1689                Slog.w(TAG, "Running with debug.separate_processes: "
1690                        + separateProcesses);
1691            }
1692        } else {
1693            mDefParseFlags = 0;
1694            mSeparateProcesses = null;
1695        }
1696
1697        mInstaller = installer;
1698        mPackageDexOptimizer = new PackageDexOptimizer(this);
1699
1700        getDefaultDisplayMetrics(context, mMetrics);
1701
1702        SystemConfig systemConfig = SystemConfig.getInstance();
1703        mGlobalGids = systemConfig.getGlobalGids();
1704        mSystemPermissions = systemConfig.getSystemPermissions();
1705        mAvailableFeatures = systemConfig.getAvailableFeatures();
1706
1707        synchronized (mInstallLock) {
1708        // writer
1709        synchronized (mPackages) {
1710            mHandlerThread = new ServiceThread(TAG,
1711                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1712            mHandlerThread.start();
1713            mHandler = new PackageHandler(mHandlerThread.getLooper());
1714            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1715
1716            File dataDir = Environment.getDataDirectory();
1717            mAppDataDir = new File(dataDir, "data");
1718            mAppInstallDir = new File(dataDir, "app");
1719            mAppLib32InstallDir = new File(dataDir, "app-lib");
1720            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1721            mUserAppDataDir = new File(dataDir, "user");
1722            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1723
1724            sUserManager = new UserManagerService(context, this,
1725                    mInstallLock, mPackages);
1726
1727            // Propagate permission configuration in to package manager.
1728            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1729                    = systemConfig.getPermissions();
1730            for (int i=0; i<permConfig.size(); i++) {
1731                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1732                BasePermission bp = mSettings.mPermissions.get(perm.name);
1733                if (bp == null) {
1734                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1735                    mSettings.mPermissions.put(perm.name, bp);
1736                }
1737                if (perm.gids != null) {
1738                    bp.setGids(perm.gids, perm.perUser);
1739                }
1740            }
1741
1742            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1743            for (int i=0; i<libConfig.size(); i++) {
1744                mSharedLibraries.put(libConfig.keyAt(i),
1745                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1746            }
1747
1748            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1749
1750            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1751                    mSdkVersion, mOnlyCore);
1752
1753            String customResolverActivity = Resources.getSystem().getString(
1754                    R.string.config_customResolverActivity);
1755            if (TextUtils.isEmpty(customResolverActivity)) {
1756                customResolverActivity = null;
1757            } else {
1758                mCustomResolverComponentName = ComponentName.unflattenFromString(
1759                        customResolverActivity);
1760            }
1761
1762            long startTime = SystemClock.uptimeMillis();
1763
1764            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1765                    startTime);
1766
1767            // Set flag to monitor and not change apk file paths when
1768            // scanning install directories.
1769            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1770
1771            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1772
1773            /**
1774             * Add everything in the in the boot class path to the
1775             * list of process files because dexopt will have been run
1776             * if necessary during zygote startup.
1777             */
1778            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1779            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1780
1781            if (bootClassPath != null) {
1782                String[] bootClassPathElements = splitString(bootClassPath, ':');
1783                for (String element : bootClassPathElements) {
1784                    alreadyDexOpted.add(element);
1785                }
1786            } else {
1787                Slog.w(TAG, "No BOOTCLASSPATH found!");
1788            }
1789
1790            if (systemServerClassPath != null) {
1791                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1792                for (String element : systemServerClassPathElements) {
1793                    alreadyDexOpted.add(element);
1794                }
1795            } else {
1796                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1797            }
1798
1799            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1800            final String[] dexCodeInstructionSets =
1801                    getDexCodeInstructionSets(
1802                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1803
1804            /**
1805             * Ensure all external libraries have had dexopt run on them.
1806             */
1807            if (mSharedLibraries.size() > 0) {
1808                // NOTE: For now, we're compiling these system "shared libraries"
1809                // (and framework jars) into all available architectures. It's possible
1810                // to compile them only when we come across an app that uses them (there's
1811                // already logic for that in scanPackageLI) but that adds some complexity.
1812                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1813                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1814                        final String lib = libEntry.path;
1815                        if (lib == null) {
1816                            continue;
1817                        }
1818
1819                        try {
1820                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1821                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1822                                alreadyDexOpted.add(lib);
1823                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1824                            }
1825                        } catch (FileNotFoundException e) {
1826                            Slog.w(TAG, "Library not found: " + lib);
1827                        } catch (IOException e) {
1828                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1829                                    + e.getMessage());
1830                        }
1831                    }
1832                }
1833            }
1834
1835            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1836
1837            // Gross hack for now: we know this file doesn't contain any
1838            // code, so don't dexopt it to avoid the resulting log spew.
1839            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1840
1841            // Gross hack for now: we know this file is only part of
1842            // the boot class path for art, so don't dexopt it to
1843            // avoid the resulting log spew.
1844            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1845
1846            /**
1847             * And there are a number of commands implemented in Java, which
1848             * we currently need to do the dexopt on so that they can be
1849             * run from a non-root shell.
1850             */
1851            String[] frameworkFiles = frameworkDir.list();
1852            if (frameworkFiles != null) {
1853                // TODO: We could compile these only for the most preferred ABI. We should
1854                // first double check that the dex files for these commands are not referenced
1855                // by other system apps.
1856                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1857                    for (int i=0; i<frameworkFiles.length; i++) {
1858                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1859                        String path = libPath.getPath();
1860                        // Skip the file if we already did it.
1861                        if (alreadyDexOpted.contains(path)) {
1862                            continue;
1863                        }
1864                        // Skip the file if it is not a type we want to dexopt.
1865                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1866                            continue;
1867                        }
1868                        try {
1869                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1870                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1871                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1872                            }
1873                        } catch (FileNotFoundException e) {
1874                            Slog.w(TAG, "Jar not found: " + path);
1875                        } catch (IOException e) {
1876                            Slog.w(TAG, "Exception reading jar: " + path, e);
1877                        }
1878                    }
1879                }
1880            }
1881
1882            // Collect vendor overlay packages.
1883            // (Do this before scanning any apps.)
1884            // For security and version matching reason, only consider
1885            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1886            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1887            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1888                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1889
1890            // Find base frameworks (resource packages without code).
1891            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1892                    | PackageParser.PARSE_IS_SYSTEM_DIR
1893                    | PackageParser.PARSE_IS_PRIVILEGED,
1894                    scanFlags | SCAN_NO_DEX, 0);
1895
1896            // Collected privileged system packages.
1897            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1898            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1899                    | PackageParser.PARSE_IS_SYSTEM_DIR
1900                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1901
1902            // Collect ordinary system packages.
1903            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1904            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1905                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1906
1907            // Collect all vendor packages.
1908            File vendorAppDir = new File("/vendor/app");
1909            try {
1910                vendorAppDir = vendorAppDir.getCanonicalFile();
1911            } catch (IOException e) {
1912                // failed to look up canonical path, continue with original one
1913            }
1914            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1915                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1916
1917            // Collect all OEM packages.
1918            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1919            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1920                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1921
1922            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1923            mInstaller.moveFiles();
1924
1925            // Prune any system packages that no longer exist.
1926            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1927            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1928            if (!mOnlyCore) {
1929                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1930                while (psit.hasNext()) {
1931                    PackageSetting ps = psit.next();
1932
1933                    /*
1934                     * If this is not a system app, it can't be a
1935                     * disable system app.
1936                     */
1937                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1938                        continue;
1939                    }
1940
1941                    /*
1942                     * If the package is scanned, it's not erased.
1943                     */
1944                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1945                    if (scannedPkg != null) {
1946                        /*
1947                         * If the system app is both scanned and in the
1948                         * disabled packages list, then it must have been
1949                         * added via OTA. Remove it from the currently
1950                         * scanned package so the previously user-installed
1951                         * application can be scanned.
1952                         */
1953                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1954                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1955                                    + ps.name + "; removing system app.  Last known codePath="
1956                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1957                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1958                                    + scannedPkg.mVersionCode);
1959                            removePackageLI(ps, true);
1960                            expectingBetter.put(ps.name, ps.codePath);
1961                        }
1962
1963                        continue;
1964                    }
1965
1966                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1967                        psit.remove();
1968                        logCriticalInfo(Log.WARN, "System package " + ps.name
1969                                + " no longer exists; wiping its data");
1970                        removeDataDirsLI(ps.name);
1971                    } else {
1972                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1973                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1974                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1975                        }
1976                    }
1977                }
1978            }
1979
1980            //look for any incomplete package installations
1981            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1982            //clean up list
1983            for(int i = 0; i < deletePkgsList.size(); i++) {
1984                //clean up here
1985                cleanupInstallFailedPackage(deletePkgsList.get(i));
1986            }
1987            //delete tmp files
1988            deleteTempPackageFiles();
1989
1990            // Remove any shared userIDs that have no associated packages
1991            mSettings.pruneSharedUsersLPw();
1992
1993            if (!mOnlyCore) {
1994                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1995                        SystemClock.uptimeMillis());
1996                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
1997
1998                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1999                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2000
2001                /**
2002                 * Remove disable package settings for any updated system
2003                 * apps that were removed via an OTA. If they're not a
2004                 * previously-updated app, remove them completely.
2005                 * Otherwise, just revoke their system-level permissions.
2006                 */
2007                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2008                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2009                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2010
2011                    String msg;
2012                    if (deletedPkg == null) {
2013                        msg = "Updated system package " + deletedAppName
2014                                + " no longer exists; wiping its data";
2015                        removeDataDirsLI(deletedAppName);
2016                    } else {
2017                        msg = "Updated system app + " + deletedAppName
2018                                + " no longer present; removing system privileges for "
2019                                + deletedAppName;
2020
2021                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2022
2023                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2024                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2025                    }
2026                    logCriticalInfo(Log.WARN, msg);
2027                }
2028
2029                /**
2030                 * Make sure all system apps that we expected to appear on
2031                 * the userdata partition actually showed up. If they never
2032                 * appeared, crawl back and revive the system version.
2033                 */
2034                for (int i = 0; i < expectingBetter.size(); i++) {
2035                    final String packageName = expectingBetter.keyAt(i);
2036                    if (!mPackages.containsKey(packageName)) {
2037                        final File scanFile = expectingBetter.valueAt(i);
2038
2039                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2040                                + " but never showed up; reverting to system");
2041
2042                        final int reparseFlags;
2043                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2044                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2045                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2046                                    | PackageParser.PARSE_IS_PRIVILEGED;
2047                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2048                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2049                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2050                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2051                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2052                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2053                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2054                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2055                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2056                        } else {
2057                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2058                            continue;
2059                        }
2060
2061                        mSettings.enableSystemPackageLPw(packageName);
2062
2063                        try {
2064                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2065                        } catch (PackageManagerException e) {
2066                            Slog.e(TAG, "Failed to parse original system package: "
2067                                    + e.getMessage());
2068                        }
2069                    }
2070                }
2071            }
2072
2073            // Now that we know all of the shared libraries, update all clients to have
2074            // the correct library paths.
2075            updateAllSharedLibrariesLPw();
2076
2077            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2078                // NOTE: We ignore potential failures here during a system scan (like
2079                // the rest of the commands above) because there's precious little we
2080                // can do about it. A settings error is reported, though.
2081                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2082                        false /* force dexopt */, false /* defer dexopt */);
2083            }
2084
2085            // Now that we know all the packages we are keeping,
2086            // read and update their last usage times.
2087            mPackageUsage.readLP();
2088
2089            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2090                    SystemClock.uptimeMillis());
2091            Slog.i(TAG, "Time to scan packages: "
2092                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2093                    + " seconds");
2094
2095            // If the platform SDK has changed since the last time we booted,
2096            // we need to re-grant app permission to catch any new ones that
2097            // appear.  This is really a hack, and means that apps can in some
2098            // cases get permissions that the user didn't initially explicitly
2099            // allow...  it would be nice to have some better way to handle
2100            // this situation.
2101            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2102                    != mSdkVersion;
2103            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2104                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2105                    + "; regranting permissions for internal storage");
2106            mSettings.mInternalSdkPlatform = mSdkVersion;
2107
2108            // For now runtime permissions are toggled via a system property.
2109            if (!RUNTIME_PERMISSIONS_ENABLED) {
2110                // Remove the runtime permissions state if the feature
2111                // was disabled by flipping the system property.
2112                mSettings.deleteRuntimePermissionsFiles();
2113            }
2114
2115            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2116                    | (regrantPermissions
2117                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2118                            : 0));
2119
2120            // If this is the first boot, and it is a normal boot, then
2121            // we need to initialize the default preferred apps.
2122            if (!mRestoredSettings && !onlyCore) {
2123                mSettings.readDefaultPreferredAppsLPw(this, 0);
2124            }
2125
2126            // If this is first boot after an OTA, and a normal boot, then
2127            // we need to clear code cache directories.
2128            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2129            if (mIsUpgrade && !onlyCore) {
2130                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2131                for (String pkgName : mSettings.mPackages.keySet()) {
2132                    deleteCodeCacheDirsLI(pkgName);
2133                }
2134                mSettings.mFingerprint = Build.FINGERPRINT;
2135            }
2136
2137            // All the changes are done during package scanning.
2138            mSettings.updateInternalDatabaseVersion();
2139
2140            // can downgrade to reader
2141            mSettings.writeLPr();
2142
2143            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2144                    SystemClock.uptimeMillis());
2145
2146            mRequiredVerifierPackage = getRequiredVerifierLPr();
2147
2148            mInstallerService = new PackageInstallerService(context, this);
2149
2150            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2151            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2152                    mIntentFilterVerifierComponent);
2153
2154            primeDomainVerificationsLPw(false);
2155
2156        } // synchronized (mPackages)
2157        } // synchronized (mInstallLock)
2158
2159        // Now after opening every single application zip, make sure they
2160        // are all flushed.  Not really needed, but keeps things nice and
2161        // tidy.
2162        Runtime.getRuntime().gc();
2163    }
2164
2165    @Override
2166    public boolean isFirstBoot() {
2167        return !mRestoredSettings;
2168    }
2169
2170    @Override
2171    public boolean isOnlyCoreApps() {
2172        return mOnlyCore;
2173    }
2174
2175    @Override
2176    public boolean isUpgrade() {
2177        return mIsUpgrade;
2178    }
2179
2180    private String getRequiredVerifierLPr() {
2181        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2182        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2183                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2184
2185        String requiredVerifier = null;
2186
2187        final int N = receivers.size();
2188        for (int i = 0; i < N; i++) {
2189            final ResolveInfo info = receivers.get(i);
2190
2191            if (info.activityInfo == null) {
2192                continue;
2193            }
2194
2195            final String packageName = info.activityInfo.packageName;
2196
2197            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2198                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2199                continue;
2200            }
2201
2202            if (requiredVerifier != null) {
2203                throw new RuntimeException("There can be only one required verifier");
2204            }
2205
2206            requiredVerifier = packageName;
2207        }
2208
2209        return requiredVerifier;
2210    }
2211
2212    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2213        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2214        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2215                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2216
2217        ComponentName verifierComponentName = null;
2218
2219        int priority = -1000;
2220        final int N = receivers.size();
2221        for (int i = 0; i < N; i++) {
2222            final ResolveInfo info = receivers.get(i);
2223
2224            if (info.activityInfo == null) {
2225                continue;
2226            }
2227
2228            final String packageName = info.activityInfo.packageName;
2229
2230            final PackageSetting ps = mSettings.mPackages.get(packageName);
2231            if (ps == null) {
2232                continue;
2233            }
2234
2235            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2236                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2237                continue;
2238            }
2239
2240            // Select the IntentFilterVerifier with the highest priority
2241            if (priority < info.priority) {
2242                priority = info.priority;
2243                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2244                Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName +
2245                        " with priority: " + info.priority);
2246            }
2247        }
2248
2249        return verifierComponentName;
2250    }
2251
2252    private void primeDomainVerificationsLPw(boolean logging) {
2253        Slog.d(TAG, "Start priming domain verification");
2254        boolean updated = false;
2255        ArrayList<String> allHosts = new ArrayList<>();
2256        for (PackageParser.Package pkg : mPackages.values()) {
2257            final String packageName = pkg.packageName;
2258            if (!hasDomainURLs(pkg)) {
2259                if (logging) {
2260                    Slog.d(TAG, "No priming domain verifications for " +
2261                            "package with no domain URLs: " + packageName);
2262                }
2263                continue;
2264            }
2265            for (PackageParser.Activity a : pkg.activities) {
2266                for (ActivityIntentInfo filter : a.intents) {
2267                    if (hasValidDomains(filter, false)) {
2268                        allHosts.addAll(filter.getHostsList());
2269                    }
2270                }
2271            }
2272            if (allHosts.size() > 0) {
2273                allHosts.add("*");
2274            }
2275            IntentFilterVerificationInfo ivi =
2276                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHosts);
2277            if (ivi != null) {
2278                // We will always log this
2279                Slog.d(TAG, "Priming domain verifications for package: " + packageName);
2280                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2281                updated = true;
2282            }
2283            else {
2284                if (logging) {
2285                    Slog.d(TAG, "No priming domain verifications for package: " + packageName);
2286                }
2287            }
2288            allHosts.clear();
2289        }
2290        if (updated) {
2291            scheduleWriteSettingsLocked();
2292        }
2293        Slog.d(TAG, "End priming domain verification");
2294    }
2295
2296    @Override
2297    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2298            throws RemoteException {
2299        try {
2300            return super.onTransact(code, data, reply, flags);
2301        } catch (RuntimeException e) {
2302            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2303                Slog.wtf(TAG, "Package Manager Crash", e);
2304            }
2305            throw e;
2306        }
2307    }
2308
2309    void cleanupInstallFailedPackage(PackageSetting ps) {
2310        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2311
2312        removeDataDirsLI(ps.name);
2313        if (ps.codePath != null) {
2314            if (ps.codePath.isDirectory()) {
2315                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2316            } else {
2317                ps.codePath.delete();
2318            }
2319        }
2320        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2321            if (ps.resourcePath.isDirectory()) {
2322                FileUtils.deleteContents(ps.resourcePath);
2323            }
2324            ps.resourcePath.delete();
2325        }
2326        mSettings.removePackageLPw(ps.name);
2327    }
2328
2329    static int[] appendInts(int[] cur, int[] add) {
2330        if (add == null) return cur;
2331        if (cur == null) return add;
2332        final int N = add.length;
2333        for (int i=0; i<N; i++) {
2334            cur = appendInt(cur, add[i]);
2335        }
2336        return cur;
2337    }
2338
2339    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2340        if (!sUserManager.exists(userId)) return null;
2341        final PackageSetting ps = (PackageSetting) p.mExtras;
2342        if (ps == null) {
2343            return null;
2344        }
2345
2346        final PermissionsState permissionsState = ps.getPermissionsState();
2347
2348        final int[] gids = permissionsState.computeGids(userId);
2349        final Set<String> permissions = permissionsState.getPermissions(userId);
2350        final PackageUserState state = ps.readUserState(userId);
2351
2352        return PackageParser.generatePackageInfo(p, gids, flags,
2353                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2354    }
2355
2356    @Override
2357    public boolean isPackageAvailable(String packageName, int userId) {
2358        if (!sUserManager.exists(userId)) return false;
2359        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2360        synchronized (mPackages) {
2361            PackageParser.Package p = mPackages.get(packageName);
2362            if (p != null) {
2363                final PackageSetting ps = (PackageSetting) p.mExtras;
2364                if (ps != null) {
2365                    final PackageUserState state = ps.readUserState(userId);
2366                    if (state != null) {
2367                        return PackageParser.isAvailable(state);
2368                    }
2369                }
2370            }
2371        }
2372        return false;
2373    }
2374
2375    @Override
2376    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2377        if (!sUserManager.exists(userId)) return null;
2378        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2379        // reader
2380        synchronized (mPackages) {
2381            PackageParser.Package p = mPackages.get(packageName);
2382            if (DEBUG_PACKAGE_INFO)
2383                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2384            if (p != null) {
2385                return generatePackageInfo(p, flags, userId);
2386            }
2387            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2388                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2389            }
2390        }
2391        return null;
2392    }
2393
2394    @Override
2395    public String[] currentToCanonicalPackageNames(String[] names) {
2396        String[] out = new String[names.length];
2397        // reader
2398        synchronized (mPackages) {
2399            for (int i=names.length-1; i>=0; i--) {
2400                PackageSetting ps = mSettings.mPackages.get(names[i]);
2401                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2402            }
2403        }
2404        return out;
2405    }
2406
2407    @Override
2408    public String[] canonicalToCurrentPackageNames(String[] names) {
2409        String[] out = new String[names.length];
2410        // reader
2411        synchronized (mPackages) {
2412            for (int i=names.length-1; i>=0; i--) {
2413                String cur = mSettings.mRenamedPackages.get(names[i]);
2414                out[i] = cur != null ? cur : names[i];
2415            }
2416        }
2417        return out;
2418    }
2419
2420    @Override
2421    public int getPackageUid(String packageName, int userId) {
2422        if (!sUserManager.exists(userId)) return -1;
2423        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2424
2425        // reader
2426        synchronized (mPackages) {
2427            PackageParser.Package p = mPackages.get(packageName);
2428            if(p != null) {
2429                return UserHandle.getUid(userId, p.applicationInfo.uid);
2430            }
2431            PackageSetting ps = mSettings.mPackages.get(packageName);
2432            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2433                return -1;
2434            }
2435            p = ps.pkg;
2436            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2437        }
2438    }
2439
2440    @Override
2441    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2442        if (!sUserManager.exists(userId)) {
2443            return null;
2444        }
2445
2446        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2447                "getPackageGids");
2448
2449        // reader
2450        synchronized (mPackages) {
2451            PackageParser.Package p = mPackages.get(packageName);
2452            if (DEBUG_PACKAGE_INFO) {
2453                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2454            }
2455            if (p != null) {
2456                PackageSetting ps = (PackageSetting) p.mExtras;
2457                return ps.getPermissionsState().computeGids(userId);
2458            }
2459        }
2460
2461        return null;
2462    }
2463
2464    static PermissionInfo generatePermissionInfo(
2465            BasePermission bp, int flags) {
2466        if (bp.perm != null) {
2467            return PackageParser.generatePermissionInfo(bp.perm, flags);
2468        }
2469        PermissionInfo pi = new PermissionInfo();
2470        pi.name = bp.name;
2471        pi.packageName = bp.sourcePackage;
2472        pi.nonLocalizedLabel = bp.name;
2473        pi.protectionLevel = bp.protectionLevel;
2474        return pi;
2475    }
2476
2477    @Override
2478    public PermissionInfo getPermissionInfo(String name, int flags) {
2479        // reader
2480        synchronized (mPackages) {
2481            final BasePermission p = mSettings.mPermissions.get(name);
2482            if (p != null) {
2483                return generatePermissionInfo(p, flags);
2484            }
2485            return null;
2486        }
2487    }
2488
2489    @Override
2490    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2491        // reader
2492        synchronized (mPackages) {
2493            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2494            for (BasePermission p : mSettings.mPermissions.values()) {
2495                if (group == null) {
2496                    if (p.perm == null || p.perm.info.group == null) {
2497                        out.add(generatePermissionInfo(p, flags));
2498                    }
2499                } else {
2500                    if (p.perm != null && group.equals(p.perm.info.group)) {
2501                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2502                    }
2503                }
2504            }
2505
2506            if (out.size() > 0) {
2507                return out;
2508            }
2509            return mPermissionGroups.containsKey(group) ? out : null;
2510        }
2511    }
2512
2513    @Override
2514    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2515        // reader
2516        synchronized (mPackages) {
2517            return PackageParser.generatePermissionGroupInfo(
2518                    mPermissionGroups.get(name), flags);
2519        }
2520    }
2521
2522    @Override
2523    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2524        // reader
2525        synchronized (mPackages) {
2526            final int N = mPermissionGroups.size();
2527            ArrayList<PermissionGroupInfo> out
2528                    = new ArrayList<PermissionGroupInfo>(N);
2529            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2530                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2531            }
2532            return out;
2533        }
2534    }
2535
2536    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2537            int userId) {
2538        if (!sUserManager.exists(userId)) return null;
2539        PackageSetting ps = mSettings.mPackages.get(packageName);
2540        if (ps != null) {
2541            if (ps.pkg == null) {
2542                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2543                        flags, userId);
2544                if (pInfo != null) {
2545                    return pInfo.applicationInfo;
2546                }
2547                return null;
2548            }
2549            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2550                    ps.readUserState(userId), userId);
2551        }
2552        return null;
2553    }
2554
2555    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2556            int userId) {
2557        if (!sUserManager.exists(userId)) return null;
2558        PackageSetting ps = mSettings.mPackages.get(packageName);
2559        if (ps != null) {
2560            PackageParser.Package pkg = ps.pkg;
2561            if (pkg == null) {
2562                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2563                    return null;
2564                }
2565                // Only data remains, so we aren't worried about code paths
2566                pkg = new PackageParser.Package(packageName);
2567                pkg.applicationInfo.packageName = packageName;
2568                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2569                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2570                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2571                        packageName, userId).getAbsolutePath();
2572                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2573                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2574            }
2575            return generatePackageInfo(pkg, flags, userId);
2576        }
2577        return null;
2578    }
2579
2580    @Override
2581    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2582        if (!sUserManager.exists(userId)) return null;
2583        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2584        // writer
2585        synchronized (mPackages) {
2586            PackageParser.Package p = mPackages.get(packageName);
2587            if (DEBUG_PACKAGE_INFO) Log.v(
2588                    TAG, "getApplicationInfo " + packageName
2589                    + ": " + p);
2590            if (p != null) {
2591                PackageSetting ps = mSettings.mPackages.get(packageName);
2592                if (ps == null) return null;
2593                // Note: isEnabledLP() does not apply here - always return info
2594                return PackageParser.generateApplicationInfo(
2595                        p, flags, ps.readUserState(userId), userId);
2596            }
2597            if ("android".equals(packageName)||"system".equals(packageName)) {
2598                return mAndroidApplication;
2599            }
2600            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2601                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2602            }
2603        }
2604        return null;
2605    }
2606
2607
2608    @Override
2609    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2610        mContext.enforceCallingOrSelfPermission(
2611                android.Manifest.permission.CLEAR_APP_CACHE, null);
2612        // Queue up an async operation since clearing cache may take a little while.
2613        mHandler.post(new Runnable() {
2614            public void run() {
2615                mHandler.removeCallbacks(this);
2616                int retCode = -1;
2617                synchronized (mInstallLock) {
2618                    retCode = mInstaller.freeCache(freeStorageSize);
2619                    if (retCode < 0) {
2620                        Slog.w(TAG, "Couldn't clear application caches");
2621                    }
2622                }
2623                if (observer != null) {
2624                    try {
2625                        observer.onRemoveCompleted(null, (retCode >= 0));
2626                    } catch (RemoteException e) {
2627                        Slog.w(TAG, "RemoveException when invoking call back");
2628                    }
2629                }
2630            }
2631        });
2632    }
2633
2634    @Override
2635    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
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(freeStorageSize);
2645                    if (retCode < 0) {
2646                        Slog.w(TAG, "Couldn't clear application caches");
2647                    }
2648                }
2649                if(pi != null) {
2650                    try {
2651                        // Callback via pending intent
2652                        int code = (retCode >= 0) ? 1 : 0;
2653                        pi.sendIntent(null, code, null,
2654                                null, null);
2655                    } catch (SendIntentException e1) {
2656                        Slog.i(TAG, "Failed to send pending intent");
2657                    }
2658                }
2659            }
2660        });
2661    }
2662
2663    void freeStorage(long freeStorageSize) throws IOException {
2664        synchronized (mInstallLock) {
2665            if (mInstaller.freeCache(freeStorageSize) < 0) {
2666                throw new IOException("Failed to free enough space");
2667            }
2668        }
2669    }
2670
2671    @Override
2672    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2673        if (!sUserManager.exists(userId)) return null;
2674        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2675        synchronized (mPackages) {
2676            PackageParser.Activity a = mActivities.mActivities.get(component);
2677
2678            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2679            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2680                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2681                if (ps == null) return null;
2682                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2683                        userId);
2684            }
2685            if (mResolveComponentName.equals(component)) {
2686                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2687                        new PackageUserState(), userId);
2688            }
2689        }
2690        return null;
2691    }
2692
2693    @Override
2694    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2695            String resolvedType) {
2696        synchronized (mPackages) {
2697            PackageParser.Activity a = mActivities.mActivities.get(component);
2698            if (a == null) {
2699                return false;
2700            }
2701            for (int i=0; i<a.intents.size(); i++) {
2702                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2703                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2704                    return true;
2705                }
2706            }
2707            return false;
2708        }
2709    }
2710
2711    @Override
2712    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2713        if (!sUserManager.exists(userId)) return null;
2714        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2715        synchronized (mPackages) {
2716            PackageParser.Activity a = mReceivers.mActivities.get(component);
2717            if (DEBUG_PACKAGE_INFO) Log.v(
2718                TAG, "getReceiverInfo " + component + ": " + a);
2719            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2720                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2721                if (ps == null) return null;
2722                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2723                        userId);
2724            }
2725        }
2726        return null;
2727    }
2728
2729    @Override
2730    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2731        if (!sUserManager.exists(userId)) return null;
2732        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2733        synchronized (mPackages) {
2734            PackageParser.Service s = mServices.mServices.get(component);
2735            if (DEBUG_PACKAGE_INFO) Log.v(
2736                TAG, "getServiceInfo " + component + ": " + s);
2737            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2738                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2739                if (ps == null) return null;
2740                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2741                        userId);
2742            }
2743        }
2744        return null;
2745    }
2746
2747    @Override
2748    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2749        if (!sUserManager.exists(userId)) return null;
2750        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2751        synchronized (mPackages) {
2752            PackageParser.Provider p = mProviders.mProviders.get(component);
2753            if (DEBUG_PACKAGE_INFO) Log.v(
2754                TAG, "getProviderInfo " + component + ": " + p);
2755            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2756                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2757                if (ps == null) return null;
2758                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2759                        userId);
2760            }
2761        }
2762        return null;
2763    }
2764
2765    @Override
2766    public String[] getSystemSharedLibraryNames() {
2767        Set<String> libSet;
2768        synchronized (mPackages) {
2769            libSet = mSharedLibraries.keySet();
2770            int size = libSet.size();
2771            if (size > 0) {
2772                String[] libs = new String[size];
2773                libSet.toArray(libs);
2774                return libs;
2775            }
2776        }
2777        return null;
2778    }
2779
2780    /**
2781     * @hide
2782     */
2783    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2784        synchronized (mPackages) {
2785            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2786            if (lib != null && lib.apk != null) {
2787                return mPackages.get(lib.apk);
2788            }
2789        }
2790        return null;
2791    }
2792
2793    @Override
2794    public FeatureInfo[] getSystemAvailableFeatures() {
2795        Collection<FeatureInfo> featSet;
2796        synchronized (mPackages) {
2797            featSet = mAvailableFeatures.values();
2798            int size = featSet.size();
2799            if (size > 0) {
2800                FeatureInfo[] features = new FeatureInfo[size+1];
2801                featSet.toArray(features);
2802                FeatureInfo fi = new FeatureInfo();
2803                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2804                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2805                features[size] = fi;
2806                return features;
2807            }
2808        }
2809        return null;
2810    }
2811
2812    @Override
2813    public boolean hasSystemFeature(String name) {
2814        synchronized (mPackages) {
2815            return mAvailableFeatures.containsKey(name);
2816        }
2817    }
2818
2819    private void checkValidCaller(int uid, int userId) {
2820        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2821            return;
2822
2823        throw new SecurityException("Caller uid=" + uid
2824                + " is not privileged to communicate with user=" + userId);
2825    }
2826
2827    @Override
2828    public int checkPermission(String permName, String pkgName, int userId) {
2829        if (!sUserManager.exists(userId)) {
2830            return PackageManager.PERMISSION_DENIED;
2831        }
2832
2833        synchronized (mPackages) {
2834            final PackageParser.Package p = mPackages.get(pkgName);
2835            if (p != null && p.mExtras != null) {
2836                final PackageSetting ps = (PackageSetting) p.mExtras;
2837                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2838                    return PackageManager.PERMISSION_GRANTED;
2839                }
2840            }
2841        }
2842
2843        return PackageManager.PERMISSION_DENIED;
2844    }
2845
2846    @Override
2847    public int checkUidPermission(String permName, int uid) {
2848        final int userId = UserHandle.getUserId(uid);
2849
2850        if (!sUserManager.exists(userId)) {
2851            return PackageManager.PERMISSION_DENIED;
2852        }
2853
2854        synchronized (mPackages) {
2855            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2856            if (obj != null) {
2857                final SettingBase ps = (SettingBase) obj;
2858                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2859                    return PackageManager.PERMISSION_GRANTED;
2860                }
2861            } else {
2862                ArraySet<String> perms = mSystemPermissions.get(uid);
2863                if (perms != null && perms.contains(permName)) {
2864                    return PackageManager.PERMISSION_GRANTED;
2865                }
2866            }
2867        }
2868
2869        return PackageManager.PERMISSION_DENIED;
2870    }
2871
2872    /**
2873     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2874     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2875     * @param checkShell TODO(yamasani):
2876     * @param message the message to log on security exception
2877     */
2878    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2879            boolean checkShell, String message) {
2880        if (userId < 0) {
2881            throw new IllegalArgumentException("Invalid userId " + userId);
2882        }
2883        if (checkShell) {
2884            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2885        }
2886        if (userId == UserHandle.getUserId(callingUid)) return;
2887        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2888            if (requireFullPermission) {
2889                mContext.enforceCallingOrSelfPermission(
2890                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2891            } else {
2892                try {
2893                    mContext.enforceCallingOrSelfPermission(
2894                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2895                } catch (SecurityException se) {
2896                    mContext.enforceCallingOrSelfPermission(
2897                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2898                }
2899            }
2900        }
2901    }
2902
2903    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2904        if (callingUid == Process.SHELL_UID) {
2905            if (userHandle >= 0
2906                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2907                throw new SecurityException("Shell does not have permission to access user "
2908                        + userHandle);
2909            } else if (userHandle < 0) {
2910                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2911                        + Debug.getCallers(3));
2912            }
2913        }
2914    }
2915
2916    private BasePermission findPermissionTreeLP(String permName) {
2917        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2918            if (permName.startsWith(bp.name) &&
2919                    permName.length() > bp.name.length() &&
2920                    permName.charAt(bp.name.length()) == '.') {
2921                return bp;
2922            }
2923        }
2924        return null;
2925    }
2926
2927    private BasePermission checkPermissionTreeLP(String permName) {
2928        if (permName != null) {
2929            BasePermission bp = findPermissionTreeLP(permName);
2930            if (bp != null) {
2931                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2932                    return bp;
2933                }
2934                throw new SecurityException("Calling uid "
2935                        + Binder.getCallingUid()
2936                        + " is not allowed to add to permission tree "
2937                        + bp.name + " owned by uid " + bp.uid);
2938            }
2939        }
2940        throw new SecurityException("No permission tree found for " + permName);
2941    }
2942
2943    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2944        if (s1 == null) {
2945            return s2 == null;
2946        }
2947        if (s2 == null) {
2948            return false;
2949        }
2950        if (s1.getClass() != s2.getClass()) {
2951            return false;
2952        }
2953        return s1.equals(s2);
2954    }
2955
2956    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2957        if (pi1.icon != pi2.icon) return false;
2958        if (pi1.logo != pi2.logo) return false;
2959        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2960        if (!compareStrings(pi1.name, pi2.name)) return false;
2961        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2962        // We'll take care of setting this one.
2963        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2964        // These are not currently stored in settings.
2965        //if (!compareStrings(pi1.group, pi2.group)) return false;
2966        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2967        //if (pi1.labelRes != pi2.labelRes) return false;
2968        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2969        return true;
2970    }
2971
2972    int permissionInfoFootprint(PermissionInfo info) {
2973        int size = info.name.length();
2974        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2975        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2976        return size;
2977    }
2978
2979    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2980        int size = 0;
2981        for (BasePermission perm : mSettings.mPermissions.values()) {
2982            if (perm.uid == tree.uid) {
2983                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2984            }
2985        }
2986        return size;
2987    }
2988
2989    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2990        // We calculate the max size of permissions defined by this uid and throw
2991        // if that plus the size of 'info' would exceed our stated maximum.
2992        if (tree.uid != Process.SYSTEM_UID) {
2993            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2994            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2995                throw new SecurityException("Permission tree size cap exceeded");
2996            }
2997        }
2998    }
2999
3000    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3001        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3002            throw new SecurityException("Label must be specified in permission");
3003        }
3004        BasePermission tree = checkPermissionTreeLP(info.name);
3005        BasePermission bp = mSettings.mPermissions.get(info.name);
3006        boolean added = bp == null;
3007        boolean changed = true;
3008        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3009        if (added) {
3010            enforcePermissionCapLocked(info, tree);
3011            bp = new BasePermission(info.name, tree.sourcePackage,
3012                    BasePermission.TYPE_DYNAMIC);
3013        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3014            throw new SecurityException(
3015                    "Not allowed to modify non-dynamic permission "
3016                    + info.name);
3017        } else {
3018            if (bp.protectionLevel == fixedLevel
3019                    && bp.perm.owner.equals(tree.perm.owner)
3020                    && bp.uid == tree.uid
3021                    && comparePermissionInfos(bp.perm.info, info)) {
3022                changed = false;
3023            }
3024        }
3025        bp.protectionLevel = fixedLevel;
3026        info = new PermissionInfo(info);
3027        info.protectionLevel = fixedLevel;
3028        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3029        bp.perm.info.packageName = tree.perm.info.packageName;
3030        bp.uid = tree.uid;
3031        if (added) {
3032            mSettings.mPermissions.put(info.name, bp);
3033        }
3034        if (changed) {
3035            if (!async) {
3036                mSettings.writeLPr();
3037            } else {
3038                scheduleWriteSettingsLocked();
3039            }
3040        }
3041        return added;
3042    }
3043
3044    @Override
3045    public boolean addPermission(PermissionInfo info) {
3046        synchronized (mPackages) {
3047            return addPermissionLocked(info, false);
3048        }
3049    }
3050
3051    @Override
3052    public boolean addPermissionAsync(PermissionInfo info) {
3053        synchronized (mPackages) {
3054            return addPermissionLocked(info, true);
3055        }
3056    }
3057
3058    @Override
3059    public void removePermission(String name) {
3060        synchronized (mPackages) {
3061            checkPermissionTreeLP(name);
3062            BasePermission bp = mSettings.mPermissions.get(name);
3063            if (bp != null) {
3064                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3065                    throw new SecurityException(
3066                            "Not allowed to modify non-dynamic permission "
3067                            + name);
3068                }
3069                mSettings.mPermissions.remove(name);
3070                mSettings.writeLPr();
3071            }
3072        }
3073    }
3074
3075    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3076            BasePermission bp) {
3077        int index = pkg.requestedPermissions.indexOf(bp.name);
3078        if (index == -1) {
3079            throw new SecurityException("Package " + pkg.packageName
3080                    + " has not requested permission " + bp.name);
3081        }
3082        if (!bp.isRuntime()) {
3083            throw new SecurityException("Permission " + bp.name
3084                    + " is not a changeable permission type");
3085        }
3086    }
3087
3088    @Override
3089    public boolean grantPermission(String packageName, String name, int userId) {
3090        if (!RUNTIME_PERMISSIONS_ENABLED) {
3091            return false;
3092        }
3093
3094        if (!sUserManager.exists(userId)) {
3095            return false;
3096        }
3097
3098        mContext.enforceCallingOrSelfPermission(
3099                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3100                "grantPermission");
3101
3102        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3103                "grantPermission");
3104
3105        boolean gidsChanged = false;
3106        final SettingBase sb;
3107
3108        synchronized (mPackages) {
3109            final PackageParser.Package pkg = mPackages.get(packageName);
3110            if (pkg == null) {
3111                throw new IllegalArgumentException("Unknown package: " + packageName);
3112            }
3113
3114            final BasePermission bp = mSettings.mPermissions.get(name);
3115            if (bp == null) {
3116                throw new IllegalArgumentException("Unknown permission: " + name);
3117            }
3118
3119            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3120
3121            sb = (SettingBase) pkg.mExtras;
3122            if (sb == null) {
3123                throw new IllegalArgumentException("Unknown package: " + packageName);
3124            }
3125
3126            final PermissionsState permissionsState = sb.getPermissionsState();
3127
3128            final int result = permissionsState.grantRuntimePermission(bp, userId);
3129            switch (result) {
3130                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3131                    return false;
3132                }
3133
3134                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3135                    gidsChanged = true;
3136                } break;
3137            }
3138
3139            // Not critical if that is lost - app has to request again.
3140            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3141        }
3142
3143        if (gidsChanged) {
3144            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3145        }
3146
3147        return true;
3148    }
3149
3150    @Override
3151    public boolean revokePermission(String packageName, String name, int userId) {
3152        if (!RUNTIME_PERMISSIONS_ENABLED) {
3153            return false;
3154        }
3155
3156        if (!sUserManager.exists(userId)) {
3157            return false;
3158        }
3159
3160        mContext.enforceCallingOrSelfPermission(
3161                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3162                "revokePermission");
3163
3164        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3165                "revokePermission");
3166
3167        final SettingBase sb;
3168
3169        synchronized (mPackages) {
3170            final PackageParser.Package pkg = mPackages.get(packageName);
3171            if (pkg == null) {
3172                throw new IllegalArgumentException("Unknown package: " + packageName);
3173            }
3174
3175            final BasePermission bp = mSettings.mPermissions.get(name);
3176            if (bp == null) {
3177                throw new IllegalArgumentException("Unknown permission: " + name);
3178            }
3179
3180            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3181
3182            sb = (SettingBase) pkg.mExtras;
3183            if (sb == null) {
3184                throw new IllegalArgumentException("Unknown package: " + packageName);
3185            }
3186
3187            final PermissionsState permissionsState = sb.getPermissionsState();
3188
3189            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3190                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3191                return false;
3192            }
3193
3194            // Critical, after this call all should never have the permission.
3195            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3196        }
3197
3198        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3199
3200        return true;
3201    }
3202
3203    @Override
3204    public boolean isProtectedBroadcast(String actionName) {
3205        synchronized (mPackages) {
3206            return mProtectedBroadcasts.contains(actionName);
3207        }
3208    }
3209
3210    @Override
3211    public int checkSignatures(String pkg1, String pkg2) {
3212        synchronized (mPackages) {
3213            final PackageParser.Package p1 = mPackages.get(pkg1);
3214            final PackageParser.Package p2 = mPackages.get(pkg2);
3215            if (p1 == null || p1.mExtras == null
3216                    || p2 == null || p2.mExtras == null) {
3217                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3218            }
3219            return compareSignatures(p1.mSignatures, p2.mSignatures);
3220        }
3221    }
3222
3223    @Override
3224    public int checkUidSignatures(int uid1, int uid2) {
3225        // Map to base uids.
3226        uid1 = UserHandle.getAppId(uid1);
3227        uid2 = UserHandle.getAppId(uid2);
3228        // reader
3229        synchronized (mPackages) {
3230            Signature[] s1;
3231            Signature[] s2;
3232            Object obj = mSettings.getUserIdLPr(uid1);
3233            if (obj != null) {
3234                if (obj instanceof SharedUserSetting) {
3235                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3236                } else if (obj instanceof PackageSetting) {
3237                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3238                } else {
3239                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3240                }
3241            } else {
3242                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3243            }
3244            obj = mSettings.getUserIdLPr(uid2);
3245            if (obj != null) {
3246                if (obj instanceof SharedUserSetting) {
3247                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3248                } else if (obj instanceof PackageSetting) {
3249                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3250                } else {
3251                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3252                }
3253            } else {
3254                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3255            }
3256            return compareSignatures(s1, s2);
3257        }
3258    }
3259
3260    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3261        final long identity = Binder.clearCallingIdentity();
3262        try {
3263            if (sb instanceof SharedUserSetting) {
3264                SharedUserSetting sus = (SharedUserSetting) sb;
3265                final int packageCount = sus.packages.size();
3266                for (int i = 0; i < packageCount; i++) {
3267                    PackageSetting susPs = sus.packages.valueAt(i);
3268                    if (userId == UserHandle.USER_ALL) {
3269                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3270                    } else {
3271                        final int uid = UserHandle.getUid(userId, susPs.appId);
3272                        killUid(uid, reason);
3273                    }
3274                }
3275            } else if (sb instanceof PackageSetting) {
3276                PackageSetting ps = (PackageSetting) sb;
3277                if (userId == UserHandle.USER_ALL) {
3278                    killApplication(ps.pkg.packageName, ps.appId, reason);
3279                } else {
3280                    final int uid = UserHandle.getUid(userId, ps.appId);
3281                    killUid(uid, reason);
3282                }
3283            }
3284        } finally {
3285            Binder.restoreCallingIdentity(identity);
3286        }
3287    }
3288
3289    private static void killUid(int uid, String reason) {
3290        IActivityManager am = ActivityManagerNative.getDefault();
3291        if (am != null) {
3292            try {
3293                am.killUid(uid, reason);
3294            } catch (RemoteException e) {
3295                /* ignore - same process */
3296            }
3297        }
3298    }
3299
3300    /**
3301     * Compares two sets of signatures. Returns:
3302     * <br />
3303     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3304     * <br />
3305     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3306     * <br />
3307     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3308     * <br />
3309     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3310     * <br />
3311     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3312     */
3313    static int compareSignatures(Signature[] s1, Signature[] s2) {
3314        if (s1 == null) {
3315            return s2 == null
3316                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3317                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3318        }
3319
3320        if (s2 == null) {
3321            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3322        }
3323
3324        if (s1.length != s2.length) {
3325            return PackageManager.SIGNATURE_NO_MATCH;
3326        }
3327
3328        // Since both signature sets are of size 1, we can compare without HashSets.
3329        if (s1.length == 1) {
3330            return s1[0].equals(s2[0]) ?
3331                    PackageManager.SIGNATURE_MATCH :
3332                    PackageManager.SIGNATURE_NO_MATCH;
3333        }
3334
3335        ArraySet<Signature> set1 = new ArraySet<Signature>();
3336        for (Signature sig : s1) {
3337            set1.add(sig);
3338        }
3339        ArraySet<Signature> set2 = new ArraySet<Signature>();
3340        for (Signature sig : s2) {
3341            set2.add(sig);
3342        }
3343        // Make sure s2 contains all signatures in s1.
3344        if (set1.equals(set2)) {
3345            return PackageManager.SIGNATURE_MATCH;
3346        }
3347        return PackageManager.SIGNATURE_NO_MATCH;
3348    }
3349
3350    /**
3351     * If the database version for this type of package (internal storage or
3352     * external storage) is less than the version where package signatures
3353     * were updated, return true.
3354     */
3355    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3356        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3357                DatabaseVersion.SIGNATURE_END_ENTITY))
3358                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3359                        DatabaseVersion.SIGNATURE_END_ENTITY));
3360    }
3361
3362    /**
3363     * Used for backward compatibility to make sure any packages with
3364     * certificate chains get upgraded to the new style. {@code existingSigs}
3365     * will be in the old format (since they were stored on disk from before the
3366     * system upgrade) and {@code scannedSigs} will be in the newer format.
3367     */
3368    private int compareSignaturesCompat(PackageSignatures existingSigs,
3369            PackageParser.Package scannedPkg) {
3370        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3371            return PackageManager.SIGNATURE_NO_MATCH;
3372        }
3373
3374        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3375        for (Signature sig : existingSigs.mSignatures) {
3376            existingSet.add(sig);
3377        }
3378        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3379        for (Signature sig : scannedPkg.mSignatures) {
3380            try {
3381                Signature[] chainSignatures = sig.getChainSignatures();
3382                for (Signature chainSig : chainSignatures) {
3383                    scannedCompatSet.add(chainSig);
3384                }
3385            } catch (CertificateEncodingException e) {
3386                scannedCompatSet.add(sig);
3387            }
3388        }
3389        /*
3390         * Make sure the expanded scanned set contains all signatures in the
3391         * existing one.
3392         */
3393        if (scannedCompatSet.equals(existingSet)) {
3394            // Migrate the old signatures to the new scheme.
3395            existingSigs.assignSignatures(scannedPkg.mSignatures);
3396            // The new KeySets will be re-added later in the scanning process.
3397            synchronized (mPackages) {
3398                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3399            }
3400            return PackageManager.SIGNATURE_MATCH;
3401        }
3402        return PackageManager.SIGNATURE_NO_MATCH;
3403    }
3404
3405    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3406        if (isExternal(scannedPkg)) {
3407            return mSettings.isExternalDatabaseVersionOlderThan(
3408                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3409        } else {
3410            return mSettings.isInternalDatabaseVersionOlderThan(
3411                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3412        }
3413    }
3414
3415    private int compareSignaturesRecover(PackageSignatures existingSigs,
3416            PackageParser.Package scannedPkg) {
3417        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3418            return PackageManager.SIGNATURE_NO_MATCH;
3419        }
3420
3421        String msg = null;
3422        try {
3423            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3424                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3425                        + scannedPkg.packageName);
3426                return PackageManager.SIGNATURE_MATCH;
3427            }
3428        } catch (CertificateException e) {
3429            msg = e.getMessage();
3430        }
3431
3432        logCriticalInfo(Log.INFO,
3433                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3434        return PackageManager.SIGNATURE_NO_MATCH;
3435    }
3436
3437    @Override
3438    public String[] getPackagesForUid(int uid) {
3439        uid = UserHandle.getAppId(uid);
3440        // reader
3441        synchronized (mPackages) {
3442            Object obj = mSettings.getUserIdLPr(uid);
3443            if (obj instanceof SharedUserSetting) {
3444                final SharedUserSetting sus = (SharedUserSetting) obj;
3445                final int N = sus.packages.size();
3446                final String[] res = new String[N];
3447                final Iterator<PackageSetting> it = sus.packages.iterator();
3448                int i = 0;
3449                while (it.hasNext()) {
3450                    res[i++] = it.next().name;
3451                }
3452                return res;
3453            } else if (obj instanceof PackageSetting) {
3454                final PackageSetting ps = (PackageSetting) obj;
3455                return new String[] { ps.name };
3456            }
3457        }
3458        return null;
3459    }
3460
3461    @Override
3462    public String getNameForUid(int uid) {
3463        // reader
3464        synchronized (mPackages) {
3465            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3466            if (obj instanceof SharedUserSetting) {
3467                final SharedUserSetting sus = (SharedUserSetting) obj;
3468                return sus.name + ":" + sus.userId;
3469            } else if (obj instanceof PackageSetting) {
3470                final PackageSetting ps = (PackageSetting) obj;
3471                return ps.name;
3472            }
3473        }
3474        return null;
3475    }
3476
3477    @Override
3478    public int getUidForSharedUser(String sharedUserName) {
3479        if(sharedUserName == null) {
3480            return -1;
3481        }
3482        // reader
3483        synchronized (mPackages) {
3484            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3485            if (suid == null) {
3486                return -1;
3487            }
3488            return suid.userId;
3489        }
3490    }
3491
3492    @Override
3493    public int getFlagsForUid(int uid) {
3494        synchronized (mPackages) {
3495            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3496            if (obj instanceof SharedUserSetting) {
3497                final SharedUserSetting sus = (SharedUserSetting) obj;
3498                return sus.pkgFlags;
3499            } else if (obj instanceof PackageSetting) {
3500                final PackageSetting ps = (PackageSetting) obj;
3501                return ps.pkgFlags;
3502            }
3503        }
3504        return 0;
3505    }
3506
3507    @Override
3508    public int getPrivateFlagsForUid(int uid) {
3509        synchronized (mPackages) {
3510            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3511            if (obj instanceof SharedUserSetting) {
3512                final SharedUserSetting sus = (SharedUserSetting) obj;
3513                return sus.pkgPrivateFlags;
3514            } else if (obj instanceof PackageSetting) {
3515                final PackageSetting ps = (PackageSetting) obj;
3516                return ps.pkgPrivateFlags;
3517            }
3518        }
3519        return 0;
3520    }
3521
3522    @Override
3523    public boolean isUidPrivileged(int uid) {
3524        uid = UserHandle.getAppId(uid);
3525        // reader
3526        synchronized (mPackages) {
3527            Object obj = mSettings.getUserIdLPr(uid);
3528            if (obj instanceof SharedUserSetting) {
3529                final SharedUserSetting sus = (SharedUserSetting) obj;
3530                final Iterator<PackageSetting> it = sus.packages.iterator();
3531                while (it.hasNext()) {
3532                    if (it.next().isPrivileged()) {
3533                        return true;
3534                    }
3535                }
3536            } else if (obj instanceof PackageSetting) {
3537                final PackageSetting ps = (PackageSetting) obj;
3538                return ps.isPrivileged();
3539            }
3540        }
3541        return false;
3542    }
3543
3544    @Override
3545    public String[] getAppOpPermissionPackages(String permissionName) {
3546        synchronized (mPackages) {
3547            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3548            if (pkgs == null) {
3549                return null;
3550            }
3551            return pkgs.toArray(new String[pkgs.size()]);
3552        }
3553    }
3554
3555    @Override
3556    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3557            int flags, int userId) {
3558        if (!sUserManager.exists(userId)) return null;
3559        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3560        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3561        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3562    }
3563
3564    @Override
3565    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3566            IntentFilter filter, int match, ComponentName activity) {
3567        final int userId = UserHandle.getCallingUserId();
3568        if (DEBUG_PREFERRED) {
3569            Log.v(TAG, "setLastChosenActivity intent=" + intent
3570                + " resolvedType=" + resolvedType
3571                + " flags=" + flags
3572                + " filter=" + filter
3573                + " match=" + match
3574                + " activity=" + activity);
3575            filter.dump(new PrintStreamPrinter(System.out), "    ");
3576        }
3577        intent.setComponent(null);
3578        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3579        // Find any earlier preferred or last chosen entries and nuke them
3580        findPreferredActivity(intent, resolvedType,
3581                flags, query, 0, false, true, false, userId);
3582        // Add the new activity as the last chosen for this filter
3583        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3584                "Setting last chosen");
3585    }
3586
3587    @Override
3588    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3589        final int userId = UserHandle.getCallingUserId();
3590        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3591        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3592        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3593                false, false, false, userId);
3594    }
3595
3596    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3597            int flags, List<ResolveInfo> query, int userId) {
3598        if (query != null) {
3599            final int N = query.size();
3600            if (N == 1) {
3601                return query.get(0);
3602            } else if (N > 1) {
3603                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3604                // If there is more than one activity with the same priority,
3605                // then let the user decide between them.
3606                ResolveInfo r0 = query.get(0);
3607                ResolveInfo r1 = query.get(1);
3608                if (DEBUG_INTENT_MATCHING || debug) {
3609                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3610                            + r1.activityInfo.name + "=" + r1.priority);
3611                }
3612                // If the first activity has a higher priority, or a different
3613                // default, then it is always desireable to pick it.
3614                if (r0.priority != r1.priority
3615                        || r0.preferredOrder != r1.preferredOrder
3616                        || r0.isDefault != r1.isDefault) {
3617                    return query.get(0);
3618                }
3619                // If we have saved a preference for a preferred activity for
3620                // this Intent, use that.
3621                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3622                        flags, query, r0.priority, true, false, debug, userId);
3623                if (ri != null) {
3624                    return ri;
3625                }
3626                if (userId != 0) {
3627                    ri = new ResolveInfo(mResolveInfo);
3628                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3629                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3630                            ri.activityInfo.applicationInfo);
3631                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3632                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3633                    return ri;
3634                }
3635                return mResolveInfo;
3636            }
3637        }
3638        return null;
3639    }
3640
3641    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3642            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3643        final int N = query.size();
3644        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3645                .get(userId);
3646        // Get the list of persistent preferred activities that handle the intent
3647        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3648        List<PersistentPreferredActivity> pprefs = ppir != null
3649                ? ppir.queryIntent(intent, resolvedType,
3650                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3651                : null;
3652        if (pprefs != null && pprefs.size() > 0) {
3653            final int M = pprefs.size();
3654            for (int i=0; i<M; i++) {
3655                final PersistentPreferredActivity ppa = pprefs.get(i);
3656                if (DEBUG_PREFERRED || debug) {
3657                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3658                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3659                            + "\n  component=" + ppa.mComponent);
3660                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3661                }
3662                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3663                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3664                if (DEBUG_PREFERRED || debug) {
3665                    Slog.v(TAG, "Found persistent preferred activity:");
3666                    if (ai != null) {
3667                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3668                    } else {
3669                        Slog.v(TAG, "  null");
3670                    }
3671                }
3672                if (ai == null) {
3673                    // This previously registered persistent preferred activity
3674                    // component is no longer known. Ignore it and do NOT remove it.
3675                    continue;
3676                }
3677                for (int j=0; j<N; j++) {
3678                    final ResolveInfo ri = query.get(j);
3679                    if (!ri.activityInfo.applicationInfo.packageName
3680                            .equals(ai.applicationInfo.packageName)) {
3681                        continue;
3682                    }
3683                    if (!ri.activityInfo.name.equals(ai.name)) {
3684                        continue;
3685                    }
3686                    //  Found a persistent preference that can handle the intent.
3687                    if (DEBUG_PREFERRED || debug) {
3688                        Slog.v(TAG, "Returning persistent preferred activity: " +
3689                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3690                    }
3691                    return ri;
3692                }
3693            }
3694        }
3695        return null;
3696    }
3697
3698    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3699            List<ResolveInfo> query, int priority, boolean always,
3700            boolean removeMatches, boolean debug, int userId) {
3701        if (!sUserManager.exists(userId)) return null;
3702        // writer
3703        synchronized (mPackages) {
3704            if (intent.getSelector() != null) {
3705                intent = intent.getSelector();
3706            }
3707            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3708
3709            // Try to find a matching persistent preferred activity.
3710            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3711                    debug, userId);
3712
3713            // If a persistent preferred activity matched, use it.
3714            if (pri != null) {
3715                return pri;
3716            }
3717
3718            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3719            // Get the list of preferred activities that handle the intent
3720            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3721            List<PreferredActivity> prefs = pir != null
3722                    ? pir.queryIntent(intent, resolvedType,
3723                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3724                    : null;
3725            if (prefs != null && prefs.size() > 0) {
3726                boolean changed = false;
3727                try {
3728                    // First figure out how good the original match set is.
3729                    // We will only allow preferred activities that came
3730                    // from the same match quality.
3731                    int match = 0;
3732
3733                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3734
3735                    final int N = query.size();
3736                    for (int j=0; j<N; j++) {
3737                        final ResolveInfo ri = query.get(j);
3738                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3739                                + ": 0x" + Integer.toHexString(match));
3740                        if (ri.match > match) {
3741                            match = ri.match;
3742                        }
3743                    }
3744
3745                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3746                            + Integer.toHexString(match));
3747
3748                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3749                    final int M = prefs.size();
3750                    for (int i=0; i<M; i++) {
3751                        final PreferredActivity pa = prefs.get(i);
3752                        if (DEBUG_PREFERRED || debug) {
3753                            Slog.v(TAG, "Checking PreferredActivity ds="
3754                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3755                                    + "\n  component=" + pa.mPref.mComponent);
3756                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3757                        }
3758                        if (pa.mPref.mMatch != match) {
3759                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3760                                    + Integer.toHexString(pa.mPref.mMatch));
3761                            continue;
3762                        }
3763                        // If it's not an "always" type preferred activity and that's what we're
3764                        // looking for, skip it.
3765                        if (always && !pa.mPref.mAlways) {
3766                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3767                            continue;
3768                        }
3769                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3770                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3771                        if (DEBUG_PREFERRED || debug) {
3772                            Slog.v(TAG, "Found preferred activity:");
3773                            if (ai != null) {
3774                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3775                            } else {
3776                                Slog.v(TAG, "  null");
3777                            }
3778                        }
3779                        if (ai == null) {
3780                            // This previously registered preferred activity
3781                            // component is no longer known.  Most likely an update
3782                            // to the app was installed and in the new version this
3783                            // component no longer exists.  Clean it up by removing
3784                            // it from the preferred activities list, and skip it.
3785                            Slog.w(TAG, "Removing dangling preferred activity: "
3786                                    + pa.mPref.mComponent);
3787                            pir.removeFilter(pa);
3788                            changed = true;
3789                            continue;
3790                        }
3791                        for (int j=0; j<N; j++) {
3792                            final ResolveInfo ri = query.get(j);
3793                            if (!ri.activityInfo.applicationInfo.packageName
3794                                    .equals(ai.applicationInfo.packageName)) {
3795                                continue;
3796                            }
3797                            if (!ri.activityInfo.name.equals(ai.name)) {
3798                                continue;
3799                            }
3800
3801                            if (removeMatches) {
3802                                pir.removeFilter(pa);
3803                                changed = true;
3804                                if (DEBUG_PREFERRED) {
3805                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3806                                }
3807                                break;
3808                            }
3809
3810                            // Okay we found a previously set preferred or last chosen app.
3811                            // If the result set is different from when this
3812                            // was created, we need to clear it and re-ask the
3813                            // user their preference, if we're looking for an "always" type entry.
3814                            if (always && !pa.mPref.sameSet(query)) {
3815                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3816                                        + intent + " type " + resolvedType);
3817                                if (DEBUG_PREFERRED) {
3818                                    Slog.v(TAG, "Removing preferred activity since set changed "
3819                                            + pa.mPref.mComponent);
3820                                }
3821                                pir.removeFilter(pa);
3822                                // Re-add the filter as a "last chosen" entry (!always)
3823                                PreferredActivity lastChosen = new PreferredActivity(
3824                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3825                                pir.addFilter(lastChosen);
3826                                changed = true;
3827                                return null;
3828                            }
3829
3830                            // Yay! Either the set matched or we're looking for the last chosen
3831                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3832                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3833                            return ri;
3834                        }
3835                    }
3836                } finally {
3837                    if (changed) {
3838                        if (DEBUG_PREFERRED) {
3839                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3840                        }
3841                        scheduleWritePackageRestrictionsLocked(userId);
3842                    }
3843                }
3844            }
3845        }
3846        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3847        return null;
3848    }
3849
3850    /*
3851     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3852     */
3853    @Override
3854    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3855            int targetUserId) {
3856        mContext.enforceCallingOrSelfPermission(
3857                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3858        List<CrossProfileIntentFilter> matches =
3859                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3860        if (matches != null) {
3861            int size = matches.size();
3862            for (int i = 0; i < size; i++) {
3863                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3864            }
3865        }
3866        return false;
3867    }
3868
3869    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3870            String resolvedType, int userId) {
3871        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3872        if (resolver != null) {
3873            return resolver.queryIntent(intent, resolvedType, false, userId);
3874        }
3875        return null;
3876    }
3877
3878    @Override
3879    public List<ResolveInfo> queryIntentActivities(Intent intent,
3880            String resolvedType, int flags, int userId) {
3881        if (!sUserManager.exists(userId)) return Collections.emptyList();
3882        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3883        ComponentName comp = intent.getComponent();
3884        if (comp == null) {
3885            if (intent.getSelector() != null) {
3886                intent = intent.getSelector();
3887                comp = intent.getComponent();
3888            }
3889        }
3890
3891        if (comp != null) {
3892            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3893            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3894            if (ai != null) {
3895                final ResolveInfo ri = new ResolveInfo();
3896                ri.activityInfo = ai;
3897                list.add(ri);
3898            }
3899            return list;
3900        }
3901
3902        // reader
3903        synchronized (mPackages) {
3904            final String pkgName = intent.getPackage();
3905            if (pkgName == null) {
3906                List<CrossProfileIntentFilter> matchingFilters =
3907                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3908                // Check for results that need to skip the current profile.
3909                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3910                        resolvedType, flags, userId);
3911                if (resolveInfo != null) {
3912                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3913                    result.add(resolveInfo);
3914                    return filterIfNotPrimaryUser(result, userId);
3915                }
3916                // Check for cross profile results.
3917                resolveInfo = queryCrossProfileIntents(
3918                        matchingFilters, intent, resolvedType, flags, userId);
3919
3920                // Check for results in the current profile.
3921                List<ResolveInfo> result = mActivities.queryIntent(
3922                        intent, resolvedType, flags, userId);
3923                if (resolveInfo != null) {
3924                    result.add(resolveInfo);
3925                    Collections.sort(result, mResolvePrioritySorter);
3926                }
3927                result = filterIfNotPrimaryUser(result, userId);
3928                if (result.size() > 1 && hasWebURI(intent)) {
3929                    return filterCandidatesWithDomainPreferedActivitiesLPr(result);
3930                }
3931                return result;
3932            }
3933            final PackageParser.Package pkg = mPackages.get(pkgName);
3934            if (pkg != null) {
3935                return filterIfNotPrimaryUser(
3936                        mActivities.queryIntentForPackage(
3937                                intent, resolvedType, flags, pkg.activities, userId),
3938                        userId);
3939            }
3940            return new ArrayList<ResolveInfo>();
3941        }
3942    }
3943
3944    /**
3945     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
3946     *
3947     * @return filtered list
3948     */
3949    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
3950        if (userId == UserHandle.USER_OWNER) {
3951            return resolveInfos;
3952        }
3953        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
3954            ResolveInfo info = resolveInfos.get(i);
3955            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
3956                resolveInfos.remove(i);
3957            }
3958        }
3959        return resolveInfos;
3960    }
3961
3962    private static boolean hasWebURI(Intent intent) {
3963        if (intent.getData() == null) {
3964            return false;
3965        }
3966        final String scheme = intent.getScheme();
3967        if (TextUtils.isEmpty(scheme)) {
3968            return false;
3969        }
3970        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
3971    }
3972
3973    private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr(
3974            List<ResolveInfo> candidates) {
3975        if (DEBUG_PREFERRED) {
3976            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
3977                    candidates.size());
3978        }
3979
3980        final int userId = UserHandle.getCallingUserId();
3981        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
3982        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
3983        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
3984        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
3985
3986        synchronized (mPackages) {
3987            final int count = candidates.size();
3988            // First, try to use the domain prefered App
3989            for (int n=0; n<count; n++) {
3990                ResolveInfo info = candidates.get(n);
3991                String packageName = info.activityInfo.packageName;
3992                PackageSetting ps = mSettings.mPackages.get(packageName);
3993                if (ps != null) {
3994                    // Try to get the status from User settings first
3995                    int status = getDomainVerificationStatusLPr(ps, userId);
3996                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
3997                        result.add(info);
3998                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
3999                        neverList.add(info);
4000                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4001                        undefinedList.add(info);
4002                    }
4003                    // Add to the special match all list (Browser use case)
4004                    if (info.handleAllWebDataURI) {
4005                        matchAllList.add(info);
4006                    }
4007                }
4008            }
4009            // If there is nothing selected, add all candidates and remove the ones that the User
4010            // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and
4011            // also remove any Browser Apps ones.
4012            // If there is still none after this pass, add all undefined one and Browser Apps and
4013            // let the User decide with the Disambiguation dialog if there are several ones.
4014            if (result.size() == 0) {
4015                result.addAll(candidates);
4016            }
4017            result.removeAll(neverList);
4018            result.removeAll(matchAllList);
4019            if (result.size() == 0) {
4020                result.addAll(undefinedList);
4021                result.addAll(matchAllList);
4022            }
4023        }
4024        if (DEBUG_PREFERRED) {
4025            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4026                    result.size());
4027        }
4028        return result;
4029    }
4030
4031    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4032        int status = ps.getDomainVerificationStatusForUser(userId);
4033        // if none available, get the master status
4034        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4035            if (ps.getIntentFilterVerificationInfo() != null) {
4036                status = ps.getIntentFilterVerificationInfo().getStatus();
4037            }
4038        }
4039        return status;
4040    }
4041
4042    private ResolveInfo querySkipCurrentProfileIntents(
4043            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4044            int flags, int sourceUserId) {
4045        if (matchingFilters != null) {
4046            int size = matchingFilters.size();
4047            for (int i = 0; i < size; i ++) {
4048                CrossProfileIntentFilter filter = matchingFilters.get(i);
4049                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4050                    // Checking if there are activities in the target user that can handle the
4051                    // intent.
4052                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4053                            flags, sourceUserId);
4054                    if (resolveInfo != null) {
4055                        return resolveInfo;
4056                    }
4057                }
4058            }
4059        }
4060        return null;
4061    }
4062
4063    // Return matching ResolveInfo if any for skip current profile intent filters.
4064    private ResolveInfo queryCrossProfileIntents(
4065            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4066            int flags, int sourceUserId) {
4067        if (matchingFilters != null) {
4068            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4069            // match the same intent. For performance reasons, it is better not to
4070            // run queryIntent twice for the same userId
4071            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4072            int size = matchingFilters.size();
4073            for (int i = 0; i < size; i++) {
4074                CrossProfileIntentFilter filter = matchingFilters.get(i);
4075                int targetUserId = filter.getTargetUserId();
4076                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4077                        && !alreadyTriedUserIds.get(targetUserId)) {
4078                    // Checking if there are activities in the target user that can handle the
4079                    // intent.
4080                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4081                            flags, sourceUserId);
4082                    if (resolveInfo != null) return resolveInfo;
4083                    alreadyTriedUserIds.put(targetUserId, true);
4084                }
4085            }
4086        }
4087        return null;
4088    }
4089
4090    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4091            String resolvedType, int flags, int sourceUserId) {
4092        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4093                resolvedType, flags, filter.getTargetUserId());
4094        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4095            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4096        }
4097        return null;
4098    }
4099
4100    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4101            int sourceUserId, int targetUserId) {
4102        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4103        String className;
4104        if (targetUserId == UserHandle.USER_OWNER) {
4105            className = FORWARD_INTENT_TO_USER_OWNER;
4106        } else {
4107            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4108        }
4109        ComponentName forwardingActivityComponentName = new ComponentName(
4110                mAndroidApplication.packageName, className);
4111        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4112                sourceUserId);
4113        if (targetUserId == UserHandle.USER_OWNER) {
4114            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4115            forwardingResolveInfo.noResourceId = true;
4116        }
4117        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4118        forwardingResolveInfo.priority = 0;
4119        forwardingResolveInfo.preferredOrder = 0;
4120        forwardingResolveInfo.match = 0;
4121        forwardingResolveInfo.isDefault = true;
4122        forwardingResolveInfo.filter = filter;
4123        forwardingResolveInfo.targetUserId = targetUserId;
4124        return forwardingResolveInfo;
4125    }
4126
4127    @Override
4128    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4129            Intent[] specifics, String[] specificTypes, Intent intent,
4130            String resolvedType, int flags, int userId) {
4131        if (!sUserManager.exists(userId)) return Collections.emptyList();
4132        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4133                false, "query intent activity options");
4134        final String resultsAction = intent.getAction();
4135
4136        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4137                | PackageManager.GET_RESOLVED_FILTER, userId);
4138
4139        if (DEBUG_INTENT_MATCHING) {
4140            Log.v(TAG, "Query " + intent + ": " + results);
4141        }
4142
4143        int specificsPos = 0;
4144        int N;
4145
4146        // todo: note that the algorithm used here is O(N^2).  This
4147        // isn't a problem in our current environment, but if we start running
4148        // into situations where we have more than 5 or 10 matches then this
4149        // should probably be changed to something smarter...
4150
4151        // First we go through and resolve each of the specific items
4152        // that were supplied, taking care of removing any corresponding
4153        // duplicate items in the generic resolve list.
4154        if (specifics != null) {
4155            for (int i=0; i<specifics.length; i++) {
4156                final Intent sintent = specifics[i];
4157                if (sintent == null) {
4158                    continue;
4159                }
4160
4161                if (DEBUG_INTENT_MATCHING) {
4162                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4163                }
4164
4165                String action = sintent.getAction();
4166                if (resultsAction != null && resultsAction.equals(action)) {
4167                    // If this action was explicitly requested, then don't
4168                    // remove things that have it.
4169                    action = null;
4170                }
4171
4172                ResolveInfo ri = null;
4173                ActivityInfo ai = null;
4174
4175                ComponentName comp = sintent.getComponent();
4176                if (comp == null) {
4177                    ri = resolveIntent(
4178                        sintent,
4179                        specificTypes != null ? specificTypes[i] : null,
4180                            flags, userId);
4181                    if (ri == null) {
4182                        continue;
4183                    }
4184                    if (ri == mResolveInfo) {
4185                        // ACK!  Must do something better with this.
4186                    }
4187                    ai = ri.activityInfo;
4188                    comp = new ComponentName(ai.applicationInfo.packageName,
4189                            ai.name);
4190                } else {
4191                    ai = getActivityInfo(comp, flags, userId);
4192                    if (ai == null) {
4193                        continue;
4194                    }
4195                }
4196
4197                // Look for any generic query activities that are duplicates
4198                // of this specific one, and remove them from the results.
4199                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4200                N = results.size();
4201                int j;
4202                for (j=specificsPos; j<N; j++) {
4203                    ResolveInfo sri = results.get(j);
4204                    if ((sri.activityInfo.name.equals(comp.getClassName())
4205                            && sri.activityInfo.applicationInfo.packageName.equals(
4206                                    comp.getPackageName()))
4207                        || (action != null && sri.filter.matchAction(action))) {
4208                        results.remove(j);
4209                        if (DEBUG_INTENT_MATCHING) Log.v(
4210                            TAG, "Removing duplicate item from " + j
4211                            + " due to specific " + specificsPos);
4212                        if (ri == null) {
4213                            ri = sri;
4214                        }
4215                        j--;
4216                        N--;
4217                    }
4218                }
4219
4220                // Add this specific item to its proper place.
4221                if (ri == null) {
4222                    ri = new ResolveInfo();
4223                    ri.activityInfo = ai;
4224                }
4225                results.add(specificsPos, ri);
4226                ri.specificIndex = i;
4227                specificsPos++;
4228            }
4229        }
4230
4231        // Now we go through the remaining generic results and remove any
4232        // duplicate actions that are found here.
4233        N = results.size();
4234        for (int i=specificsPos; i<N-1; i++) {
4235            final ResolveInfo rii = results.get(i);
4236            if (rii.filter == null) {
4237                continue;
4238            }
4239
4240            // Iterate over all of the actions of this result's intent
4241            // filter...  typically this should be just one.
4242            final Iterator<String> it = rii.filter.actionsIterator();
4243            if (it == null) {
4244                continue;
4245            }
4246            while (it.hasNext()) {
4247                final String action = it.next();
4248                if (resultsAction != null && resultsAction.equals(action)) {
4249                    // If this action was explicitly requested, then don't
4250                    // remove things that have it.
4251                    continue;
4252                }
4253                for (int j=i+1; j<N; j++) {
4254                    final ResolveInfo rij = results.get(j);
4255                    if (rij.filter != null && rij.filter.hasAction(action)) {
4256                        results.remove(j);
4257                        if (DEBUG_INTENT_MATCHING) Log.v(
4258                            TAG, "Removing duplicate item from " + j
4259                            + " due to action " + action + " at " + i);
4260                        j--;
4261                        N--;
4262                    }
4263                }
4264            }
4265
4266            // If the caller didn't request filter information, drop it now
4267            // so we don't have to marshall/unmarshall it.
4268            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4269                rii.filter = null;
4270            }
4271        }
4272
4273        // Filter out the caller activity if so requested.
4274        if (caller != null) {
4275            N = results.size();
4276            for (int i=0; i<N; i++) {
4277                ActivityInfo ainfo = results.get(i).activityInfo;
4278                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4279                        && caller.getClassName().equals(ainfo.name)) {
4280                    results.remove(i);
4281                    break;
4282                }
4283            }
4284        }
4285
4286        // If the caller didn't request filter information,
4287        // drop them now so we don't have to
4288        // marshall/unmarshall it.
4289        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4290            N = results.size();
4291            for (int i=0; i<N; i++) {
4292                results.get(i).filter = null;
4293            }
4294        }
4295
4296        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4297        return results;
4298    }
4299
4300    @Override
4301    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4302            int userId) {
4303        if (!sUserManager.exists(userId)) return Collections.emptyList();
4304        ComponentName comp = intent.getComponent();
4305        if (comp == null) {
4306            if (intent.getSelector() != null) {
4307                intent = intent.getSelector();
4308                comp = intent.getComponent();
4309            }
4310        }
4311        if (comp != null) {
4312            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4313            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4314            if (ai != null) {
4315                ResolveInfo ri = new ResolveInfo();
4316                ri.activityInfo = ai;
4317                list.add(ri);
4318            }
4319            return list;
4320        }
4321
4322        // reader
4323        synchronized (mPackages) {
4324            String pkgName = intent.getPackage();
4325            if (pkgName == null) {
4326                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4327            }
4328            final PackageParser.Package pkg = mPackages.get(pkgName);
4329            if (pkg != null) {
4330                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4331                        userId);
4332            }
4333            return null;
4334        }
4335    }
4336
4337    @Override
4338    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4339        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4340        if (!sUserManager.exists(userId)) return null;
4341        if (query != null) {
4342            if (query.size() >= 1) {
4343                // If there is more than one service with the same priority,
4344                // just arbitrarily pick the first one.
4345                return query.get(0);
4346            }
4347        }
4348        return null;
4349    }
4350
4351    @Override
4352    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4353            int userId) {
4354        if (!sUserManager.exists(userId)) return Collections.emptyList();
4355        ComponentName comp = intent.getComponent();
4356        if (comp == null) {
4357            if (intent.getSelector() != null) {
4358                intent = intent.getSelector();
4359                comp = intent.getComponent();
4360            }
4361        }
4362        if (comp != null) {
4363            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4364            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4365            if (si != null) {
4366                final ResolveInfo ri = new ResolveInfo();
4367                ri.serviceInfo = si;
4368                list.add(ri);
4369            }
4370            return list;
4371        }
4372
4373        // reader
4374        synchronized (mPackages) {
4375            String pkgName = intent.getPackage();
4376            if (pkgName == null) {
4377                return mServices.queryIntent(intent, resolvedType, flags, userId);
4378            }
4379            final PackageParser.Package pkg = mPackages.get(pkgName);
4380            if (pkg != null) {
4381                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4382                        userId);
4383            }
4384            return null;
4385        }
4386    }
4387
4388    @Override
4389    public List<ResolveInfo> queryIntentContentProviders(
4390            Intent intent, String resolvedType, int flags, int userId) {
4391        if (!sUserManager.exists(userId)) return Collections.emptyList();
4392        ComponentName comp = intent.getComponent();
4393        if (comp == null) {
4394            if (intent.getSelector() != null) {
4395                intent = intent.getSelector();
4396                comp = intent.getComponent();
4397            }
4398        }
4399        if (comp != null) {
4400            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4401            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4402            if (pi != null) {
4403                final ResolveInfo ri = new ResolveInfo();
4404                ri.providerInfo = pi;
4405                list.add(ri);
4406            }
4407            return list;
4408        }
4409
4410        // reader
4411        synchronized (mPackages) {
4412            String pkgName = intent.getPackage();
4413            if (pkgName == null) {
4414                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4415            }
4416            final PackageParser.Package pkg = mPackages.get(pkgName);
4417            if (pkg != null) {
4418                return mProviders.queryIntentForPackage(
4419                        intent, resolvedType, flags, pkg.providers, userId);
4420            }
4421            return null;
4422        }
4423    }
4424
4425    @Override
4426    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4427        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4428
4429        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4430
4431        // writer
4432        synchronized (mPackages) {
4433            ArrayList<PackageInfo> list;
4434            if (listUninstalled) {
4435                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4436                for (PackageSetting ps : mSettings.mPackages.values()) {
4437                    PackageInfo pi;
4438                    if (ps.pkg != null) {
4439                        pi = generatePackageInfo(ps.pkg, flags, userId);
4440                    } else {
4441                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4442                    }
4443                    if (pi != null) {
4444                        list.add(pi);
4445                    }
4446                }
4447            } else {
4448                list = new ArrayList<PackageInfo>(mPackages.size());
4449                for (PackageParser.Package p : mPackages.values()) {
4450                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4451                    if (pi != null) {
4452                        list.add(pi);
4453                    }
4454                }
4455            }
4456
4457            return new ParceledListSlice<PackageInfo>(list);
4458        }
4459    }
4460
4461    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4462            String[] permissions, boolean[] tmp, int flags, int userId) {
4463        int numMatch = 0;
4464        final PermissionsState permissionsState = ps.getPermissionsState();
4465        for (int i=0; i<permissions.length; i++) {
4466            final String permission = permissions[i];
4467            if (permissionsState.hasPermission(permission, userId)) {
4468                tmp[i] = true;
4469                numMatch++;
4470            } else {
4471                tmp[i] = false;
4472            }
4473        }
4474        if (numMatch == 0) {
4475            return;
4476        }
4477        PackageInfo pi;
4478        if (ps.pkg != null) {
4479            pi = generatePackageInfo(ps.pkg, flags, userId);
4480        } else {
4481            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4482        }
4483        // The above might return null in cases of uninstalled apps or install-state
4484        // skew across users/profiles.
4485        if (pi != null) {
4486            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4487                if (numMatch == permissions.length) {
4488                    pi.requestedPermissions = permissions;
4489                } else {
4490                    pi.requestedPermissions = new String[numMatch];
4491                    numMatch = 0;
4492                    for (int i=0; i<permissions.length; i++) {
4493                        if (tmp[i]) {
4494                            pi.requestedPermissions[numMatch] = permissions[i];
4495                            numMatch++;
4496                        }
4497                    }
4498                }
4499            }
4500            list.add(pi);
4501        }
4502    }
4503
4504    @Override
4505    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4506            String[] permissions, int flags, int userId) {
4507        if (!sUserManager.exists(userId)) return null;
4508        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4509
4510        // writer
4511        synchronized (mPackages) {
4512            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4513            boolean[] tmpBools = new boolean[permissions.length];
4514            if (listUninstalled) {
4515                for (PackageSetting ps : mSettings.mPackages.values()) {
4516                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4517                }
4518            } else {
4519                for (PackageParser.Package pkg : mPackages.values()) {
4520                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4521                    if (ps != null) {
4522                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4523                                userId);
4524                    }
4525                }
4526            }
4527
4528            return new ParceledListSlice<PackageInfo>(list);
4529        }
4530    }
4531
4532    @Override
4533    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4534        if (!sUserManager.exists(userId)) return null;
4535        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4536
4537        // writer
4538        synchronized (mPackages) {
4539            ArrayList<ApplicationInfo> list;
4540            if (listUninstalled) {
4541                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4542                for (PackageSetting ps : mSettings.mPackages.values()) {
4543                    ApplicationInfo ai;
4544                    if (ps.pkg != null) {
4545                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4546                                ps.readUserState(userId), userId);
4547                    } else {
4548                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4549                    }
4550                    if (ai != null) {
4551                        list.add(ai);
4552                    }
4553                }
4554            } else {
4555                list = new ArrayList<ApplicationInfo>(mPackages.size());
4556                for (PackageParser.Package p : mPackages.values()) {
4557                    if (p.mExtras != null) {
4558                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4559                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4560                        if (ai != null) {
4561                            list.add(ai);
4562                        }
4563                    }
4564                }
4565            }
4566
4567            return new ParceledListSlice<ApplicationInfo>(list);
4568        }
4569    }
4570
4571    public List<ApplicationInfo> getPersistentApplications(int flags) {
4572        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4573
4574        // reader
4575        synchronized (mPackages) {
4576            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4577            final int userId = UserHandle.getCallingUserId();
4578            while (i.hasNext()) {
4579                final PackageParser.Package p = i.next();
4580                if (p.applicationInfo != null
4581                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4582                        && (!mSafeMode || isSystemApp(p))) {
4583                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4584                    if (ps != null) {
4585                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4586                                ps.readUserState(userId), userId);
4587                        if (ai != null) {
4588                            finalList.add(ai);
4589                        }
4590                    }
4591                }
4592            }
4593        }
4594
4595        return finalList;
4596    }
4597
4598    @Override
4599    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4600        if (!sUserManager.exists(userId)) return null;
4601        // reader
4602        synchronized (mPackages) {
4603            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4604            PackageSetting ps = provider != null
4605                    ? mSettings.mPackages.get(provider.owner.packageName)
4606                    : null;
4607            return ps != null
4608                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4609                    && (!mSafeMode || (provider.info.applicationInfo.flags
4610                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4611                    ? PackageParser.generateProviderInfo(provider, flags,
4612                            ps.readUserState(userId), userId)
4613                    : null;
4614        }
4615    }
4616
4617    /**
4618     * @deprecated
4619     */
4620    @Deprecated
4621    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4622        // reader
4623        synchronized (mPackages) {
4624            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4625                    .entrySet().iterator();
4626            final int userId = UserHandle.getCallingUserId();
4627            while (i.hasNext()) {
4628                Map.Entry<String, PackageParser.Provider> entry = i.next();
4629                PackageParser.Provider p = entry.getValue();
4630                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4631
4632                if (ps != null && p.syncable
4633                        && (!mSafeMode || (p.info.applicationInfo.flags
4634                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4635                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4636                            ps.readUserState(userId), userId);
4637                    if (info != null) {
4638                        outNames.add(entry.getKey());
4639                        outInfo.add(info);
4640                    }
4641                }
4642            }
4643        }
4644    }
4645
4646    @Override
4647    public List<ProviderInfo> queryContentProviders(String processName,
4648            int uid, int flags) {
4649        ArrayList<ProviderInfo> finalList = null;
4650        // reader
4651        synchronized (mPackages) {
4652            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4653            final int userId = processName != null ?
4654                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4655            while (i.hasNext()) {
4656                final PackageParser.Provider p = i.next();
4657                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4658                if (ps != null && p.info.authority != null
4659                        && (processName == null
4660                                || (p.info.processName.equals(processName)
4661                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4662                        && mSettings.isEnabledLPr(p.info, flags, userId)
4663                        && (!mSafeMode
4664                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4665                    if (finalList == null) {
4666                        finalList = new ArrayList<ProviderInfo>(3);
4667                    }
4668                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4669                            ps.readUserState(userId), userId);
4670                    if (info != null) {
4671                        finalList.add(info);
4672                    }
4673                }
4674            }
4675        }
4676
4677        if (finalList != null) {
4678            Collections.sort(finalList, mProviderInitOrderSorter);
4679        }
4680
4681        return finalList;
4682    }
4683
4684    @Override
4685    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4686            int flags) {
4687        // reader
4688        synchronized (mPackages) {
4689            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4690            return PackageParser.generateInstrumentationInfo(i, flags);
4691        }
4692    }
4693
4694    @Override
4695    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4696            int flags) {
4697        ArrayList<InstrumentationInfo> finalList =
4698            new ArrayList<InstrumentationInfo>();
4699
4700        // reader
4701        synchronized (mPackages) {
4702            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4703            while (i.hasNext()) {
4704                final PackageParser.Instrumentation p = i.next();
4705                if (targetPackage == null
4706                        || targetPackage.equals(p.info.targetPackage)) {
4707                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4708                            flags);
4709                    if (ii != null) {
4710                        finalList.add(ii);
4711                    }
4712                }
4713            }
4714        }
4715
4716        return finalList;
4717    }
4718
4719    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4720        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4721        if (overlays == null) {
4722            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4723            return;
4724        }
4725        for (PackageParser.Package opkg : overlays.values()) {
4726            // Not much to do if idmap fails: we already logged the error
4727            // and we certainly don't want to abort installation of pkg simply
4728            // because an overlay didn't fit properly. For these reasons,
4729            // ignore the return value of createIdmapForPackagePairLI.
4730            createIdmapForPackagePairLI(pkg, opkg);
4731        }
4732    }
4733
4734    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4735            PackageParser.Package opkg) {
4736        if (!opkg.mTrustedOverlay) {
4737            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4738                    opkg.baseCodePath + ": overlay not trusted");
4739            return false;
4740        }
4741        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4742        if (overlaySet == null) {
4743            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4744                    opkg.baseCodePath + " but target package has no known overlays");
4745            return false;
4746        }
4747        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4748        // TODO: generate idmap for split APKs
4749        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4750            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4751                    + opkg.baseCodePath);
4752            return false;
4753        }
4754        PackageParser.Package[] overlayArray =
4755            overlaySet.values().toArray(new PackageParser.Package[0]);
4756        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4757            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4758                return p1.mOverlayPriority - p2.mOverlayPriority;
4759            }
4760        };
4761        Arrays.sort(overlayArray, cmp);
4762
4763        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4764        int i = 0;
4765        for (PackageParser.Package p : overlayArray) {
4766            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4767        }
4768        return true;
4769    }
4770
4771    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4772        final File[] files = dir.listFiles();
4773        if (ArrayUtils.isEmpty(files)) {
4774            Log.d(TAG, "No files in app dir " + dir);
4775            return;
4776        }
4777
4778        if (DEBUG_PACKAGE_SCANNING) {
4779            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4780                    + " flags=0x" + Integer.toHexString(parseFlags));
4781        }
4782
4783        for (File file : files) {
4784            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4785                    && !PackageInstallerService.isStageName(file.getName());
4786            if (!isPackage) {
4787                // Ignore entries which are not packages
4788                continue;
4789            }
4790            try {
4791                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4792                        scanFlags, currentTime, null);
4793            } catch (PackageManagerException e) {
4794                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4795
4796                // Delete invalid userdata apps
4797                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4798                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4799                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4800                    if (file.isDirectory()) {
4801                        mInstaller.rmPackageDir(file.getAbsolutePath());
4802                    } else {
4803                        file.delete();
4804                    }
4805                }
4806            }
4807        }
4808    }
4809
4810    private static File getSettingsProblemFile() {
4811        File dataDir = Environment.getDataDirectory();
4812        File systemDir = new File(dataDir, "system");
4813        File fname = new File(systemDir, "uiderrors.txt");
4814        return fname;
4815    }
4816
4817    static void reportSettingsProblem(int priority, String msg) {
4818        logCriticalInfo(priority, msg);
4819    }
4820
4821    static void logCriticalInfo(int priority, String msg) {
4822        Slog.println(priority, TAG, msg);
4823        EventLogTags.writePmCriticalInfo(msg);
4824        try {
4825            File fname = getSettingsProblemFile();
4826            FileOutputStream out = new FileOutputStream(fname, true);
4827            PrintWriter pw = new FastPrintWriter(out);
4828            SimpleDateFormat formatter = new SimpleDateFormat();
4829            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4830            pw.println(dateString + ": " + msg);
4831            pw.close();
4832            FileUtils.setPermissions(
4833                    fname.toString(),
4834                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4835                    -1, -1);
4836        } catch (java.io.IOException e) {
4837        }
4838    }
4839
4840    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4841            PackageParser.Package pkg, File srcFile, int parseFlags)
4842            throws PackageManagerException {
4843        if (ps != null
4844                && ps.codePath.equals(srcFile)
4845                && ps.timeStamp == srcFile.lastModified()
4846                && !isCompatSignatureUpdateNeeded(pkg)
4847                && !isRecoverSignatureUpdateNeeded(pkg)) {
4848            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4849            if (ps.signatures.mSignatures != null
4850                    && ps.signatures.mSignatures.length != 0
4851                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4852                // Optimization: reuse the existing cached certificates
4853                // if the package appears to be unchanged.
4854                pkg.mSignatures = ps.signatures.mSignatures;
4855                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4856                synchronized (mPackages) {
4857                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4858                }
4859                return;
4860            }
4861
4862            Slog.w(TAG, "PackageSetting for " + ps.name
4863                    + " is missing signatures.  Collecting certs again to recover them.");
4864        } else {
4865            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4866        }
4867
4868        try {
4869            pp.collectCertificates(pkg, parseFlags);
4870            pp.collectManifestDigest(pkg);
4871        } catch (PackageParserException e) {
4872            throw PackageManagerException.from(e);
4873        }
4874    }
4875
4876    /*
4877     *  Scan a package and return the newly parsed package.
4878     *  Returns null in case of errors and the error code is stored in mLastScanError
4879     */
4880    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4881            long currentTime, UserHandle user) throws PackageManagerException {
4882        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4883        parseFlags |= mDefParseFlags;
4884        PackageParser pp = new PackageParser();
4885        pp.setSeparateProcesses(mSeparateProcesses);
4886        pp.setOnlyCoreApps(mOnlyCore);
4887        pp.setDisplayMetrics(mMetrics);
4888
4889        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4890            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4891        }
4892
4893        final PackageParser.Package pkg;
4894        try {
4895            pkg = pp.parsePackage(scanFile, parseFlags);
4896        } catch (PackageParserException e) {
4897            throw PackageManagerException.from(e);
4898        }
4899
4900        PackageSetting ps = null;
4901        PackageSetting updatedPkg;
4902        // reader
4903        synchronized (mPackages) {
4904            // Look to see if we already know about this package.
4905            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4906            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4907                // This package has been renamed to its original name.  Let's
4908                // use that.
4909                ps = mSettings.peekPackageLPr(oldName);
4910            }
4911            // If there was no original package, see one for the real package name.
4912            if (ps == null) {
4913                ps = mSettings.peekPackageLPr(pkg.packageName);
4914            }
4915            // Check to see if this package could be hiding/updating a system
4916            // package.  Must look for it either under the original or real
4917            // package name depending on our state.
4918            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4919            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4920        }
4921        boolean updatedPkgBetter = false;
4922        // First check if this is a system package that may involve an update
4923        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4924            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
4925            // it needs to drop FLAG_PRIVILEGED.
4926            if (locationIsPrivileged(scanFile)) {
4927                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4928            } else {
4929                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4930            }
4931
4932            if (ps != null && !ps.codePath.equals(scanFile)) {
4933                // The path has changed from what was last scanned...  check the
4934                // version of the new path against what we have stored to determine
4935                // what to do.
4936                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4937                if (pkg.mVersionCode <= ps.versionCode) {
4938                    // The system package has been updated and the code path does not match
4939                    // Ignore entry. Skip it.
4940                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
4941                            + " ignored: updated version " + ps.versionCode
4942                            + " better than this " + pkg.mVersionCode);
4943                    if (!updatedPkg.codePath.equals(scanFile)) {
4944                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4945                                + ps.name + " changing from " + updatedPkg.codePathString
4946                                + " to " + scanFile);
4947                        updatedPkg.codePath = scanFile;
4948                        updatedPkg.codePathString = scanFile.toString();
4949                        updatedPkg.resourcePath = scanFile;
4950                        updatedPkg.resourcePathString = scanFile.toString();
4951                    }
4952                    updatedPkg.pkg = pkg;
4953                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4954                } else {
4955                    // The current app on the system partition is better than
4956                    // what we have updated to on the data partition; switch
4957                    // back to the system partition version.
4958                    // At this point, its safely assumed that package installation for
4959                    // apps in system partition will go through. If not there won't be a working
4960                    // version of the app
4961                    // writer
4962                    synchronized (mPackages) {
4963                        // Just remove the loaded entries from package lists.
4964                        mPackages.remove(ps.name);
4965                    }
4966
4967                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4968                            + " reverting from " + ps.codePathString
4969                            + ": new version " + pkg.mVersionCode
4970                            + " better than installed " + ps.versionCode);
4971
4972                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4973                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4974                            getAppDexInstructionSets(ps));
4975                    synchronized (mInstallLock) {
4976                        args.cleanUpResourcesLI();
4977                    }
4978                    synchronized (mPackages) {
4979                        mSettings.enableSystemPackageLPw(ps.name);
4980                    }
4981                    updatedPkgBetter = true;
4982                }
4983            }
4984        }
4985
4986        if (updatedPkg != null) {
4987            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4988            // initially
4989            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4990
4991            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4992            // flag set initially
4993            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
4994                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4995            }
4996        }
4997
4998        // Verify certificates against what was last scanned
4999        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5000
5001        /*
5002         * A new system app appeared, but we already had a non-system one of the
5003         * same name installed earlier.
5004         */
5005        boolean shouldHideSystemApp = false;
5006        if (updatedPkg == null && ps != null
5007                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5008            /*
5009             * Check to make sure the signatures match first. If they don't,
5010             * wipe the installed application and its data.
5011             */
5012            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5013                    != PackageManager.SIGNATURE_MATCH) {
5014                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5015                        + " signatures don't match existing userdata copy; removing");
5016                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5017                ps = null;
5018            } else {
5019                /*
5020                 * If the newly-added system app is an older version than the
5021                 * already installed version, hide it. It will be scanned later
5022                 * and re-added like an update.
5023                 */
5024                if (pkg.mVersionCode <= ps.versionCode) {
5025                    shouldHideSystemApp = true;
5026                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5027                            + " but new version " + pkg.mVersionCode + " better than installed "
5028                            + ps.versionCode + "; hiding system");
5029                } else {
5030                    /*
5031                     * The newly found system app is a newer version that the
5032                     * one previously installed. Simply remove the
5033                     * already-installed application and replace it with our own
5034                     * while keeping the application data.
5035                     */
5036                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5037                            + " reverting from " + ps.codePathString + ": new version "
5038                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5039                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5040                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
5041                            getAppDexInstructionSets(ps));
5042                    synchronized (mInstallLock) {
5043                        args.cleanUpResourcesLI();
5044                    }
5045                }
5046            }
5047        }
5048
5049        // The apk is forward locked (not public) if its code and resources
5050        // are kept in different files. (except for app in either system or
5051        // vendor path).
5052        // TODO grab this value from PackageSettings
5053        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5054            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5055                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5056            }
5057        }
5058
5059        // TODO: extend to support forward-locked splits
5060        String resourcePath = null;
5061        String baseResourcePath = null;
5062        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5063            if (ps != null && ps.resourcePathString != null) {
5064                resourcePath = ps.resourcePathString;
5065                baseResourcePath = ps.resourcePathString;
5066            } else {
5067                // Should not happen at all. Just log an error.
5068                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5069            }
5070        } else {
5071            resourcePath = pkg.codePath;
5072            baseResourcePath = pkg.baseCodePath;
5073        }
5074
5075        // Set application objects path explicitly.
5076        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5077        pkg.applicationInfo.setCodePath(pkg.codePath);
5078        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5079        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5080        pkg.applicationInfo.setResourcePath(resourcePath);
5081        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5082        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5083
5084        // Note that we invoke the following method only if we are about to unpack an application
5085        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5086                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5087
5088        /*
5089         * If the system app should be overridden by a previously installed
5090         * data, hide the system app now and let the /data/app scan pick it up
5091         * again.
5092         */
5093        if (shouldHideSystemApp) {
5094            synchronized (mPackages) {
5095                /*
5096                 * We have to grant systems permissions before we hide, because
5097                 * grantPermissions will assume the package update is trying to
5098                 * expand its permissions.
5099                 */
5100                grantPermissionsLPw(pkg, true, pkg.packageName);
5101                mSettings.disableSystemPackageLPw(pkg.packageName);
5102            }
5103        }
5104
5105        return scannedPkg;
5106    }
5107
5108    private static String fixProcessName(String defProcessName,
5109            String processName, int uid) {
5110        if (processName == null) {
5111            return defProcessName;
5112        }
5113        return processName;
5114    }
5115
5116    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5117            throws PackageManagerException {
5118        if (pkgSetting.signatures.mSignatures != null) {
5119            // Already existing package. Make sure signatures match
5120            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5121                    == PackageManager.SIGNATURE_MATCH;
5122            if (!match) {
5123                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5124                        == PackageManager.SIGNATURE_MATCH;
5125            }
5126            if (!match) {
5127                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5128                        == PackageManager.SIGNATURE_MATCH;
5129            }
5130            if (!match) {
5131                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5132                        + pkg.packageName + " signatures do not match the "
5133                        + "previously installed version; ignoring!");
5134            }
5135        }
5136
5137        // Check for shared user signatures
5138        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5139            // Already existing package. Make sure signatures match
5140            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5141                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5142            if (!match) {
5143                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5144                        == PackageManager.SIGNATURE_MATCH;
5145            }
5146            if (!match) {
5147                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5148                        == PackageManager.SIGNATURE_MATCH;
5149            }
5150            if (!match) {
5151                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5152                        "Package " + pkg.packageName
5153                        + " has no signatures that match those in shared user "
5154                        + pkgSetting.sharedUser.name + "; ignoring!");
5155            }
5156        }
5157    }
5158
5159    /**
5160     * Enforces that only the system UID or root's UID can call a method exposed
5161     * via Binder.
5162     *
5163     * @param message used as message if SecurityException is thrown
5164     * @throws SecurityException if the caller is not system or root
5165     */
5166    private static final void enforceSystemOrRoot(String message) {
5167        final int uid = Binder.getCallingUid();
5168        if (uid != Process.SYSTEM_UID && uid != 0) {
5169            throw new SecurityException(message);
5170        }
5171    }
5172
5173    @Override
5174    public void performBootDexOpt() {
5175        enforceSystemOrRoot("Only the system can request dexopt be performed");
5176
5177        // Before everything else, see whether we need to fstrim.
5178        try {
5179            IMountService ms = PackageHelper.getMountService();
5180            if (ms != null) {
5181                final boolean isUpgrade = isUpgrade();
5182                boolean doTrim = isUpgrade;
5183                if (doTrim) {
5184                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5185                } else {
5186                    final long interval = android.provider.Settings.Global.getLong(
5187                            mContext.getContentResolver(),
5188                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5189                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5190                    if (interval > 0) {
5191                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5192                        if (timeSinceLast > interval) {
5193                            doTrim = true;
5194                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5195                                    + "; running immediately");
5196                        }
5197                    }
5198                }
5199                if (doTrim) {
5200                    if (!isFirstBoot()) {
5201                        try {
5202                            ActivityManagerNative.getDefault().showBootMessage(
5203                                    mContext.getResources().getString(
5204                                            R.string.android_upgrading_fstrim), true);
5205                        } catch (RemoteException e) {
5206                        }
5207                    }
5208                    ms.runMaintenance();
5209                }
5210            } else {
5211                Slog.e(TAG, "Mount service unavailable!");
5212            }
5213        } catch (RemoteException e) {
5214            // Can't happen; MountService is local
5215        }
5216
5217        final ArraySet<PackageParser.Package> pkgs;
5218        synchronized (mPackages) {
5219            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5220        }
5221
5222        if (pkgs != null) {
5223            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5224            // in case the device runs out of space.
5225            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5226            // Give priority to core apps.
5227            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5228                PackageParser.Package pkg = it.next();
5229                if (pkg.coreApp) {
5230                    if (DEBUG_DEXOPT) {
5231                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5232                    }
5233                    sortedPkgs.add(pkg);
5234                    it.remove();
5235                }
5236            }
5237            // Give priority to system apps that listen for pre boot complete.
5238            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5239            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5240            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5241                PackageParser.Package pkg = it.next();
5242                if (pkgNames.contains(pkg.packageName)) {
5243                    if (DEBUG_DEXOPT) {
5244                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5245                    }
5246                    sortedPkgs.add(pkg);
5247                    it.remove();
5248                }
5249            }
5250            // Give priority to system apps.
5251            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5252                PackageParser.Package pkg = it.next();
5253                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5254                    if (DEBUG_DEXOPT) {
5255                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5256                    }
5257                    sortedPkgs.add(pkg);
5258                    it.remove();
5259                }
5260            }
5261            // Give priority to updated system apps.
5262            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5263                PackageParser.Package pkg = it.next();
5264                if (pkg.isUpdatedSystemApp()) {
5265                    if (DEBUG_DEXOPT) {
5266                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5267                    }
5268                    sortedPkgs.add(pkg);
5269                    it.remove();
5270                }
5271            }
5272            // Give priority to apps that listen for boot complete.
5273            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5274            pkgNames = getPackageNamesForIntent(intent);
5275            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5276                PackageParser.Package pkg = it.next();
5277                if (pkgNames.contains(pkg.packageName)) {
5278                    if (DEBUG_DEXOPT) {
5279                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5280                    }
5281                    sortedPkgs.add(pkg);
5282                    it.remove();
5283                }
5284            }
5285            // Filter out packages that aren't recently used.
5286            filterRecentlyUsedApps(pkgs);
5287            // Add all remaining apps.
5288            for (PackageParser.Package pkg : pkgs) {
5289                if (DEBUG_DEXOPT) {
5290                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5291                }
5292                sortedPkgs.add(pkg);
5293            }
5294
5295            // If we want to be lazy, filter everything that wasn't recently used.
5296            if (mLazyDexOpt) {
5297                filterRecentlyUsedApps(sortedPkgs);
5298            }
5299
5300            int i = 0;
5301            int total = sortedPkgs.size();
5302            File dataDir = Environment.getDataDirectory();
5303            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5304            if (lowThreshold == 0) {
5305                throw new IllegalStateException("Invalid low memory threshold");
5306            }
5307            for (PackageParser.Package pkg : sortedPkgs) {
5308                long usableSpace = dataDir.getUsableSpace();
5309                if (usableSpace < lowThreshold) {
5310                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5311                    break;
5312                }
5313                performBootDexOpt(pkg, ++i, total);
5314            }
5315        }
5316    }
5317
5318    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5319        // Filter out packages that aren't recently used.
5320        //
5321        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5322        // should do a full dexopt.
5323        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5324            int total = pkgs.size();
5325            int skipped = 0;
5326            long now = System.currentTimeMillis();
5327            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5328                PackageParser.Package pkg = i.next();
5329                long then = pkg.mLastPackageUsageTimeInMills;
5330                if (then + mDexOptLRUThresholdInMills < now) {
5331                    if (DEBUG_DEXOPT) {
5332                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5333                              ((then == 0) ? "never" : new Date(then)));
5334                    }
5335                    i.remove();
5336                    skipped++;
5337                }
5338            }
5339            if (DEBUG_DEXOPT) {
5340                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5341            }
5342        }
5343    }
5344
5345    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5346        List<ResolveInfo> ris = null;
5347        try {
5348            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5349                    intent, null, 0, UserHandle.USER_OWNER);
5350        } catch (RemoteException e) {
5351        }
5352        ArraySet<String> pkgNames = new ArraySet<String>();
5353        if (ris != null) {
5354            for (ResolveInfo ri : ris) {
5355                pkgNames.add(ri.activityInfo.packageName);
5356            }
5357        }
5358        return pkgNames;
5359    }
5360
5361    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5362        if (DEBUG_DEXOPT) {
5363            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5364        }
5365        if (!isFirstBoot()) {
5366            try {
5367                ActivityManagerNative.getDefault().showBootMessage(
5368                        mContext.getResources().getString(R.string.android_upgrading_apk,
5369                                curr, total), true);
5370            } catch (RemoteException e) {
5371            }
5372        }
5373        PackageParser.Package p = pkg;
5374        synchronized (mInstallLock) {
5375            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5376                    false /* force dex */, false /* defer */, true /* include dependencies */);
5377        }
5378    }
5379
5380    @Override
5381    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5382        return performDexOpt(packageName, instructionSet, false);
5383    }
5384
5385    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5386        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5387        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5388        if (!dexopt && !updateUsage) {
5389            // We aren't going to dexopt or update usage, so bail early.
5390            return false;
5391        }
5392        PackageParser.Package p;
5393        final String targetInstructionSet;
5394        synchronized (mPackages) {
5395            p = mPackages.get(packageName);
5396            if (p == null) {
5397                return false;
5398            }
5399            if (updateUsage) {
5400                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5401            }
5402            mPackageUsage.write(false);
5403            if (!dexopt) {
5404                // We aren't going to dexopt, so bail early.
5405                return false;
5406            }
5407
5408            targetInstructionSet = instructionSet != null ? instructionSet :
5409                    getPrimaryInstructionSet(p.applicationInfo);
5410            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5411                return false;
5412            }
5413        }
5414
5415        synchronized (mInstallLock) {
5416            final String[] instructionSets = new String[] { targetInstructionSet };
5417            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5418                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5419            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5420        }
5421    }
5422
5423    public ArraySet<String> getPackagesThatNeedDexOpt() {
5424        ArraySet<String> pkgs = null;
5425        synchronized (mPackages) {
5426            for (PackageParser.Package p : mPackages.values()) {
5427                if (DEBUG_DEXOPT) {
5428                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5429                }
5430                if (!p.mDexOptPerformed.isEmpty()) {
5431                    continue;
5432                }
5433                if (pkgs == null) {
5434                    pkgs = new ArraySet<String>();
5435                }
5436                pkgs.add(p.packageName);
5437            }
5438        }
5439        return pkgs;
5440    }
5441
5442    public void shutdown() {
5443        mPackageUsage.write(true);
5444    }
5445
5446    @Override
5447    public void forceDexOpt(String packageName) {
5448        enforceSystemOrRoot("forceDexOpt");
5449
5450        PackageParser.Package pkg;
5451        synchronized (mPackages) {
5452            pkg = mPackages.get(packageName);
5453            if (pkg == null) {
5454                throw new IllegalArgumentException("Missing package: " + packageName);
5455            }
5456        }
5457
5458        synchronized (mInstallLock) {
5459            final String[] instructionSets = new String[] {
5460                    getPrimaryInstructionSet(pkg.applicationInfo) };
5461            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5462                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5463            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5464                throw new IllegalStateException("Failed to dexopt: " + res);
5465            }
5466        }
5467    }
5468
5469    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5470        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5471            Slog.w(TAG, "Unable to update from " + oldPkg.name
5472                    + " to " + newPkg.packageName
5473                    + ": old package not in system partition");
5474            return false;
5475        } else if (mPackages.get(oldPkg.name) != null) {
5476            Slog.w(TAG, "Unable to update from " + oldPkg.name
5477                    + " to " + newPkg.packageName
5478                    + ": old package still exists");
5479            return false;
5480        }
5481        return true;
5482    }
5483
5484    private int createDataDirsLI(String packageName, int uid, String seinfo) {
5485        int[] users = sUserManager.getUserIds();
5486        int res = mInstaller.install(packageName, uid, uid, seinfo);
5487        if (res < 0) {
5488            return res;
5489        }
5490        for (int user : users) {
5491            if (user != 0) {
5492                res = mInstaller.createUserData(packageName,
5493                        UserHandle.getUid(user, uid), user, seinfo);
5494                if (res < 0) {
5495                    return res;
5496                }
5497            }
5498        }
5499        return res;
5500    }
5501
5502    private int removeDataDirsLI(String packageName) {
5503        int[] users = sUserManager.getUserIds();
5504        int res = 0;
5505        for (int user : users) {
5506            int resInner = mInstaller.remove(packageName, user);
5507            if (resInner < 0) {
5508                res = resInner;
5509            }
5510        }
5511
5512        return res;
5513    }
5514
5515    private int deleteCodeCacheDirsLI(String packageName) {
5516        int[] users = sUserManager.getUserIds();
5517        int res = 0;
5518        for (int user : users) {
5519            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
5520            if (resInner < 0) {
5521                res = resInner;
5522            }
5523        }
5524        return res;
5525    }
5526
5527    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5528            PackageParser.Package changingLib) {
5529        if (file.path != null) {
5530            usesLibraryFiles.add(file.path);
5531            return;
5532        }
5533        PackageParser.Package p = mPackages.get(file.apk);
5534        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5535            // If we are doing this while in the middle of updating a library apk,
5536            // then we need to make sure to use that new apk for determining the
5537            // dependencies here.  (We haven't yet finished committing the new apk
5538            // to the package manager state.)
5539            if (p == null || p.packageName.equals(changingLib.packageName)) {
5540                p = changingLib;
5541            }
5542        }
5543        if (p != null) {
5544            usesLibraryFiles.addAll(p.getAllCodePaths());
5545        }
5546    }
5547
5548    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5549            PackageParser.Package changingLib) throws PackageManagerException {
5550        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5551            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5552            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5553            for (int i=0; i<N; i++) {
5554                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5555                if (file == null) {
5556                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5557                            "Package " + pkg.packageName + " requires unavailable shared library "
5558                            + pkg.usesLibraries.get(i) + "; failing!");
5559                }
5560                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5561            }
5562            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5563            for (int i=0; i<N; i++) {
5564                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5565                if (file == null) {
5566                    Slog.w(TAG, "Package " + pkg.packageName
5567                            + " desires unavailable shared library "
5568                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5569                } else {
5570                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5571                }
5572            }
5573            N = usesLibraryFiles.size();
5574            if (N > 0) {
5575                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5576            } else {
5577                pkg.usesLibraryFiles = null;
5578            }
5579        }
5580    }
5581
5582    private static boolean hasString(List<String> list, List<String> which) {
5583        if (list == null) {
5584            return false;
5585        }
5586        for (int i=list.size()-1; i>=0; i--) {
5587            for (int j=which.size()-1; j>=0; j--) {
5588                if (which.get(j).equals(list.get(i))) {
5589                    return true;
5590                }
5591            }
5592        }
5593        return false;
5594    }
5595
5596    private void updateAllSharedLibrariesLPw() {
5597        for (PackageParser.Package pkg : mPackages.values()) {
5598            try {
5599                updateSharedLibrariesLPw(pkg, null);
5600            } catch (PackageManagerException e) {
5601                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5602            }
5603        }
5604    }
5605
5606    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5607            PackageParser.Package changingPkg) {
5608        ArrayList<PackageParser.Package> res = null;
5609        for (PackageParser.Package pkg : mPackages.values()) {
5610            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5611                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5612                if (res == null) {
5613                    res = new ArrayList<PackageParser.Package>();
5614                }
5615                res.add(pkg);
5616                try {
5617                    updateSharedLibrariesLPw(pkg, changingPkg);
5618                } catch (PackageManagerException e) {
5619                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5620                }
5621            }
5622        }
5623        return res;
5624    }
5625
5626    /**
5627     * Derive the value of the {@code cpuAbiOverride} based on the provided
5628     * value and an optional stored value from the package settings.
5629     */
5630    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5631        String cpuAbiOverride = null;
5632
5633        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5634            cpuAbiOverride = null;
5635        } else if (abiOverride != null) {
5636            cpuAbiOverride = abiOverride;
5637        } else if (settings != null) {
5638            cpuAbiOverride = settings.cpuAbiOverrideString;
5639        }
5640
5641        return cpuAbiOverride;
5642    }
5643
5644    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5645            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5646        boolean success = false;
5647        try {
5648            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5649                    currentTime, user);
5650            success = true;
5651            return res;
5652        } finally {
5653            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5654                removeDataDirsLI(pkg.packageName);
5655            }
5656        }
5657    }
5658
5659    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5660            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5661        final File scanFile = new File(pkg.codePath);
5662        if (pkg.applicationInfo.getCodePath() == null ||
5663                pkg.applicationInfo.getResourcePath() == null) {
5664            // Bail out. The resource and code paths haven't been set.
5665            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5666                    "Code and resource paths haven't been set correctly");
5667        }
5668
5669        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5670            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5671        } else {
5672            // Only allow system apps to be flagged as core apps.
5673            pkg.coreApp = false;
5674        }
5675
5676        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5677            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5678        }
5679
5680        if (mCustomResolverComponentName != null &&
5681                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5682            setUpCustomResolverActivity(pkg);
5683        }
5684
5685        if (pkg.packageName.equals("android")) {
5686            synchronized (mPackages) {
5687                if (mAndroidApplication != null) {
5688                    Slog.w(TAG, "*************************************************");
5689                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5690                    Slog.w(TAG, " file=" + scanFile);
5691                    Slog.w(TAG, "*************************************************");
5692                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5693                            "Core android package being redefined.  Skipping.");
5694                }
5695
5696                // Set up information for our fall-back user intent resolution activity.
5697                mPlatformPackage = pkg;
5698                pkg.mVersionCode = mSdkVersion;
5699                mAndroidApplication = pkg.applicationInfo;
5700
5701                if (!mResolverReplaced) {
5702                    mResolveActivity.applicationInfo = mAndroidApplication;
5703                    mResolveActivity.name = ResolverActivity.class.getName();
5704                    mResolveActivity.packageName = mAndroidApplication.packageName;
5705                    mResolveActivity.processName = "system:ui";
5706                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5707                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5708                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5709                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5710                    mResolveActivity.exported = true;
5711                    mResolveActivity.enabled = true;
5712                    mResolveInfo.activityInfo = mResolveActivity;
5713                    mResolveInfo.priority = 0;
5714                    mResolveInfo.preferredOrder = 0;
5715                    mResolveInfo.match = 0;
5716                    mResolveComponentName = new ComponentName(
5717                            mAndroidApplication.packageName, mResolveActivity.name);
5718                }
5719            }
5720        }
5721
5722        if (DEBUG_PACKAGE_SCANNING) {
5723            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5724                Log.d(TAG, "Scanning package " + pkg.packageName);
5725        }
5726
5727        if (mPackages.containsKey(pkg.packageName)
5728                || mSharedLibraries.containsKey(pkg.packageName)) {
5729            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5730                    "Application package " + pkg.packageName
5731                    + " already installed.  Skipping duplicate.");
5732        }
5733
5734        // If we're only installing presumed-existing packages, require that the
5735        // scanned APK is both already known and at the path previously established
5736        // for it.  Previously unknown packages we pick up normally, but if we have an
5737        // a priori expectation about this package's install presence, enforce it.
5738        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
5739            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
5740            if (known != null) {
5741                if (DEBUG_PACKAGE_SCANNING) {
5742                    Log.d(TAG, "Examining " + pkg.codePath
5743                            + " and requiring known paths " + known.codePathString
5744                            + " & " + known.resourcePathString);
5745                }
5746                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
5747                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
5748                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
5749                            "Application package " + pkg.packageName
5750                            + " found at " + pkg.applicationInfo.getCodePath()
5751                            + " but expected at " + known.codePathString + "; ignoring.");
5752                }
5753            }
5754        }
5755
5756        // Initialize package source and resource directories
5757        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5758        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5759
5760        SharedUserSetting suid = null;
5761        PackageSetting pkgSetting = null;
5762
5763        if (!isSystemApp(pkg)) {
5764            // Only system apps can use these features.
5765            pkg.mOriginalPackages = null;
5766            pkg.mRealPackage = null;
5767            pkg.mAdoptPermissions = null;
5768        }
5769
5770        // writer
5771        synchronized (mPackages) {
5772            if (pkg.mSharedUserId != null) {
5773                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5774                if (suid == null) {
5775                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5776                            "Creating application package " + pkg.packageName
5777                            + " for shared user failed");
5778                }
5779                if (DEBUG_PACKAGE_SCANNING) {
5780                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5781                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5782                                + "): packages=" + suid.packages);
5783                }
5784            }
5785
5786            // Check if we are renaming from an original package name.
5787            PackageSetting origPackage = null;
5788            String realName = null;
5789            if (pkg.mOriginalPackages != null) {
5790                // This package may need to be renamed to a previously
5791                // installed name.  Let's check on that...
5792                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5793                if (pkg.mOriginalPackages.contains(renamed)) {
5794                    // This package had originally been installed as the
5795                    // original name, and we have already taken care of
5796                    // transitioning to the new one.  Just update the new
5797                    // one to continue using the old name.
5798                    realName = pkg.mRealPackage;
5799                    if (!pkg.packageName.equals(renamed)) {
5800                        // Callers into this function may have already taken
5801                        // care of renaming the package; only do it here if
5802                        // it is not already done.
5803                        pkg.setPackageName(renamed);
5804                    }
5805
5806                } else {
5807                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5808                        if ((origPackage = mSettings.peekPackageLPr(
5809                                pkg.mOriginalPackages.get(i))) != null) {
5810                            // We do have the package already installed under its
5811                            // original name...  should we use it?
5812                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5813                                // New package is not compatible with original.
5814                                origPackage = null;
5815                                continue;
5816                            } else if (origPackage.sharedUser != null) {
5817                                // Make sure uid is compatible between packages.
5818                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5819                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5820                                            + " to " + pkg.packageName + ": old uid "
5821                                            + origPackage.sharedUser.name
5822                                            + " differs from " + pkg.mSharedUserId);
5823                                    origPackage = null;
5824                                    continue;
5825                                }
5826                            } else {
5827                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5828                                        + pkg.packageName + " to old name " + origPackage.name);
5829                            }
5830                            break;
5831                        }
5832                    }
5833                }
5834            }
5835
5836            if (mTransferedPackages.contains(pkg.packageName)) {
5837                Slog.w(TAG, "Package " + pkg.packageName
5838                        + " was transferred to another, but its .apk remains");
5839            }
5840
5841            // Just create the setting, don't add it yet. For already existing packages
5842            // the PkgSetting exists already and doesn't have to be created.
5843            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5844                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5845                    pkg.applicationInfo.primaryCpuAbi,
5846                    pkg.applicationInfo.secondaryCpuAbi,
5847                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
5848                    user, false);
5849            if (pkgSetting == null) {
5850                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5851                        "Creating application package " + pkg.packageName + " failed");
5852            }
5853
5854            if (pkgSetting.origPackage != null) {
5855                // If we are first transitioning from an original package,
5856                // fix up the new package's name now.  We need to do this after
5857                // looking up the package under its new name, so getPackageLP
5858                // can take care of fiddling things correctly.
5859                pkg.setPackageName(origPackage.name);
5860
5861                // File a report about this.
5862                String msg = "New package " + pkgSetting.realName
5863                        + " renamed to replace old package " + pkgSetting.name;
5864                reportSettingsProblem(Log.WARN, msg);
5865
5866                // Make a note of it.
5867                mTransferedPackages.add(origPackage.name);
5868
5869                // No longer need to retain this.
5870                pkgSetting.origPackage = null;
5871            }
5872
5873            if (realName != null) {
5874                // Make a note of it.
5875                mTransferedPackages.add(pkg.packageName);
5876            }
5877
5878            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5879                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5880            }
5881
5882            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5883                // Check all shared libraries and map to their actual file path.
5884                // We only do this here for apps not on a system dir, because those
5885                // are the only ones that can fail an install due to this.  We
5886                // will take care of the system apps by updating all of their
5887                // library paths after the scan is done.
5888                updateSharedLibrariesLPw(pkg, null);
5889            }
5890
5891            if (mFoundPolicyFile) {
5892                SELinuxMMAC.assignSeinfoValue(pkg);
5893            }
5894
5895            pkg.applicationInfo.uid = pkgSetting.appId;
5896            pkg.mExtras = pkgSetting;
5897            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5898                try {
5899                    verifySignaturesLP(pkgSetting, pkg);
5900                    // We just determined the app is signed correctly, so bring
5901                    // over the latest parsed certs.
5902                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5903                } catch (PackageManagerException e) {
5904                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5905                        throw e;
5906                    }
5907                    // The signature has changed, but this package is in the system
5908                    // image...  let's recover!
5909                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5910                    // However...  if this package is part of a shared user, but it
5911                    // doesn't match the signature of the shared user, let's fail.
5912                    // What this means is that you can't change the signatures
5913                    // associated with an overall shared user, which doesn't seem all
5914                    // that unreasonable.
5915                    if (pkgSetting.sharedUser != null) {
5916                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5917                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5918                            throw new PackageManagerException(
5919                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5920                                            "Signature mismatch for shared user : "
5921                                            + pkgSetting.sharedUser);
5922                        }
5923                    }
5924                    // File a report about this.
5925                    String msg = "System package " + pkg.packageName
5926                        + " signature changed; retaining data.";
5927                    reportSettingsProblem(Log.WARN, msg);
5928                }
5929            } else {
5930                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5931                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5932                            + pkg.packageName + " upgrade keys do not match the "
5933                            + "previously installed version");
5934                } else {
5935                    // We just determined the app is signed correctly, so bring
5936                    // over the latest parsed certs.
5937                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5938                }
5939            }
5940            // Verify that this new package doesn't have any content providers
5941            // that conflict with existing packages.  Only do this if the
5942            // package isn't already installed, since we don't want to break
5943            // things that are installed.
5944            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5945                final int N = pkg.providers.size();
5946                int i;
5947                for (i=0; i<N; i++) {
5948                    PackageParser.Provider p = pkg.providers.get(i);
5949                    if (p.info.authority != null) {
5950                        String names[] = p.info.authority.split(";");
5951                        for (int j = 0; j < names.length; j++) {
5952                            if (mProvidersByAuthority.containsKey(names[j])) {
5953                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5954                                final String otherPackageName =
5955                                        ((other != null && other.getComponentName() != null) ?
5956                                                other.getComponentName().getPackageName() : "?");
5957                                throw new PackageManagerException(
5958                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5959                                                "Can't install because provider name " + names[j]
5960                                                + " (in package " + pkg.applicationInfo.packageName
5961                                                + ") is already used by " + otherPackageName);
5962                            }
5963                        }
5964                    }
5965                }
5966            }
5967
5968            if (pkg.mAdoptPermissions != null) {
5969                // This package wants to adopt ownership of permissions from
5970                // another package.
5971                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5972                    final String origName = pkg.mAdoptPermissions.get(i);
5973                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5974                    if (orig != null) {
5975                        if (verifyPackageUpdateLPr(orig, pkg)) {
5976                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5977                                    + pkg.packageName);
5978                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5979                        }
5980                    }
5981                }
5982            }
5983        }
5984
5985        final String pkgName = pkg.packageName;
5986
5987        final long scanFileTime = scanFile.lastModified();
5988        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5989        pkg.applicationInfo.processName = fixProcessName(
5990                pkg.applicationInfo.packageName,
5991                pkg.applicationInfo.processName,
5992                pkg.applicationInfo.uid);
5993
5994        File dataPath;
5995        if (mPlatformPackage == pkg) {
5996            // The system package is special.
5997            dataPath = new File(Environment.getDataDirectory(), "system");
5998
5999            pkg.applicationInfo.dataDir = dataPath.getPath();
6000
6001        } else {
6002            // This is a normal package, need to make its data directory.
6003            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6004                    UserHandle.USER_OWNER);
6005
6006            boolean uidError = false;
6007            if (dataPath.exists()) {
6008                int currentUid = 0;
6009                try {
6010                    StructStat stat = Os.stat(dataPath.getPath());
6011                    currentUid = stat.st_uid;
6012                } catch (ErrnoException e) {
6013                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6014                }
6015
6016                // If we have mismatched owners for the data path, we have a problem.
6017                if (currentUid != pkg.applicationInfo.uid) {
6018                    boolean recovered = false;
6019                    if (currentUid == 0) {
6020                        // The directory somehow became owned by root.  Wow.
6021                        // This is probably because the system was stopped while
6022                        // installd was in the middle of messing with its libs
6023                        // directory.  Ask installd to fix that.
6024                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
6025                                pkg.applicationInfo.uid);
6026                        if (ret >= 0) {
6027                            recovered = true;
6028                            String msg = "Package " + pkg.packageName
6029                                    + " unexpectedly changed to uid 0; recovered to " +
6030                                    + pkg.applicationInfo.uid;
6031                            reportSettingsProblem(Log.WARN, msg);
6032                        }
6033                    }
6034                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6035                            || (scanFlags&SCAN_BOOTING) != 0)) {
6036                        // If this is a system app, we can at least delete its
6037                        // current data so the application will still work.
6038                        int ret = removeDataDirsLI(pkgName);
6039                        if (ret >= 0) {
6040                            // TODO: Kill the processes first
6041                            // Old data gone!
6042                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6043                                    ? "System package " : "Third party package ";
6044                            String msg = prefix + pkg.packageName
6045                                    + " has changed from uid: "
6046                                    + currentUid + " to "
6047                                    + pkg.applicationInfo.uid + "; old data erased";
6048                            reportSettingsProblem(Log.WARN, msg);
6049                            recovered = true;
6050
6051                            // And now re-install the app.
6052                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
6053                                                   pkg.applicationInfo.seinfo);
6054                            if (ret == -1) {
6055                                // Ack should not happen!
6056                                msg = prefix + pkg.packageName
6057                                        + " could not have data directory re-created after delete.";
6058                                reportSettingsProblem(Log.WARN, msg);
6059                                throw new PackageManagerException(
6060                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6061                            }
6062                        }
6063                        if (!recovered) {
6064                            mHasSystemUidErrors = true;
6065                        }
6066                    } else if (!recovered) {
6067                        // If we allow this install to proceed, we will be broken.
6068                        // Abort, abort!
6069                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6070                                "scanPackageLI");
6071                    }
6072                    if (!recovered) {
6073                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6074                            + pkg.applicationInfo.uid + "/fs_"
6075                            + currentUid;
6076                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6077                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6078                        String msg = "Package " + pkg.packageName
6079                                + " has mismatched uid: "
6080                                + currentUid + " on disk, "
6081                                + pkg.applicationInfo.uid + " in settings";
6082                        // writer
6083                        synchronized (mPackages) {
6084                            mSettings.mReadMessages.append(msg);
6085                            mSettings.mReadMessages.append('\n');
6086                            uidError = true;
6087                            if (!pkgSetting.uidError) {
6088                                reportSettingsProblem(Log.ERROR, msg);
6089                            }
6090                        }
6091                    }
6092                }
6093                pkg.applicationInfo.dataDir = dataPath.getPath();
6094                if (mShouldRestoreconData) {
6095                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6096                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
6097                                pkg.applicationInfo.uid);
6098                }
6099            } else {
6100                if (DEBUG_PACKAGE_SCANNING) {
6101                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6102                        Log.v(TAG, "Want this data dir: " + dataPath);
6103                }
6104                //invoke installer to do the actual installation
6105                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
6106                                           pkg.applicationInfo.seinfo);
6107                if (ret < 0) {
6108                    // Error from installer
6109                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6110                            "Unable to create data dirs [errorCode=" + ret + "]");
6111                }
6112
6113                if (dataPath.exists()) {
6114                    pkg.applicationInfo.dataDir = dataPath.getPath();
6115                } else {
6116                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6117                    pkg.applicationInfo.dataDir = null;
6118                }
6119            }
6120
6121            pkgSetting.uidError = uidError;
6122        }
6123
6124        final String path = scanFile.getPath();
6125        final String codePath = pkg.applicationInfo.getCodePath();
6126        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6127        if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6128            setBundledAppAbisAndRoots(pkg, pkgSetting);
6129
6130            // If we haven't found any native libraries for the app, check if it has
6131            // renderscript code. We'll need to force the app to 32 bit if it has
6132            // renderscript bitcode.
6133            if (pkg.applicationInfo.primaryCpuAbi == null
6134                    && pkg.applicationInfo.secondaryCpuAbi == null
6135                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
6136                NativeLibraryHelper.Handle handle = null;
6137                try {
6138                    handle = NativeLibraryHelper.Handle.create(scanFile);
6139                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6140                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6141                    }
6142                } catch (IOException ioe) {
6143                    Slog.w(TAG, "Error scanning system app : " + ioe);
6144                } finally {
6145                    IoUtils.closeQuietly(handle);
6146                }
6147            }
6148
6149            setNativeLibraryPaths(pkg);
6150        } else {
6151            // TODO: We can probably be smarter about this stuff. For installed apps,
6152            // we can calculate this information at install time once and for all. For
6153            // system apps, we can probably assume that this information doesn't change
6154            // after the first boot scan. As things stand, we do lots of unnecessary work.
6155
6156            // Give ourselves some initial paths; we'll come back for another
6157            // pass once we've determined ABI below.
6158            setNativeLibraryPaths(pkg);
6159
6160            final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg);
6161            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6162            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6163
6164            NativeLibraryHelper.Handle handle = null;
6165            try {
6166                handle = NativeLibraryHelper.Handle.create(scanFile);
6167                // TODO(multiArch): This can be null for apps that didn't go through the
6168                // usual installation process. We can calculate it again, like we
6169                // do during install time.
6170                //
6171                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6172                // unnecessary.
6173                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6174
6175                // Null out the abis so that they can be recalculated.
6176                pkg.applicationInfo.primaryCpuAbi = null;
6177                pkg.applicationInfo.secondaryCpuAbi = null;
6178                if (isMultiArch(pkg.applicationInfo)) {
6179                    // Warn if we've set an abiOverride for multi-lib packages..
6180                    // By definition, we need to copy both 32 and 64 bit libraries for
6181                    // such packages.
6182                    if (pkg.cpuAbiOverride != null
6183                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
6184                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
6185                    }
6186
6187                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
6188                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
6189                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
6190                        if (isAsec) {
6191                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
6192                        } else {
6193                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6194                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
6195                                    useIsaSpecificSubdirs);
6196                        }
6197                    }
6198
6199                    maybeThrowExceptionForMultiArchCopy(
6200                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
6201
6202                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
6203                        if (isAsec) {
6204                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
6205                        } else {
6206                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6207                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
6208                                    useIsaSpecificSubdirs);
6209                        }
6210                    }
6211
6212                    maybeThrowExceptionForMultiArchCopy(
6213                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
6214
6215                    if (abi64 >= 0) {
6216                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
6217                    }
6218
6219                    if (abi32 >= 0) {
6220                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
6221                        if (abi64 >= 0) {
6222                            pkg.applicationInfo.secondaryCpuAbi = abi;
6223                        } else {
6224                            pkg.applicationInfo.primaryCpuAbi = abi;
6225                        }
6226                    }
6227                } else {
6228                    String[] abiList = (cpuAbiOverride != null) ?
6229                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
6230
6231                    // Enable gross and lame hacks for apps that are built with old
6232                    // SDK tools. We must scan their APKs for renderscript bitcode and
6233                    // not launch them if it's present. Don't bother checking on devices
6234                    // that don't have 64 bit support.
6235                    boolean needsRenderScriptOverride = false;
6236                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
6237                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6238                        abiList = Build.SUPPORTED_32_BIT_ABIS;
6239                        needsRenderScriptOverride = true;
6240                    }
6241
6242                    final int copyRet;
6243                    if (isAsec) {
6244                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6245                    } else {
6246                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6247                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
6248                    }
6249
6250                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
6251                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6252                                "Error unpackaging native libs for app, errorCode=" + copyRet);
6253                    }
6254
6255                    if (copyRet >= 0) {
6256                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
6257                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
6258                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
6259                    } else if (needsRenderScriptOverride) {
6260                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
6261                    }
6262                }
6263            } catch (IOException ioe) {
6264                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
6265            } finally {
6266                IoUtils.closeQuietly(handle);
6267            }
6268
6269            // Now that we've calculated the ABIs and determined if it's an internal app,
6270            // we will go ahead and populate the nativeLibraryPath.
6271            setNativeLibraryPaths(pkg);
6272
6273            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6274            final int[] userIds = sUserManager.getUserIds();
6275            synchronized (mInstallLock) {
6276                // Create a native library symlink only if we have native libraries
6277                // and if the native libraries are 32 bit libraries. We do not provide
6278                // this symlink for 64 bit libraries.
6279                if (pkg.applicationInfo.primaryCpuAbi != null &&
6280                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6281                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6282                    for (int userId : userIds) {
6283                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6284                                nativeLibPath, userId) < 0) {
6285                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6286                                    "Failed linking native library dir (user=" + userId + ")");
6287                        }
6288                    }
6289                }
6290            }
6291        }
6292
6293        // This is a special case for the "system" package, where the ABI is
6294        // dictated by the zygote configuration (and init.rc). We should keep track
6295        // of this ABI so that we can deal with "normal" applications that run under
6296        // the same UID correctly.
6297        if (mPlatformPackage == pkg) {
6298            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6299                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6300        }
6301
6302        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6303        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6304        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6305        // Copy the derived override back to the parsed package, so that we can
6306        // update the package settings accordingly.
6307        pkg.cpuAbiOverride = cpuAbiOverride;
6308
6309        if (DEBUG_ABI_SELECTION) {
6310            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6311                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6312                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6313        }
6314
6315        // Push the derived path down into PackageSettings so we know what to
6316        // clean up at uninstall time.
6317        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6318
6319        if (DEBUG_ABI_SELECTION) {
6320            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6321                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6322                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6323        }
6324
6325        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6326            // We don't do this here during boot because we can do it all
6327            // at once after scanning all existing packages.
6328            //
6329            // We also do this *before* we perform dexopt on this package, so that
6330            // we can avoid redundant dexopts, and also to make sure we've got the
6331            // code and package path correct.
6332            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6333                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6334        }
6335
6336        if ((scanFlags & SCAN_NO_DEX) == 0) {
6337            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6338                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6339            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6340                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6341            }
6342        }
6343        if (mFactoryTest && pkg.requestedPermissions.contains(
6344                android.Manifest.permission.FACTORY_TEST)) {
6345            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6346        }
6347
6348        ArrayList<PackageParser.Package> clientLibPkgs = null;
6349
6350        // writer
6351        synchronized (mPackages) {
6352            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6353                // Only system apps can add new shared libraries.
6354                if (pkg.libraryNames != null) {
6355                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6356                        String name = pkg.libraryNames.get(i);
6357                        boolean allowed = false;
6358                        if (pkg.isUpdatedSystemApp()) {
6359                            // New library entries can only be added through the
6360                            // system image.  This is important to get rid of a lot
6361                            // of nasty edge cases: for example if we allowed a non-
6362                            // system update of the app to add a library, then uninstalling
6363                            // the update would make the library go away, and assumptions
6364                            // we made such as through app install filtering would now
6365                            // have allowed apps on the device which aren't compatible
6366                            // with it.  Better to just have the restriction here, be
6367                            // conservative, and create many fewer cases that can negatively
6368                            // impact the user experience.
6369                            final PackageSetting sysPs = mSettings
6370                                    .getDisabledSystemPkgLPr(pkg.packageName);
6371                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6372                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6373                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6374                                        allowed = true;
6375                                        allowed = true;
6376                                        break;
6377                                    }
6378                                }
6379                            }
6380                        } else {
6381                            allowed = true;
6382                        }
6383                        if (allowed) {
6384                            if (!mSharedLibraries.containsKey(name)) {
6385                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6386                            } else if (!name.equals(pkg.packageName)) {
6387                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6388                                        + name + " already exists; skipping");
6389                            }
6390                        } else {
6391                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6392                                    + name + " that is not declared on system image; skipping");
6393                        }
6394                    }
6395                    if ((scanFlags&SCAN_BOOTING) == 0) {
6396                        // If we are not booting, we need to update any applications
6397                        // that are clients of our shared library.  If we are booting,
6398                        // this will all be done once the scan is complete.
6399                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6400                    }
6401                }
6402            }
6403        }
6404
6405        // We also need to dexopt any apps that are dependent on this library.  Note that
6406        // if these fail, we should abort the install since installing the library will
6407        // result in some apps being broken.
6408        if (clientLibPkgs != null) {
6409            if ((scanFlags & SCAN_NO_DEX) == 0) {
6410                for (int i = 0; i < clientLibPkgs.size(); i++) {
6411                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6412                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6413                            null /* instruction sets */, forceDex,
6414                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6415                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6416                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6417                                "scanPackageLI failed to dexopt clientLibPkgs");
6418                    }
6419                }
6420            }
6421        }
6422
6423        // Request the ActivityManager to kill the process(only for existing packages)
6424        // so that we do not end up in a confused state while the user is still using the older
6425        // version of the application while the new one gets installed.
6426        if ((scanFlags & SCAN_REPLACING) != 0) {
6427            killApplication(pkg.applicationInfo.packageName,
6428                        pkg.applicationInfo.uid, "update pkg");
6429        }
6430
6431        // Also need to kill any apps that are dependent on the library.
6432        if (clientLibPkgs != null) {
6433            for (int i=0; i<clientLibPkgs.size(); i++) {
6434                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6435                killApplication(clientPkg.applicationInfo.packageName,
6436                        clientPkg.applicationInfo.uid, "update lib");
6437            }
6438        }
6439
6440        // writer
6441        synchronized (mPackages) {
6442            // We don't expect installation to fail beyond this point
6443
6444            // Add the new setting to mSettings
6445            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6446            // Add the new setting to mPackages
6447            mPackages.put(pkg.applicationInfo.packageName, pkg);
6448            // Make sure we don't accidentally delete its data.
6449            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6450            while (iter.hasNext()) {
6451                PackageCleanItem item = iter.next();
6452                if (pkgName.equals(item.packageName)) {
6453                    iter.remove();
6454                }
6455            }
6456
6457            // Take care of first install / last update times.
6458            if (currentTime != 0) {
6459                if (pkgSetting.firstInstallTime == 0) {
6460                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6461                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6462                    pkgSetting.lastUpdateTime = currentTime;
6463                }
6464            } else if (pkgSetting.firstInstallTime == 0) {
6465                // We need *something*.  Take time time stamp of the file.
6466                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6467            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6468                if (scanFileTime != pkgSetting.timeStamp) {
6469                    // A package on the system image has changed; consider this
6470                    // to be an update.
6471                    pkgSetting.lastUpdateTime = scanFileTime;
6472                }
6473            }
6474
6475            // Add the package's KeySets to the global KeySetManagerService
6476            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6477            try {
6478                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6479                if (pkg.mKeySetMapping != null) {
6480                    ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping);
6481                    if (pkg.mUpgradeKeySets != null) {
6482                        ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets);
6483                    }
6484                }
6485            } catch (NullPointerException e) {
6486                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6487            } catch (IllegalArgumentException e) {
6488                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6489            }
6490
6491            int N = pkg.providers.size();
6492            StringBuilder r = null;
6493            int i;
6494            for (i=0; i<N; i++) {
6495                PackageParser.Provider p = pkg.providers.get(i);
6496                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6497                        p.info.processName, pkg.applicationInfo.uid);
6498                mProviders.addProvider(p);
6499                p.syncable = p.info.isSyncable;
6500                if (p.info.authority != null) {
6501                    String names[] = p.info.authority.split(";");
6502                    p.info.authority = null;
6503                    for (int j = 0; j < names.length; j++) {
6504                        if (j == 1 && p.syncable) {
6505                            // We only want the first authority for a provider to possibly be
6506                            // syncable, so if we already added this provider using a different
6507                            // authority clear the syncable flag. We copy the provider before
6508                            // changing it because the mProviders object contains a reference
6509                            // to a provider that we don't want to change.
6510                            // Only do this for the second authority since the resulting provider
6511                            // object can be the same for all future authorities for this provider.
6512                            p = new PackageParser.Provider(p);
6513                            p.syncable = false;
6514                        }
6515                        if (!mProvidersByAuthority.containsKey(names[j])) {
6516                            mProvidersByAuthority.put(names[j], p);
6517                            if (p.info.authority == null) {
6518                                p.info.authority = names[j];
6519                            } else {
6520                                p.info.authority = p.info.authority + ";" + names[j];
6521                            }
6522                            if (DEBUG_PACKAGE_SCANNING) {
6523                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6524                                    Log.d(TAG, "Registered content provider: " + names[j]
6525                                            + ", className = " + p.info.name + ", isSyncable = "
6526                                            + p.info.isSyncable);
6527                            }
6528                        } else {
6529                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6530                            Slog.w(TAG, "Skipping provider name " + names[j] +
6531                                    " (in package " + pkg.applicationInfo.packageName +
6532                                    "): name already used by "
6533                                    + ((other != null && other.getComponentName() != null)
6534                                            ? other.getComponentName().getPackageName() : "?"));
6535                        }
6536                    }
6537                }
6538                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6539                    if (r == null) {
6540                        r = new StringBuilder(256);
6541                    } else {
6542                        r.append(' ');
6543                    }
6544                    r.append(p.info.name);
6545                }
6546            }
6547            if (r != null) {
6548                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6549            }
6550
6551            N = pkg.services.size();
6552            r = null;
6553            for (i=0; i<N; i++) {
6554                PackageParser.Service s = pkg.services.get(i);
6555                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6556                        s.info.processName, pkg.applicationInfo.uid);
6557                mServices.addService(s);
6558                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6559                    if (r == null) {
6560                        r = new StringBuilder(256);
6561                    } else {
6562                        r.append(' ');
6563                    }
6564                    r.append(s.info.name);
6565                }
6566            }
6567            if (r != null) {
6568                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6569            }
6570
6571            N = pkg.receivers.size();
6572            r = null;
6573            for (i=0; i<N; i++) {
6574                PackageParser.Activity a = pkg.receivers.get(i);
6575                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6576                        a.info.processName, pkg.applicationInfo.uid);
6577                mReceivers.addActivity(a, "receiver");
6578                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6579                    if (r == null) {
6580                        r = new StringBuilder(256);
6581                    } else {
6582                        r.append(' ');
6583                    }
6584                    r.append(a.info.name);
6585                }
6586            }
6587            if (r != null) {
6588                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6589            }
6590
6591            N = pkg.activities.size();
6592            r = null;
6593            for (i=0; i<N; i++) {
6594                PackageParser.Activity a = pkg.activities.get(i);
6595                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6596                        a.info.processName, pkg.applicationInfo.uid);
6597                mActivities.addActivity(a, "activity");
6598                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6599                    if (r == null) {
6600                        r = new StringBuilder(256);
6601                    } else {
6602                        r.append(' ');
6603                    }
6604                    r.append(a.info.name);
6605                }
6606            }
6607            if (r != null) {
6608                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6609            }
6610
6611            N = pkg.permissionGroups.size();
6612            r = null;
6613            for (i=0; i<N; i++) {
6614                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6615                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6616                if (cur == null) {
6617                    mPermissionGroups.put(pg.info.name, pg);
6618                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6619                        if (r == null) {
6620                            r = new StringBuilder(256);
6621                        } else {
6622                            r.append(' ');
6623                        }
6624                        r.append(pg.info.name);
6625                    }
6626                } else {
6627                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6628                            + pg.info.packageName + " ignored: original from "
6629                            + cur.info.packageName);
6630                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6631                        if (r == null) {
6632                            r = new StringBuilder(256);
6633                        } else {
6634                            r.append(' ');
6635                        }
6636                        r.append("DUP:");
6637                        r.append(pg.info.name);
6638                    }
6639                }
6640            }
6641            if (r != null) {
6642                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6643            }
6644
6645            N = pkg.permissions.size();
6646            r = null;
6647            for (i=0; i<N; i++) {
6648                PackageParser.Permission p = pkg.permissions.get(i);
6649
6650                // Now that permission groups have a special meaning, we ignore permission
6651                // groups for legacy apps to prevent unexpected behavior. In particular,
6652                // permissions for one app being granted to someone just becuase they happen
6653                // to be in a group defined by another app (before this had no implications).
6654                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6655                    p.group = mPermissionGroups.get(p.info.group);
6656                    // Warn for a permission in an unknown group.
6657                    if (p.info.group != null && p.group == null) {
6658                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6659                                + p.info.packageName + " in an unknown group " + p.info.group);
6660                    }
6661                }
6662
6663                ArrayMap<String, BasePermission> permissionMap =
6664                        p.tree ? mSettings.mPermissionTrees
6665                                : mSettings.mPermissions;
6666                BasePermission bp = permissionMap.get(p.info.name);
6667
6668                // Allow system apps to redefine non-system permissions
6669                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6670                    final boolean currentOwnerIsSystem = (bp.perm != null
6671                            && isSystemApp(bp.perm.owner));
6672                    if (isSystemApp(p.owner)) {
6673                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6674                            // It's a built-in permission and no owner, take ownership now
6675                            bp.packageSetting = pkgSetting;
6676                            bp.perm = p;
6677                            bp.uid = pkg.applicationInfo.uid;
6678                            bp.sourcePackage = p.info.packageName;
6679                        } else if (!currentOwnerIsSystem) {
6680                            String msg = "New decl " + p.owner + " of permission  "
6681                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6682                            reportSettingsProblem(Log.WARN, msg);
6683                            bp = null;
6684                        }
6685                    }
6686                }
6687
6688                if (bp == null) {
6689                    bp = new BasePermission(p.info.name, p.info.packageName,
6690                            BasePermission.TYPE_NORMAL);
6691                    permissionMap.put(p.info.name, bp);
6692                }
6693
6694                if (bp.perm == null) {
6695                    if (bp.sourcePackage == null
6696                            || bp.sourcePackage.equals(p.info.packageName)) {
6697                        BasePermission tree = findPermissionTreeLP(p.info.name);
6698                        if (tree == null
6699                                || tree.sourcePackage.equals(p.info.packageName)) {
6700                            bp.packageSetting = pkgSetting;
6701                            bp.perm = p;
6702                            bp.uid = pkg.applicationInfo.uid;
6703                            bp.sourcePackage = p.info.packageName;
6704                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6705                                if (r == null) {
6706                                    r = new StringBuilder(256);
6707                                } else {
6708                                    r.append(' ');
6709                                }
6710                                r.append(p.info.name);
6711                            }
6712                        } else {
6713                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6714                                    + p.info.packageName + " ignored: base tree "
6715                                    + tree.name + " is from package "
6716                                    + tree.sourcePackage);
6717                        }
6718                    } else {
6719                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6720                                + p.info.packageName + " ignored: original from "
6721                                + bp.sourcePackage);
6722                    }
6723                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6724                    if (r == null) {
6725                        r = new StringBuilder(256);
6726                    } else {
6727                        r.append(' ');
6728                    }
6729                    r.append("DUP:");
6730                    r.append(p.info.name);
6731                }
6732                if (bp.perm == p) {
6733                    bp.protectionLevel = p.info.protectionLevel;
6734                }
6735            }
6736
6737            if (r != null) {
6738                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6739            }
6740
6741            N = pkg.instrumentation.size();
6742            r = null;
6743            for (i=0; i<N; i++) {
6744                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6745                a.info.packageName = pkg.applicationInfo.packageName;
6746                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6747                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6748                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6749                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6750                a.info.dataDir = pkg.applicationInfo.dataDir;
6751
6752                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6753                // need other information about the application, like the ABI and what not ?
6754                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6755                mInstrumentation.put(a.getComponentName(), a);
6756                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6757                    if (r == null) {
6758                        r = new StringBuilder(256);
6759                    } else {
6760                        r.append(' ');
6761                    }
6762                    r.append(a.info.name);
6763                }
6764            }
6765            if (r != null) {
6766                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6767            }
6768
6769            if (pkg.protectedBroadcasts != null) {
6770                N = pkg.protectedBroadcasts.size();
6771                for (i=0; i<N; i++) {
6772                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6773                }
6774            }
6775
6776            pkgSetting.setTimeStamp(scanFileTime);
6777
6778            // Create idmap files for pairs of (packages, overlay packages).
6779            // Note: "android", ie framework-res.apk, is handled by native layers.
6780            if (pkg.mOverlayTarget != null) {
6781                // This is an overlay package.
6782                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6783                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6784                        mOverlays.put(pkg.mOverlayTarget,
6785                                new ArrayMap<String, PackageParser.Package>());
6786                    }
6787                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6788                    map.put(pkg.packageName, pkg);
6789                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6790                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6791                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6792                                "scanPackageLI failed to createIdmap");
6793                    }
6794                }
6795            } else if (mOverlays.containsKey(pkg.packageName) &&
6796                    !pkg.packageName.equals("android")) {
6797                // This is a regular package, with one or more known overlay packages.
6798                createIdmapsForPackageLI(pkg);
6799            }
6800        }
6801
6802        return pkg;
6803    }
6804
6805    /**
6806     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6807     * i.e, so that all packages can be run inside a single process if required.
6808     *
6809     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6810     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6811     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6812     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6813     * updating a package that belongs to a shared user.
6814     *
6815     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6816     * adds unnecessary complexity.
6817     */
6818    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6819            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6820        String requiredInstructionSet = null;
6821        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6822            requiredInstructionSet = VMRuntime.getInstructionSet(
6823                     scannedPackage.applicationInfo.primaryCpuAbi);
6824        }
6825
6826        PackageSetting requirer = null;
6827        for (PackageSetting ps : packagesForUser) {
6828            // If packagesForUser contains scannedPackage, we skip it. This will happen
6829            // when scannedPackage is an update of an existing package. Without this check,
6830            // we will never be able to change the ABI of any package belonging to a shared
6831            // user, even if it's compatible with other packages.
6832            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6833                if (ps.primaryCpuAbiString == null) {
6834                    continue;
6835                }
6836
6837                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6838                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6839                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6840                    // this but there's not much we can do.
6841                    String errorMessage = "Instruction set mismatch, "
6842                            + ((requirer == null) ? "[caller]" : requirer)
6843                            + " requires " + requiredInstructionSet + " whereas " + ps
6844                            + " requires " + instructionSet;
6845                    Slog.w(TAG, errorMessage);
6846                }
6847
6848                if (requiredInstructionSet == null) {
6849                    requiredInstructionSet = instructionSet;
6850                    requirer = ps;
6851                }
6852            }
6853        }
6854
6855        if (requiredInstructionSet != null) {
6856            String adjustedAbi;
6857            if (requirer != null) {
6858                // requirer != null implies that either scannedPackage was null or that scannedPackage
6859                // did not require an ABI, in which case we have to adjust scannedPackage to match
6860                // the ABI of the set (which is the same as requirer's ABI)
6861                adjustedAbi = requirer.primaryCpuAbiString;
6862                if (scannedPackage != null) {
6863                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6864                }
6865            } else {
6866                // requirer == null implies that we're updating all ABIs in the set to
6867                // match scannedPackage.
6868                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6869            }
6870
6871            for (PackageSetting ps : packagesForUser) {
6872                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6873                    if (ps.primaryCpuAbiString != null) {
6874                        continue;
6875                    }
6876
6877                    ps.primaryCpuAbiString = adjustedAbi;
6878                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6879                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6880                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6881
6882                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
6883                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
6884                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6885                            ps.primaryCpuAbiString = null;
6886                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6887                            return;
6888                        } else {
6889                            mInstaller.rmdex(ps.codePathString,
6890                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
6891                        }
6892                    }
6893                }
6894            }
6895        }
6896    }
6897
6898    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6899        synchronized (mPackages) {
6900            mResolverReplaced = true;
6901            // Set up information for custom user intent resolution activity.
6902            mResolveActivity.applicationInfo = pkg.applicationInfo;
6903            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6904            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6905            mResolveActivity.processName = pkg.applicationInfo.packageName;
6906            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6907            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6908                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6909            mResolveActivity.theme = 0;
6910            mResolveActivity.exported = true;
6911            mResolveActivity.enabled = true;
6912            mResolveInfo.activityInfo = mResolveActivity;
6913            mResolveInfo.priority = 0;
6914            mResolveInfo.preferredOrder = 0;
6915            mResolveInfo.match = 0;
6916            mResolveComponentName = mCustomResolverComponentName;
6917            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6918                    mResolveComponentName);
6919        }
6920    }
6921
6922    private static String calculateBundledApkRoot(final String codePathString) {
6923        final File codePath = new File(codePathString);
6924        final File codeRoot;
6925        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6926            codeRoot = Environment.getRootDirectory();
6927        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6928            codeRoot = Environment.getOemDirectory();
6929        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6930            codeRoot = Environment.getVendorDirectory();
6931        } else {
6932            // Unrecognized code path; take its top real segment as the apk root:
6933            // e.g. /something/app/blah.apk => /something
6934            try {
6935                File f = codePath.getCanonicalFile();
6936                File parent = f.getParentFile();    // non-null because codePath is a file
6937                File tmp;
6938                while ((tmp = parent.getParentFile()) != null) {
6939                    f = parent;
6940                    parent = tmp;
6941                }
6942                codeRoot = f;
6943                Slog.w(TAG, "Unrecognized code path "
6944                        + codePath + " - using " + codeRoot);
6945            } catch (IOException e) {
6946                // Can't canonicalize the code path -- shenanigans?
6947                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6948                return Environment.getRootDirectory().getPath();
6949            }
6950        }
6951        return codeRoot.getPath();
6952    }
6953
6954    /**
6955     * Derive and set the location of native libraries for the given package,
6956     * which varies depending on where and how the package was installed.
6957     */
6958    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6959        final ApplicationInfo info = pkg.applicationInfo;
6960        final String codePath = pkg.codePath;
6961        final File codeFile = new File(codePath);
6962        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
6963        final boolean asecApp = info.isForwardLocked() || isExternal(info);
6964
6965        info.nativeLibraryRootDir = null;
6966        info.nativeLibraryRootRequiresIsa = false;
6967        info.nativeLibraryDir = null;
6968        info.secondaryNativeLibraryDir = null;
6969
6970        if (isApkFile(codeFile)) {
6971            // Monolithic install
6972            if (bundledApp) {
6973                // If "/system/lib64/apkname" exists, assume that is the per-package
6974                // native library directory to use; otherwise use "/system/lib/apkname".
6975                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6976                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6977                        getPrimaryInstructionSet(info));
6978
6979                // This is a bundled system app so choose the path based on the ABI.
6980                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6981                // is just the default path.
6982                final String apkName = deriveCodePathName(codePath);
6983                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6984                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6985                        apkName).getAbsolutePath();
6986
6987                if (info.secondaryCpuAbi != null) {
6988                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6989                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6990                            secondaryLibDir, apkName).getAbsolutePath();
6991                }
6992            } else if (asecApp) {
6993                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6994                        .getAbsolutePath();
6995            } else {
6996                final String apkName = deriveCodePathName(codePath);
6997                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6998                        .getAbsolutePath();
6999            }
7000
7001            info.nativeLibraryRootRequiresIsa = false;
7002            info.nativeLibraryDir = info.nativeLibraryRootDir;
7003        } else {
7004            // Cluster install
7005            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7006            info.nativeLibraryRootRequiresIsa = true;
7007
7008            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7009                    getPrimaryInstructionSet(info)).getAbsolutePath();
7010
7011            if (info.secondaryCpuAbi != null) {
7012                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7013                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7014            }
7015        }
7016    }
7017
7018    /**
7019     * Calculate the abis and roots for a bundled app. These can uniquely
7020     * be determined from the contents of the system partition, i.e whether
7021     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7022     * of this information, and instead assume that the system was built
7023     * sensibly.
7024     */
7025    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7026                                           PackageSetting pkgSetting) {
7027        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7028
7029        // If "/system/lib64/apkname" exists, assume that is the per-package
7030        // native library directory to use; otherwise use "/system/lib/apkname".
7031        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7032        setBundledAppAbi(pkg, apkRoot, apkName);
7033        // pkgSetting might be null during rescan following uninstall of updates
7034        // to a bundled app, so accommodate that possibility.  The settings in
7035        // that case will be established later from the parsed package.
7036        //
7037        // If the settings aren't null, sync them up with what we've just derived.
7038        // note that apkRoot isn't stored in the package settings.
7039        if (pkgSetting != null) {
7040            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7041            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7042        }
7043    }
7044
7045    /**
7046     * Deduces the ABI of a bundled app and sets the relevant fields on the
7047     * parsed pkg object.
7048     *
7049     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7050     *        under which system libraries are installed.
7051     * @param apkName the name of the installed package.
7052     */
7053    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7054        final File codeFile = new File(pkg.codePath);
7055
7056        final boolean has64BitLibs;
7057        final boolean has32BitLibs;
7058        if (isApkFile(codeFile)) {
7059            // Monolithic install
7060            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7061            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7062        } else {
7063            // Cluster install
7064            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7065            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7066                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7067                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7068                has64BitLibs = (new File(rootDir, isa)).exists();
7069            } else {
7070                has64BitLibs = false;
7071            }
7072            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7073                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7074                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7075                has32BitLibs = (new File(rootDir, isa)).exists();
7076            } else {
7077                has32BitLibs = false;
7078            }
7079        }
7080
7081        if (has64BitLibs && !has32BitLibs) {
7082            // The package has 64 bit libs, but not 32 bit libs. Its primary
7083            // ABI should be 64 bit. We can safely assume here that the bundled
7084            // native libraries correspond to the most preferred ABI in the list.
7085
7086            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7087            pkg.applicationInfo.secondaryCpuAbi = null;
7088        } else if (has32BitLibs && !has64BitLibs) {
7089            // The package has 32 bit libs but not 64 bit libs. Its primary
7090            // ABI should be 32 bit.
7091
7092            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7093            pkg.applicationInfo.secondaryCpuAbi = null;
7094        } else if (has32BitLibs && has64BitLibs) {
7095            // The application has both 64 and 32 bit bundled libraries. We check
7096            // here that the app declares multiArch support, and warn if it doesn't.
7097            //
7098            // We will be lenient here and record both ABIs. The primary will be the
7099            // ABI that's higher on the list, i.e, a device that's configured to prefer
7100            // 64 bit apps will see a 64 bit primary ABI,
7101
7102            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7103                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7104            }
7105
7106            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7107                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7108                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7109            } else {
7110                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7111                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7112            }
7113        } else {
7114            pkg.applicationInfo.primaryCpuAbi = null;
7115            pkg.applicationInfo.secondaryCpuAbi = null;
7116        }
7117    }
7118
7119    private void killApplication(String pkgName, int appId, String reason) {
7120        // Request the ActivityManager to kill the process(only for existing packages)
7121        // so that we do not end up in a confused state while the user is still using the older
7122        // version of the application while the new one gets installed.
7123        IActivityManager am = ActivityManagerNative.getDefault();
7124        if (am != null) {
7125            try {
7126                am.killApplicationWithAppId(pkgName, appId, reason);
7127            } catch (RemoteException e) {
7128            }
7129        }
7130    }
7131
7132    void removePackageLI(PackageSetting ps, boolean chatty) {
7133        if (DEBUG_INSTALL) {
7134            if (chatty)
7135                Log.d(TAG, "Removing package " + ps.name);
7136        }
7137
7138        // writer
7139        synchronized (mPackages) {
7140            mPackages.remove(ps.name);
7141            final PackageParser.Package pkg = ps.pkg;
7142            if (pkg != null) {
7143                cleanPackageDataStructuresLILPw(pkg, chatty);
7144            }
7145        }
7146    }
7147
7148    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7149        if (DEBUG_INSTALL) {
7150            if (chatty)
7151                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7152        }
7153
7154        // writer
7155        synchronized (mPackages) {
7156            mPackages.remove(pkg.applicationInfo.packageName);
7157            cleanPackageDataStructuresLILPw(pkg, chatty);
7158        }
7159    }
7160
7161    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7162        int N = pkg.providers.size();
7163        StringBuilder r = null;
7164        int i;
7165        for (i=0; i<N; i++) {
7166            PackageParser.Provider p = pkg.providers.get(i);
7167            mProviders.removeProvider(p);
7168            if (p.info.authority == null) {
7169
7170                /* There was another ContentProvider with this authority when
7171                 * this app was installed so this authority is null,
7172                 * Ignore it as we don't have to unregister the provider.
7173                 */
7174                continue;
7175            }
7176            String names[] = p.info.authority.split(";");
7177            for (int j = 0; j < names.length; j++) {
7178                if (mProvidersByAuthority.get(names[j]) == p) {
7179                    mProvidersByAuthority.remove(names[j]);
7180                    if (DEBUG_REMOVE) {
7181                        if (chatty)
7182                            Log.d(TAG, "Unregistered content provider: " + names[j]
7183                                    + ", className = " + p.info.name + ", isSyncable = "
7184                                    + p.info.isSyncable);
7185                    }
7186                }
7187            }
7188            if (DEBUG_REMOVE && chatty) {
7189                if (r == null) {
7190                    r = new StringBuilder(256);
7191                } else {
7192                    r.append(' ');
7193                }
7194                r.append(p.info.name);
7195            }
7196        }
7197        if (r != null) {
7198            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7199        }
7200
7201        N = pkg.services.size();
7202        r = null;
7203        for (i=0; i<N; i++) {
7204            PackageParser.Service s = pkg.services.get(i);
7205            mServices.removeService(s);
7206            if (chatty) {
7207                if (r == null) {
7208                    r = new StringBuilder(256);
7209                } else {
7210                    r.append(' ');
7211                }
7212                r.append(s.info.name);
7213            }
7214        }
7215        if (r != null) {
7216            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7217        }
7218
7219        N = pkg.receivers.size();
7220        r = null;
7221        for (i=0; i<N; i++) {
7222            PackageParser.Activity a = pkg.receivers.get(i);
7223            mReceivers.removeActivity(a, "receiver");
7224            if (DEBUG_REMOVE && chatty) {
7225                if (r == null) {
7226                    r = new StringBuilder(256);
7227                } else {
7228                    r.append(' ');
7229                }
7230                r.append(a.info.name);
7231            }
7232        }
7233        if (r != null) {
7234            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7235        }
7236
7237        N = pkg.activities.size();
7238        r = null;
7239        for (i=0; i<N; i++) {
7240            PackageParser.Activity a = pkg.activities.get(i);
7241            mActivities.removeActivity(a, "activity");
7242            if (DEBUG_REMOVE && chatty) {
7243                if (r == null) {
7244                    r = new StringBuilder(256);
7245                } else {
7246                    r.append(' ');
7247                }
7248                r.append(a.info.name);
7249            }
7250        }
7251        if (r != null) {
7252            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7253        }
7254
7255        N = pkg.permissions.size();
7256        r = null;
7257        for (i=0; i<N; i++) {
7258            PackageParser.Permission p = pkg.permissions.get(i);
7259            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7260            if (bp == null) {
7261                bp = mSettings.mPermissionTrees.get(p.info.name);
7262            }
7263            if (bp != null && bp.perm == p) {
7264                bp.perm = null;
7265                if (DEBUG_REMOVE && chatty) {
7266                    if (r == null) {
7267                        r = new StringBuilder(256);
7268                    } else {
7269                        r.append(' ');
7270                    }
7271                    r.append(p.info.name);
7272                }
7273            }
7274            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7275                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7276                if (appOpPerms != null) {
7277                    appOpPerms.remove(pkg.packageName);
7278                }
7279            }
7280        }
7281        if (r != null) {
7282            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7283        }
7284
7285        N = pkg.requestedPermissions.size();
7286        r = null;
7287        for (i=0; i<N; i++) {
7288            String perm = pkg.requestedPermissions.get(i);
7289            BasePermission bp = mSettings.mPermissions.get(perm);
7290            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7291                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7292                if (appOpPerms != null) {
7293                    appOpPerms.remove(pkg.packageName);
7294                    if (appOpPerms.isEmpty()) {
7295                        mAppOpPermissionPackages.remove(perm);
7296                    }
7297                }
7298            }
7299        }
7300        if (r != null) {
7301            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7302        }
7303
7304        N = pkg.instrumentation.size();
7305        r = null;
7306        for (i=0; i<N; i++) {
7307            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7308            mInstrumentation.remove(a.getComponentName());
7309            if (DEBUG_REMOVE && chatty) {
7310                if (r == null) {
7311                    r = new StringBuilder(256);
7312                } else {
7313                    r.append(' ');
7314                }
7315                r.append(a.info.name);
7316            }
7317        }
7318        if (r != null) {
7319            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7320        }
7321
7322        r = null;
7323        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7324            // Only system apps can hold shared libraries.
7325            if (pkg.libraryNames != null) {
7326                for (i=0; i<pkg.libraryNames.size(); i++) {
7327                    String name = pkg.libraryNames.get(i);
7328                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7329                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7330                        mSharedLibraries.remove(name);
7331                        if (DEBUG_REMOVE && chatty) {
7332                            if (r == null) {
7333                                r = new StringBuilder(256);
7334                            } else {
7335                                r.append(' ');
7336                            }
7337                            r.append(name);
7338                        }
7339                    }
7340                }
7341            }
7342        }
7343        if (r != null) {
7344            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7345        }
7346    }
7347
7348    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7349        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7350            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7351                return true;
7352            }
7353        }
7354        return false;
7355    }
7356
7357    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7358    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7359    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7360
7361    private void updatePermissionsLPw(String changingPkg,
7362            PackageParser.Package pkgInfo, int flags) {
7363        // Make sure there are no dangling permission trees.
7364        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7365        while (it.hasNext()) {
7366            final BasePermission bp = it.next();
7367            if (bp.packageSetting == null) {
7368                // We may not yet have parsed the package, so just see if
7369                // we still know about its settings.
7370                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7371            }
7372            if (bp.packageSetting == null) {
7373                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7374                        + " from package " + bp.sourcePackage);
7375                it.remove();
7376            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7377                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7378                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7379                            + " from package " + bp.sourcePackage);
7380                    flags |= UPDATE_PERMISSIONS_ALL;
7381                    it.remove();
7382                }
7383            }
7384        }
7385
7386        // Make sure all dynamic permissions have been assigned to a package,
7387        // and make sure there are no dangling permissions.
7388        it = mSettings.mPermissions.values().iterator();
7389        while (it.hasNext()) {
7390            final BasePermission bp = it.next();
7391            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7392                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7393                        + bp.name + " pkg=" + bp.sourcePackage
7394                        + " info=" + bp.pendingInfo);
7395                if (bp.packageSetting == null && bp.pendingInfo != null) {
7396                    final BasePermission tree = findPermissionTreeLP(bp.name);
7397                    if (tree != null && tree.perm != null) {
7398                        bp.packageSetting = tree.packageSetting;
7399                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7400                                new PermissionInfo(bp.pendingInfo));
7401                        bp.perm.info.packageName = tree.perm.info.packageName;
7402                        bp.perm.info.name = bp.name;
7403                        bp.uid = tree.uid;
7404                    }
7405                }
7406            }
7407            if (bp.packageSetting == null) {
7408                // We may not yet have parsed the package, so just see if
7409                // we still know about its settings.
7410                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7411            }
7412            if (bp.packageSetting == null) {
7413                Slog.w(TAG, "Removing dangling permission: " + bp.name
7414                        + " from package " + bp.sourcePackage);
7415                it.remove();
7416            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7417                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7418                    Slog.i(TAG, "Removing old permission: " + bp.name
7419                            + " from package " + bp.sourcePackage);
7420                    flags |= UPDATE_PERMISSIONS_ALL;
7421                    it.remove();
7422                }
7423            }
7424        }
7425
7426        // Now update the permissions for all packages, in particular
7427        // replace the granted permissions of the system packages.
7428        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7429            for (PackageParser.Package pkg : mPackages.values()) {
7430                if (pkg != pkgInfo) {
7431                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7432                            changingPkg);
7433                }
7434            }
7435        }
7436
7437        if (pkgInfo != null) {
7438            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7439        }
7440    }
7441
7442    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7443            String packageOfInterest) {
7444        // IMPORTANT: There are two types of permissions: install and runtime.
7445        // Install time permissions are granted when the app is installed to
7446        // all device users and users added in the future. Runtime permissions
7447        // are granted at runtime explicitly to specific users. Normal and signature
7448        // protected permissions are install time permissions. Dangerous permissions
7449        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7450        // otherwise they are runtime permissions. This function does not manage
7451        // runtime permissions except for the case an app targeting Lollipop MR1
7452        // being upgraded to target a newer SDK, in which case dangerous permissions
7453        // are transformed from install time to runtime ones.
7454
7455        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7456        if (ps == null) {
7457            return;
7458        }
7459
7460        PermissionsState permissionsState = ps.getPermissionsState();
7461        PermissionsState origPermissions = permissionsState;
7462
7463        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7464
7465        int[] upgradeUserIds = PermissionsState.USERS_NONE;
7466        int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE;
7467
7468        boolean changedInstallPermission = false;
7469
7470        if (replace) {
7471            ps.installPermissionsFixed = false;
7472            if (!ps.isSharedUser()) {
7473                origPermissions = new PermissionsState(permissionsState);
7474                permissionsState.reset();
7475            }
7476        }
7477
7478        permissionsState.setGlobalGids(mGlobalGids);
7479
7480        final int N = pkg.requestedPermissions.size();
7481        for (int i=0; i<N; i++) {
7482            final String name = pkg.requestedPermissions.get(i);
7483            final BasePermission bp = mSettings.mPermissions.get(name);
7484
7485            if (DEBUG_INSTALL) {
7486                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7487            }
7488
7489            if (bp == null || bp.packageSetting == null) {
7490                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7491                    Slog.w(TAG, "Unknown permission " + name
7492                            + " in package " + pkg.packageName);
7493                }
7494                continue;
7495            }
7496
7497            final String perm = bp.name;
7498            boolean allowedSig = false;
7499            int grant = GRANT_DENIED;
7500
7501            // Keep track of app op permissions.
7502            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7503                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7504                if (pkgs == null) {
7505                    pkgs = new ArraySet<>();
7506                    mAppOpPermissionPackages.put(bp.name, pkgs);
7507                }
7508                pkgs.add(pkg.packageName);
7509            }
7510
7511            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7512            switch (level) {
7513                case PermissionInfo.PROTECTION_NORMAL: {
7514                    // For all apps normal permissions are install time ones.
7515                    grant = GRANT_INSTALL;
7516                } break;
7517
7518                case PermissionInfo.PROTECTION_DANGEROUS: {
7519                    if (!RUNTIME_PERMISSIONS_ENABLED
7520                            || pkg.applicationInfo.targetSdkVersion
7521                                    <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7522                        // For legacy apps dangerous permissions are install time ones.
7523                        grant = GRANT_INSTALL;
7524                    } else if (ps.isSystem()) {
7525                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7526                        if (origPermissions.hasInstallPermission(bp.name)) {
7527                            // If a system app had an install permission, then the app was
7528                            // upgraded and we grant the permissions as runtime to all users.
7529                            grant = GRANT_UPGRADE;
7530                            upgradeUserIds = currentUserIds;
7531                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7532                            // If users changed since the last permissions update for a
7533                            // system app, we grant the permission as runtime to the new users.
7534                            grant = GRANT_UPGRADE;
7535                            upgradeUserIds = currentUserIds;
7536                            for (int userId : updatedUserIds) {
7537                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7538                            }
7539                        } else {
7540                            // Otherwise, we grant the permission as runtime if the app
7541                            // already had it, i.e. we preserve runtime permissions.
7542                            grant = GRANT_RUNTIME;
7543                        }
7544                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7545                        // For legacy apps that became modern, install becomes runtime.
7546                        grant = GRANT_UPGRADE;
7547                        upgradeUserIds = currentUserIds;
7548                    } else if (replace) {
7549                        // For upgraded modern apps keep runtime permissions unchanged.
7550                        grant = GRANT_RUNTIME;
7551                    }
7552                } break;
7553
7554                case PermissionInfo.PROTECTION_SIGNATURE: {
7555                    // For all apps signature permissions are install time ones.
7556                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7557                    if (allowedSig) {
7558                        grant = GRANT_INSTALL;
7559                    }
7560                } break;
7561            }
7562
7563            if (DEBUG_INSTALL) {
7564                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7565            }
7566
7567            if (grant != GRANT_DENIED) {
7568                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7569                    // If this is an existing, non-system package, then
7570                    // we can't add any new permissions to it.
7571                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7572                        // Except...  if this is a permission that was added
7573                        // to the platform (note: need to only do this when
7574                        // updating the platform).
7575                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7576                            grant = GRANT_DENIED;
7577                        }
7578                    }
7579                }
7580
7581                switch (grant) {
7582                    case GRANT_INSTALL: {
7583                        // Grant an install permission.
7584                        if (permissionsState.grantInstallPermission(bp) !=
7585                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7586                            changedInstallPermission = true;
7587                        }
7588                    } break;
7589
7590                    case GRANT_RUNTIME: {
7591                        // Grant previously granted runtime permissions.
7592                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7593                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7594                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7595                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7596                                    // If we cannot put the permission as it was, we have to write.
7597                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7598                                            changedRuntimePermissionUserIds, userId);
7599                                }
7600                            }
7601                        }
7602                    } break;
7603
7604                    case GRANT_UPGRADE: {
7605                        // Grant runtime permissions for a previously held install permission.
7606                        permissionsState.revokeInstallPermission(bp);
7607                        for (int userId : upgradeUserIds) {
7608                            if (permissionsState.grantRuntimePermission(bp, userId) !=
7609                                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
7610                                // If we granted the permission, we have to write.
7611                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7612                                        changedRuntimePermissionUserIds, userId);
7613                            }
7614                        }
7615                    } break;
7616
7617                    default: {
7618                        if (packageOfInterest == null
7619                                || packageOfInterest.equals(pkg.packageName)) {
7620                            Slog.w(TAG, "Not granting permission " + perm
7621                                    + " to package " + pkg.packageName
7622                                    + " because it was previously installed without");
7623                        }
7624                    } break;
7625                }
7626            } else {
7627                if (permissionsState.revokeInstallPermission(bp) !=
7628                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7629                    changedInstallPermission = true;
7630                    Slog.i(TAG, "Un-granting permission " + perm
7631                            + " from package " + pkg.packageName
7632                            + " (protectionLevel=" + bp.protectionLevel
7633                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7634                            + ")");
7635                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7636                    // Don't print warning for app op permissions, since it is fine for them
7637                    // not to be granted, there is a UI for the user to decide.
7638                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7639                        Slog.w(TAG, "Not granting permission " + perm
7640                                + " to package " + pkg.packageName
7641                                + " (protectionLevel=" + bp.protectionLevel
7642                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7643                                + ")");
7644                    }
7645                }
7646            }
7647        }
7648
7649        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7650                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7651            // This is the first that we have heard about this package, so the
7652            // permissions we have now selected are fixed until explicitly
7653            // changed.
7654            ps.installPermissionsFixed = true;
7655        }
7656
7657        ps.setPermissionsUpdatedForUserIds(currentUserIds);
7658
7659        // Persist the runtime permissions state for users with changes.
7660        if (RUNTIME_PERMISSIONS_ENABLED) {
7661            for (int userId : changedRuntimePermissionUserIds) {
7662                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
7663            }
7664        }
7665    }
7666
7667    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7668        boolean allowed = false;
7669        final int NP = PackageParser.NEW_PERMISSIONS.length;
7670        for (int ip=0; ip<NP; ip++) {
7671            final PackageParser.NewPermissionInfo npi
7672                    = PackageParser.NEW_PERMISSIONS[ip];
7673            if (npi.name.equals(perm)
7674                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7675                allowed = true;
7676                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7677                        + pkg.packageName);
7678                break;
7679            }
7680        }
7681        return allowed;
7682    }
7683
7684    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7685            BasePermission bp, PermissionsState origPermissions) {
7686        boolean allowed;
7687        allowed = (compareSignatures(
7688                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7689                        == PackageManager.SIGNATURE_MATCH)
7690                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7691                        == PackageManager.SIGNATURE_MATCH);
7692        if (!allowed && (bp.protectionLevel
7693                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7694            if (isSystemApp(pkg)) {
7695                // For updated system applications, a system permission
7696                // is granted only if it had been defined by the original application.
7697                if (pkg.isUpdatedSystemApp()) {
7698                    final PackageSetting sysPs = mSettings
7699                            .getDisabledSystemPkgLPr(pkg.packageName);
7700                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
7701                        // If the original was granted this permission, we take
7702                        // that grant decision as read and propagate it to the
7703                        // update.
7704                        if (sysPs.isPrivileged()) {
7705                            allowed = true;
7706                        }
7707                    } else {
7708                        // The system apk may have been updated with an older
7709                        // version of the one on the data partition, but which
7710                        // granted a new system permission that it didn't have
7711                        // before.  In this case we do want to allow the app to
7712                        // now get the new permission if the ancestral apk is
7713                        // privileged to get it.
7714                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7715                            for (int j=0;
7716                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7717                                if (perm.equals(
7718                                        sysPs.pkg.requestedPermissions.get(j))) {
7719                                    allowed = true;
7720                                    break;
7721                                }
7722                            }
7723                        }
7724                    }
7725                } else {
7726                    allowed = isPrivilegedApp(pkg);
7727                }
7728            }
7729        }
7730        if (!allowed && (bp.protectionLevel
7731                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7732            // For development permissions, a development permission
7733            // is granted only if it was already granted.
7734            allowed = origPermissions.hasInstallPermission(perm);
7735        }
7736        return allowed;
7737    }
7738
7739    final class ActivityIntentResolver
7740            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7741        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7742                boolean defaultOnly, int userId) {
7743            if (!sUserManager.exists(userId)) return null;
7744            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7745            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7746        }
7747
7748        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7749                int userId) {
7750            if (!sUserManager.exists(userId)) return null;
7751            mFlags = flags;
7752            return super.queryIntent(intent, resolvedType,
7753                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7754        }
7755
7756        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7757                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7758            if (!sUserManager.exists(userId)) return null;
7759            if (packageActivities == null) {
7760                return null;
7761            }
7762            mFlags = flags;
7763            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7764            final int N = packageActivities.size();
7765            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7766                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7767
7768            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7769            for (int i = 0; i < N; ++i) {
7770                intentFilters = packageActivities.get(i).intents;
7771                if (intentFilters != null && intentFilters.size() > 0) {
7772                    PackageParser.ActivityIntentInfo[] array =
7773                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7774                    intentFilters.toArray(array);
7775                    listCut.add(array);
7776                }
7777            }
7778            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7779        }
7780
7781        public final void addActivity(PackageParser.Activity a, String type) {
7782            final boolean systemApp = a.info.applicationInfo.isSystemApp();
7783            mActivities.put(a.getComponentName(), a);
7784            if (DEBUG_SHOW_INFO)
7785                Log.v(
7786                TAG, "  " + type + " " +
7787                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7788            if (DEBUG_SHOW_INFO)
7789                Log.v(TAG, "    Class=" + a.info.name);
7790            final int NI = a.intents.size();
7791            for (int j=0; j<NI; j++) {
7792                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7793                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7794                    intent.setPriority(0);
7795                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7796                            + a.className + " with priority > 0, forcing to 0");
7797                }
7798                if (DEBUG_SHOW_INFO) {
7799                    Log.v(TAG, "    IntentFilter:");
7800                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7801                }
7802                if (!intent.debugCheck()) {
7803                    Log.w(TAG, "==> For Activity " + a.info.name);
7804                }
7805                addFilter(intent);
7806            }
7807        }
7808
7809        public final void removeActivity(PackageParser.Activity a, String type) {
7810            mActivities.remove(a.getComponentName());
7811            if (DEBUG_SHOW_INFO) {
7812                Log.v(TAG, "  " + type + " "
7813                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7814                                : a.info.name) + ":");
7815                Log.v(TAG, "    Class=" + a.info.name);
7816            }
7817            final int NI = a.intents.size();
7818            for (int j=0; j<NI; j++) {
7819                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7820                if (DEBUG_SHOW_INFO) {
7821                    Log.v(TAG, "    IntentFilter:");
7822                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7823                }
7824                removeFilter(intent);
7825            }
7826        }
7827
7828        @Override
7829        protected boolean allowFilterResult(
7830                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7831            ActivityInfo filterAi = filter.activity.info;
7832            for (int i=dest.size()-1; i>=0; i--) {
7833                ActivityInfo destAi = dest.get(i).activityInfo;
7834                if (destAi.name == filterAi.name
7835                        && destAi.packageName == filterAi.packageName) {
7836                    return false;
7837                }
7838            }
7839            return true;
7840        }
7841
7842        @Override
7843        protected ActivityIntentInfo[] newArray(int size) {
7844            return new ActivityIntentInfo[size];
7845        }
7846
7847        @Override
7848        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7849            if (!sUserManager.exists(userId)) return true;
7850            PackageParser.Package p = filter.activity.owner;
7851            if (p != null) {
7852                PackageSetting ps = (PackageSetting)p.mExtras;
7853                if (ps != null) {
7854                    // System apps are never considered stopped for purposes of
7855                    // filtering, because there may be no way for the user to
7856                    // actually re-launch them.
7857                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7858                            && ps.getStopped(userId);
7859                }
7860            }
7861            return false;
7862        }
7863
7864        @Override
7865        protected boolean isPackageForFilter(String packageName,
7866                PackageParser.ActivityIntentInfo info) {
7867            return packageName.equals(info.activity.owner.packageName);
7868        }
7869
7870        @Override
7871        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7872                int match, int userId) {
7873            if (!sUserManager.exists(userId)) return null;
7874            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7875                return null;
7876            }
7877            final PackageParser.Activity activity = info.activity;
7878            if (mSafeMode && (activity.info.applicationInfo.flags
7879                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7880                return null;
7881            }
7882            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7883            if (ps == null) {
7884                return null;
7885            }
7886            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7887                    ps.readUserState(userId), userId);
7888            if (ai == null) {
7889                return null;
7890            }
7891            final ResolveInfo res = new ResolveInfo();
7892            res.activityInfo = ai;
7893            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7894                res.filter = info;
7895            }
7896            if (info != null) {
7897                res.handleAllWebDataURI = info.handleAllWebDataURI();
7898            }
7899            res.priority = info.getPriority();
7900            res.preferredOrder = activity.owner.mPreferredOrder;
7901            //System.out.println("Result: " + res.activityInfo.className +
7902            //                   " = " + res.priority);
7903            res.match = match;
7904            res.isDefault = info.hasDefault;
7905            res.labelRes = info.labelRes;
7906            res.nonLocalizedLabel = info.nonLocalizedLabel;
7907            if (userNeedsBadging(userId)) {
7908                res.noResourceId = true;
7909            } else {
7910                res.icon = info.icon;
7911            }
7912            res.system = res.activityInfo.applicationInfo.isSystemApp();
7913            return res;
7914        }
7915
7916        @Override
7917        protected void sortResults(List<ResolveInfo> results) {
7918            Collections.sort(results, mResolvePrioritySorter);
7919        }
7920
7921        @Override
7922        protected void dumpFilter(PrintWriter out, String prefix,
7923                PackageParser.ActivityIntentInfo filter) {
7924            out.print(prefix); out.print(
7925                    Integer.toHexString(System.identityHashCode(filter.activity)));
7926                    out.print(' ');
7927                    filter.activity.printComponentShortName(out);
7928                    out.print(" filter ");
7929                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7930        }
7931
7932        @Override
7933        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
7934            return filter.activity;
7935        }
7936
7937        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7938            PackageParser.Activity activity = (PackageParser.Activity)label;
7939            out.print(prefix); out.print(
7940                    Integer.toHexString(System.identityHashCode(activity)));
7941                    out.print(' ');
7942                    activity.printComponentShortName(out);
7943            if (count > 1) {
7944                out.print(" ("); out.print(count); out.print(" filters)");
7945            }
7946            out.println();
7947        }
7948
7949//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7950//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7951//            final List<ResolveInfo> retList = Lists.newArrayList();
7952//            while (i.hasNext()) {
7953//                final ResolveInfo resolveInfo = i.next();
7954//                if (isEnabledLP(resolveInfo.activityInfo)) {
7955//                    retList.add(resolveInfo);
7956//                }
7957//            }
7958//            return retList;
7959//        }
7960
7961        // Keys are String (activity class name), values are Activity.
7962        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
7963                = new ArrayMap<ComponentName, PackageParser.Activity>();
7964        private int mFlags;
7965    }
7966
7967    private final class ServiceIntentResolver
7968            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7969        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7970                boolean defaultOnly, int userId) {
7971            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7972            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7973        }
7974
7975        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7976                int userId) {
7977            if (!sUserManager.exists(userId)) return null;
7978            mFlags = flags;
7979            return super.queryIntent(intent, resolvedType,
7980                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7981        }
7982
7983        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7984                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7985            if (!sUserManager.exists(userId)) return null;
7986            if (packageServices == null) {
7987                return null;
7988            }
7989            mFlags = flags;
7990            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7991            final int N = packageServices.size();
7992            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7993                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7994
7995            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7996            for (int i = 0; i < N; ++i) {
7997                intentFilters = packageServices.get(i).intents;
7998                if (intentFilters != null && intentFilters.size() > 0) {
7999                    PackageParser.ServiceIntentInfo[] array =
8000                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8001                    intentFilters.toArray(array);
8002                    listCut.add(array);
8003                }
8004            }
8005            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8006        }
8007
8008        public final void addService(PackageParser.Service s) {
8009            mServices.put(s.getComponentName(), s);
8010            if (DEBUG_SHOW_INFO) {
8011                Log.v(TAG, "  "
8012                        + (s.info.nonLocalizedLabel != null
8013                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8014                Log.v(TAG, "    Class=" + s.info.name);
8015            }
8016            final int NI = s.intents.size();
8017            int j;
8018            for (j=0; j<NI; j++) {
8019                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8020                if (DEBUG_SHOW_INFO) {
8021                    Log.v(TAG, "    IntentFilter:");
8022                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8023                }
8024                if (!intent.debugCheck()) {
8025                    Log.w(TAG, "==> For Service " + s.info.name);
8026                }
8027                addFilter(intent);
8028            }
8029        }
8030
8031        public final void removeService(PackageParser.Service s) {
8032            mServices.remove(s.getComponentName());
8033            if (DEBUG_SHOW_INFO) {
8034                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8035                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8036                Log.v(TAG, "    Class=" + s.info.name);
8037            }
8038            final int NI = s.intents.size();
8039            int j;
8040            for (j=0; j<NI; j++) {
8041                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8042                if (DEBUG_SHOW_INFO) {
8043                    Log.v(TAG, "    IntentFilter:");
8044                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8045                }
8046                removeFilter(intent);
8047            }
8048        }
8049
8050        @Override
8051        protected boolean allowFilterResult(
8052                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8053            ServiceInfo filterSi = filter.service.info;
8054            for (int i=dest.size()-1; i>=0; i--) {
8055                ServiceInfo destAi = dest.get(i).serviceInfo;
8056                if (destAi.name == filterSi.name
8057                        && destAi.packageName == filterSi.packageName) {
8058                    return false;
8059                }
8060            }
8061            return true;
8062        }
8063
8064        @Override
8065        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8066            return new PackageParser.ServiceIntentInfo[size];
8067        }
8068
8069        @Override
8070        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8071            if (!sUserManager.exists(userId)) return true;
8072            PackageParser.Package p = filter.service.owner;
8073            if (p != null) {
8074                PackageSetting ps = (PackageSetting)p.mExtras;
8075                if (ps != null) {
8076                    // System apps are never considered stopped for purposes of
8077                    // filtering, because there may be no way for the user to
8078                    // actually re-launch them.
8079                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8080                            && ps.getStopped(userId);
8081                }
8082            }
8083            return false;
8084        }
8085
8086        @Override
8087        protected boolean isPackageForFilter(String packageName,
8088                PackageParser.ServiceIntentInfo info) {
8089            return packageName.equals(info.service.owner.packageName);
8090        }
8091
8092        @Override
8093        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8094                int match, int userId) {
8095            if (!sUserManager.exists(userId)) return null;
8096            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8097            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8098                return null;
8099            }
8100            final PackageParser.Service service = info.service;
8101            if (mSafeMode && (service.info.applicationInfo.flags
8102                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8103                return null;
8104            }
8105            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8106            if (ps == null) {
8107                return null;
8108            }
8109            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8110                    ps.readUserState(userId), userId);
8111            if (si == null) {
8112                return null;
8113            }
8114            final ResolveInfo res = new ResolveInfo();
8115            res.serviceInfo = si;
8116            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8117                res.filter = filter;
8118            }
8119            res.priority = info.getPriority();
8120            res.preferredOrder = service.owner.mPreferredOrder;
8121            res.match = match;
8122            res.isDefault = info.hasDefault;
8123            res.labelRes = info.labelRes;
8124            res.nonLocalizedLabel = info.nonLocalizedLabel;
8125            res.icon = info.icon;
8126            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8127            return res;
8128        }
8129
8130        @Override
8131        protected void sortResults(List<ResolveInfo> results) {
8132            Collections.sort(results, mResolvePrioritySorter);
8133        }
8134
8135        @Override
8136        protected void dumpFilter(PrintWriter out, String prefix,
8137                PackageParser.ServiceIntentInfo filter) {
8138            out.print(prefix); out.print(
8139                    Integer.toHexString(System.identityHashCode(filter.service)));
8140                    out.print(' ');
8141                    filter.service.printComponentShortName(out);
8142                    out.print(" filter ");
8143                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8144        }
8145
8146        @Override
8147        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8148            return filter.service;
8149        }
8150
8151        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8152            PackageParser.Service service = (PackageParser.Service)label;
8153            out.print(prefix); out.print(
8154                    Integer.toHexString(System.identityHashCode(service)));
8155                    out.print(' ');
8156                    service.printComponentShortName(out);
8157            if (count > 1) {
8158                out.print(" ("); out.print(count); out.print(" filters)");
8159            }
8160            out.println();
8161        }
8162
8163//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8164//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8165//            final List<ResolveInfo> retList = Lists.newArrayList();
8166//            while (i.hasNext()) {
8167//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8168//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8169//                    retList.add(resolveInfo);
8170//                }
8171//            }
8172//            return retList;
8173//        }
8174
8175        // Keys are String (activity class name), values are Activity.
8176        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8177                = new ArrayMap<ComponentName, PackageParser.Service>();
8178        private int mFlags;
8179    };
8180
8181    private final class ProviderIntentResolver
8182            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8183        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8184                boolean defaultOnly, int userId) {
8185            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8186            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8187        }
8188
8189        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8190                int userId) {
8191            if (!sUserManager.exists(userId))
8192                return null;
8193            mFlags = flags;
8194            return super.queryIntent(intent, resolvedType,
8195                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8196        }
8197
8198        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8199                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8200            if (!sUserManager.exists(userId))
8201                return null;
8202            if (packageProviders == null) {
8203                return null;
8204            }
8205            mFlags = flags;
8206            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8207            final int N = packageProviders.size();
8208            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8209                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8210
8211            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8212            for (int i = 0; i < N; ++i) {
8213                intentFilters = packageProviders.get(i).intents;
8214                if (intentFilters != null && intentFilters.size() > 0) {
8215                    PackageParser.ProviderIntentInfo[] array =
8216                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8217                    intentFilters.toArray(array);
8218                    listCut.add(array);
8219                }
8220            }
8221            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8222        }
8223
8224        public final void addProvider(PackageParser.Provider p) {
8225            if (mProviders.containsKey(p.getComponentName())) {
8226                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8227                return;
8228            }
8229
8230            mProviders.put(p.getComponentName(), p);
8231            if (DEBUG_SHOW_INFO) {
8232                Log.v(TAG, "  "
8233                        + (p.info.nonLocalizedLabel != null
8234                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8235                Log.v(TAG, "    Class=" + p.info.name);
8236            }
8237            final int NI = p.intents.size();
8238            int j;
8239            for (j = 0; j < NI; j++) {
8240                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8241                if (DEBUG_SHOW_INFO) {
8242                    Log.v(TAG, "    IntentFilter:");
8243                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8244                }
8245                if (!intent.debugCheck()) {
8246                    Log.w(TAG, "==> For Provider " + p.info.name);
8247                }
8248                addFilter(intent);
8249            }
8250        }
8251
8252        public final void removeProvider(PackageParser.Provider p) {
8253            mProviders.remove(p.getComponentName());
8254            if (DEBUG_SHOW_INFO) {
8255                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8256                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8257                Log.v(TAG, "    Class=" + p.info.name);
8258            }
8259            final int NI = p.intents.size();
8260            int j;
8261            for (j = 0; j < NI; j++) {
8262                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8263                if (DEBUG_SHOW_INFO) {
8264                    Log.v(TAG, "    IntentFilter:");
8265                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8266                }
8267                removeFilter(intent);
8268            }
8269        }
8270
8271        @Override
8272        protected boolean allowFilterResult(
8273                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8274            ProviderInfo filterPi = filter.provider.info;
8275            for (int i = dest.size() - 1; i >= 0; i--) {
8276                ProviderInfo destPi = dest.get(i).providerInfo;
8277                if (destPi.name == filterPi.name
8278                        && destPi.packageName == filterPi.packageName) {
8279                    return false;
8280                }
8281            }
8282            return true;
8283        }
8284
8285        @Override
8286        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8287            return new PackageParser.ProviderIntentInfo[size];
8288        }
8289
8290        @Override
8291        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8292            if (!sUserManager.exists(userId))
8293                return true;
8294            PackageParser.Package p = filter.provider.owner;
8295            if (p != null) {
8296                PackageSetting ps = (PackageSetting) p.mExtras;
8297                if (ps != null) {
8298                    // System apps are never considered stopped for purposes of
8299                    // filtering, because there may be no way for the user to
8300                    // actually re-launch them.
8301                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8302                            && ps.getStopped(userId);
8303                }
8304            }
8305            return false;
8306        }
8307
8308        @Override
8309        protected boolean isPackageForFilter(String packageName,
8310                PackageParser.ProviderIntentInfo info) {
8311            return packageName.equals(info.provider.owner.packageName);
8312        }
8313
8314        @Override
8315        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8316                int match, int userId) {
8317            if (!sUserManager.exists(userId))
8318                return null;
8319            final PackageParser.ProviderIntentInfo info = filter;
8320            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8321                return null;
8322            }
8323            final PackageParser.Provider provider = info.provider;
8324            if (mSafeMode && (provider.info.applicationInfo.flags
8325                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8326                return null;
8327            }
8328            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8329            if (ps == null) {
8330                return null;
8331            }
8332            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8333                    ps.readUserState(userId), userId);
8334            if (pi == null) {
8335                return null;
8336            }
8337            final ResolveInfo res = new ResolveInfo();
8338            res.providerInfo = pi;
8339            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8340                res.filter = filter;
8341            }
8342            res.priority = info.getPriority();
8343            res.preferredOrder = provider.owner.mPreferredOrder;
8344            res.match = match;
8345            res.isDefault = info.hasDefault;
8346            res.labelRes = info.labelRes;
8347            res.nonLocalizedLabel = info.nonLocalizedLabel;
8348            res.icon = info.icon;
8349            res.system = res.providerInfo.applicationInfo.isSystemApp();
8350            return res;
8351        }
8352
8353        @Override
8354        protected void sortResults(List<ResolveInfo> results) {
8355            Collections.sort(results, mResolvePrioritySorter);
8356        }
8357
8358        @Override
8359        protected void dumpFilter(PrintWriter out, String prefix,
8360                PackageParser.ProviderIntentInfo filter) {
8361            out.print(prefix);
8362            out.print(
8363                    Integer.toHexString(System.identityHashCode(filter.provider)));
8364            out.print(' ');
8365            filter.provider.printComponentShortName(out);
8366            out.print(" filter ");
8367            out.println(Integer.toHexString(System.identityHashCode(filter)));
8368        }
8369
8370        @Override
8371        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8372            return filter.provider;
8373        }
8374
8375        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8376            PackageParser.Provider provider = (PackageParser.Provider)label;
8377            out.print(prefix); out.print(
8378                    Integer.toHexString(System.identityHashCode(provider)));
8379                    out.print(' ');
8380                    provider.printComponentShortName(out);
8381            if (count > 1) {
8382                out.print(" ("); out.print(count); out.print(" filters)");
8383            }
8384            out.println();
8385        }
8386
8387        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8388                = new ArrayMap<ComponentName, PackageParser.Provider>();
8389        private int mFlags;
8390    };
8391
8392    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8393            new Comparator<ResolveInfo>() {
8394        public int compare(ResolveInfo r1, ResolveInfo r2) {
8395            int v1 = r1.priority;
8396            int v2 = r2.priority;
8397            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8398            if (v1 != v2) {
8399                return (v1 > v2) ? -1 : 1;
8400            }
8401            v1 = r1.preferredOrder;
8402            v2 = r2.preferredOrder;
8403            if (v1 != v2) {
8404                return (v1 > v2) ? -1 : 1;
8405            }
8406            if (r1.isDefault != r2.isDefault) {
8407                return r1.isDefault ? -1 : 1;
8408            }
8409            v1 = r1.match;
8410            v2 = r2.match;
8411            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8412            if (v1 != v2) {
8413                return (v1 > v2) ? -1 : 1;
8414            }
8415            if (r1.system != r2.system) {
8416                return r1.system ? -1 : 1;
8417            }
8418            return 0;
8419        }
8420    };
8421
8422    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8423            new Comparator<ProviderInfo>() {
8424        public int compare(ProviderInfo p1, ProviderInfo p2) {
8425            final int v1 = p1.initOrder;
8426            final int v2 = p2.initOrder;
8427            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8428        }
8429    };
8430
8431    static final void sendPackageBroadcast(String action, String pkg,
8432            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
8433            int[] userIds) {
8434        IActivityManager am = ActivityManagerNative.getDefault();
8435        if (am != null) {
8436            try {
8437                if (userIds == null) {
8438                    userIds = am.getRunningUserIds();
8439                }
8440                for (int id : userIds) {
8441                    final Intent intent = new Intent(action,
8442                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
8443                    if (extras != null) {
8444                        intent.putExtras(extras);
8445                    }
8446                    if (targetPkg != null) {
8447                        intent.setPackage(targetPkg);
8448                    }
8449                    // Modify the UID when posting to other users
8450                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8451                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
8452                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8453                        intent.putExtra(Intent.EXTRA_UID, uid);
8454                    }
8455                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8456                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8457                    if (DEBUG_BROADCASTS) {
8458                        RuntimeException here = new RuntimeException("here");
8459                        here.fillInStackTrace();
8460                        Slog.d(TAG, "Sending to user " + id + ": "
8461                                + intent.toShortString(false, true, false, false)
8462                                + " " + intent.getExtras(), here);
8463                    }
8464                    am.broadcastIntent(null, intent, null, finishedReceiver,
8465                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
8466                            finishedReceiver != null, false, id);
8467                }
8468            } catch (RemoteException ex) {
8469            }
8470        }
8471    }
8472
8473    /**
8474     * Check if the external storage media is available. This is true if there
8475     * is a mounted external storage medium or if the external storage is
8476     * emulated.
8477     */
8478    private boolean isExternalMediaAvailable() {
8479        return mMediaMounted || Environment.isExternalStorageEmulated();
8480    }
8481
8482    @Override
8483    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8484        // writer
8485        synchronized (mPackages) {
8486            if (!isExternalMediaAvailable()) {
8487                // If the external storage is no longer mounted at this point,
8488                // the caller may not have been able to delete all of this
8489                // packages files and can not delete any more.  Bail.
8490                return null;
8491            }
8492            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8493            if (lastPackage != null) {
8494                pkgs.remove(lastPackage);
8495            }
8496            if (pkgs.size() > 0) {
8497                return pkgs.get(0);
8498            }
8499        }
8500        return null;
8501    }
8502
8503    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8504        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8505                userId, andCode ? 1 : 0, packageName);
8506        if (mSystemReady) {
8507            msg.sendToTarget();
8508        } else {
8509            if (mPostSystemReadyMessages == null) {
8510                mPostSystemReadyMessages = new ArrayList<>();
8511            }
8512            mPostSystemReadyMessages.add(msg);
8513        }
8514    }
8515
8516    void startCleaningPackages() {
8517        // reader
8518        synchronized (mPackages) {
8519            if (!isExternalMediaAvailable()) {
8520                return;
8521            }
8522            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8523                return;
8524            }
8525        }
8526        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8527        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8528        IActivityManager am = ActivityManagerNative.getDefault();
8529        if (am != null) {
8530            try {
8531                am.startService(null, intent, null, UserHandle.USER_OWNER);
8532            } catch (RemoteException e) {
8533            }
8534        }
8535    }
8536
8537    @Override
8538    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8539            int installFlags, String installerPackageName, VerificationParams verificationParams,
8540            String packageAbiOverride) {
8541        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8542                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8543    }
8544
8545    @Override
8546    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8547            int installFlags, String installerPackageName, VerificationParams verificationParams,
8548            String packageAbiOverride, int userId) {
8549        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8550
8551        final int callingUid = Binder.getCallingUid();
8552        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8553
8554        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8555            try {
8556                if (observer != null) {
8557                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8558                }
8559            } catch (RemoteException re) {
8560            }
8561            return;
8562        }
8563
8564        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8565            installFlags |= PackageManager.INSTALL_FROM_ADB;
8566
8567        } else {
8568            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8569            // about installerPackageName.
8570
8571            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8572            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8573        }
8574
8575        UserHandle user;
8576        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8577            user = UserHandle.ALL;
8578        } else {
8579            user = new UserHandle(userId);
8580        }
8581
8582        // Only system components can circumvent runtime permissions when installing.
8583        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
8584                && mContext.checkCallingOrSelfPermission(Manifest.permission
8585                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
8586            throw new SecurityException("You need the "
8587                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
8588                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
8589        }
8590
8591        verificationParams.setInstallerUid(callingUid);
8592
8593        final File originFile = new File(originPath);
8594        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8595
8596        final Message msg = mHandler.obtainMessage(INIT_COPY);
8597        msg.obj = new InstallParams(origin, observer, installFlags,
8598                installerPackageName, null, verificationParams, user, packageAbiOverride);
8599        mHandler.sendMessage(msg);
8600    }
8601
8602    void installStage(String packageName, File stagedDir, String stagedCid,
8603            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8604            String installerPackageName, int installerUid, UserHandle user) {
8605        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8606                params.referrerUri, installerUid, null);
8607
8608        final OriginInfo origin;
8609        if (stagedDir != null) {
8610            origin = OriginInfo.fromStagedFile(stagedDir);
8611        } else {
8612            origin = OriginInfo.fromStagedContainer(stagedCid);
8613        }
8614
8615        final Message msg = mHandler.obtainMessage(INIT_COPY);
8616        msg.obj = new InstallParams(origin, observer, params.installFlags,
8617                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8618        mHandler.sendMessage(msg);
8619    }
8620
8621    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8622        Bundle extras = new Bundle(1);
8623        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8624
8625        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8626                packageName, extras, null, null, new int[] {userId});
8627        try {
8628            IActivityManager am = ActivityManagerNative.getDefault();
8629            final boolean isSystem =
8630                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8631            if (isSystem && am.isUserRunning(userId, false)) {
8632                // The just-installed/enabled app is bundled on the system, so presumed
8633                // to be able to run automatically without needing an explicit launch.
8634                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8635                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8636                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8637                        .setPackage(packageName);
8638                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8639                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8640            }
8641        } catch (RemoteException e) {
8642            // shouldn't happen
8643            Slog.w(TAG, "Unable to bootstrap installed package", e);
8644        }
8645    }
8646
8647    @Override
8648    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8649            int userId) {
8650        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8651        PackageSetting pkgSetting;
8652        final int uid = Binder.getCallingUid();
8653        enforceCrossUserPermission(uid, userId, true, true,
8654                "setApplicationHiddenSetting for user " + userId);
8655
8656        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8657            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8658            return false;
8659        }
8660
8661        long callingId = Binder.clearCallingIdentity();
8662        try {
8663            boolean sendAdded = false;
8664            boolean sendRemoved = false;
8665            // writer
8666            synchronized (mPackages) {
8667                pkgSetting = mSettings.mPackages.get(packageName);
8668                if (pkgSetting == null) {
8669                    return false;
8670                }
8671                if (pkgSetting.getHidden(userId) != hidden) {
8672                    pkgSetting.setHidden(hidden, userId);
8673                    mSettings.writePackageRestrictionsLPr(userId);
8674                    if (hidden) {
8675                        sendRemoved = true;
8676                    } else {
8677                        sendAdded = true;
8678                    }
8679                }
8680            }
8681            if (sendAdded) {
8682                sendPackageAddedForUser(packageName, pkgSetting, userId);
8683                return true;
8684            }
8685            if (sendRemoved) {
8686                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8687                        "hiding pkg");
8688                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8689            }
8690        } finally {
8691            Binder.restoreCallingIdentity(callingId);
8692        }
8693        return false;
8694    }
8695
8696    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8697            int userId) {
8698        final PackageRemovedInfo info = new PackageRemovedInfo();
8699        info.removedPackage = packageName;
8700        info.removedUsers = new int[] {userId};
8701        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8702        info.sendBroadcast(false, false, false);
8703    }
8704
8705    /**
8706     * Returns true if application is not found or there was an error. Otherwise it returns
8707     * the hidden state of the package for the given user.
8708     */
8709    @Override
8710    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8711        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8712        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8713                false, "getApplicationHidden for user " + userId);
8714        PackageSetting pkgSetting;
8715        long callingId = Binder.clearCallingIdentity();
8716        try {
8717            // writer
8718            synchronized (mPackages) {
8719                pkgSetting = mSettings.mPackages.get(packageName);
8720                if (pkgSetting == null) {
8721                    return true;
8722                }
8723                return pkgSetting.getHidden(userId);
8724            }
8725        } finally {
8726            Binder.restoreCallingIdentity(callingId);
8727        }
8728    }
8729
8730    /**
8731     * @hide
8732     */
8733    @Override
8734    public int installExistingPackageAsUser(String packageName, int userId) {
8735        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8736                null);
8737        PackageSetting pkgSetting;
8738        final int uid = Binder.getCallingUid();
8739        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8740                + userId);
8741        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8742            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8743        }
8744
8745        long callingId = Binder.clearCallingIdentity();
8746        try {
8747            boolean sendAdded = false;
8748
8749            // writer
8750            synchronized (mPackages) {
8751                pkgSetting = mSettings.mPackages.get(packageName);
8752                if (pkgSetting == null) {
8753                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8754                }
8755                if (!pkgSetting.getInstalled(userId)) {
8756                    pkgSetting.setInstalled(true, userId);
8757                    pkgSetting.setHidden(false, userId);
8758                    mSettings.writePackageRestrictionsLPr(userId);
8759                    sendAdded = true;
8760                }
8761            }
8762
8763            if (sendAdded) {
8764                sendPackageAddedForUser(packageName, pkgSetting, userId);
8765            }
8766        } finally {
8767            Binder.restoreCallingIdentity(callingId);
8768        }
8769
8770        return PackageManager.INSTALL_SUCCEEDED;
8771    }
8772
8773    boolean isUserRestricted(int userId, String restrictionKey) {
8774        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8775        if (restrictions.getBoolean(restrictionKey, false)) {
8776            Log.w(TAG, "User is restricted: " + restrictionKey);
8777            return true;
8778        }
8779        return false;
8780    }
8781
8782    @Override
8783    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8784        mContext.enforceCallingOrSelfPermission(
8785                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8786                "Only package verification agents can verify applications");
8787
8788        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8789        final PackageVerificationResponse response = new PackageVerificationResponse(
8790                verificationCode, Binder.getCallingUid());
8791        msg.arg1 = id;
8792        msg.obj = response;
8793        mHandler.sendMessage(msg);
8794    }
8795
8796    @Override
8797    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8798            long millisecondsToDelay) {
8799        mContext.enforceCallingOrSelfPermission(
8800                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8801                "Only package verification agents can extend verification timeouts");
8802
8803        final PackageVerificationState state = mPendingVerification.get(id);
8804        final PackageVerificationResponse response = new PackageVerificationResponse(
8805                verificationCodeAtTimeout, Binder.getCallingUid());
8806
8807        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8808            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8809        }
8810        if (millisecondsToDelay < 0) {
8811            millisecondsToDelay = 0;
8812        }
8813        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8814                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8815            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8816        }
8817
8818        if ((state != null) && !state.timeoutExtended()) {
8819            state.extendTimeout();
8820
8821            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8822            msg.arg1 = id;
8823            msg.obj = response;
8824            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8825        }
8826    }
8827
8828    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8829            int verificationCode, UserHandle user) {
8830        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8831        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8832        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8833        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8834        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8835
8836        mContext.sendBroadcastAsUser(intent, user,
8837                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8838    }
8839
8840    private ComponentName matchComponentForVerifier(String packageName,
8841            List<ResolveInfo> receivers) {
8842        ActivityInfo targetReceiver = null;
8843
8844        final int NR = receivers.size();
8845        for (int i = 0; i < NR; i++) {
8846            final ResolveInfo info = receivers.get(i);
8847            if (info.activityInfo == null) {
8848                continue;
8849            }
8850
8851            if (packageName.equals(info.activityInfo.packageName)) {
8852                targetReceiver = info.activityInfo;
8853                break;
8854            }
8855        }
8856
8857        if (targetReceiver == null) {
8858            return null;
8859        }
8860
8861        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8862    }
8863
8864    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8865            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8866        if (pkgInfo.verifiers.length == 0) {
8867            return null;
8868        }
8869
8870        final int N = pkgInfo.verifiers.length;
8871        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8872        for (int i = 0; i < N; i++) {
8873            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8874
8875            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8876                    receivers);
8877            if (comp == null) {
8878                continue;
8879            }
8880
8881            final int verifierUid = getUidForVerifier(verifierInfo);
8882            if (verifierUid == -1) {
8883                continue;
8884            }
8885
8886            if (DEBUG_VERIFY) {
8887                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8888                        + " with the correct signature");
8889            }
8890            sufficientVerifiers.add(comp);
8891            verificationState.addSufficientVerifier(verifierUid);
8892        }
8893
8894        return sufficientVerifiers;
8895    }
8896
8897    private int getUidForVerifier(VerifierInfo verifierInfo) {
8898        synchronized (mPackages) {
8899            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8900            if (pkg == null) {
8901                return -1;
8902            } else if (pkg.mSignatures.length != 1) {
8903                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8904                        + " has more than one signature; ignoring");
8905                return -1;
8906            }
8907
8908            /*
8909             * If the public key of the package's signature does not match
8910             * our expected public key, then this is a different package and
8911             * we should skip.
8912             */
8913
8914            final byte[] expectedPublicKey;
8915            try {
8916                final Signature verifierSig = pkg.mSignatures[0];
8917                final PublicKey publicKey = verifierSig.getPublicKey();
8918                expectedPublicKey = publicKey.getEncoded();
8919            } catch (CertificateException e) {
8920                return -1;
8921            }
8922
8923            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8924
8925            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8926                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8927                        + " does not have the expected public key; ignoring");
8928                return -1;
8929            }
8930
8931            return pkg.applicationInfo.uid;
8932        }
8933    }
8934
8935    @Override
8936    public void finishPackageInstall(int token) {
8937        enforceSystemOrRoot("Only the system is allowed to finish installs");
8938
8939        if (DEBUG_INSTALL) {
8940            Slog.v(TAG, "BM finishing package install for " + token);
8941        }
8942
8943        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8944        mHandler.sendMessage(msg);
8945    }
8946
8947    /**
8948     * Get the verification agent timeout.
8949     *
8950     * @return verification timeout in milliseconds
8951     */
8952    private long getVerificationTimeout() {
8953        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8954                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8955                DEFAULT_VERIFICATION_TIMEOUT);
8956    }
8957
8958    /**
8959     * Get the default verification agent response code.
8960     *
8961     * @return default verification response code
8962     */
8963    private int getDefaultVerificationResponse() {
8964        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8965                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8966                DEFAULT_VERIFICATION_RESPONSE);
8967    }
8968
8969    /**
8970     * Check whether or not package verification has been enabled.
8971     *
8972     * @return true if verification should be performed
8973     */
8974    private boolean isVerificationEnabled(int userId, int installFlags) {
8975        if (!DEFAULT_VERIFY_ENABLE) {
8976            return false;
8977        }
8978
8979        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8980
8981        // Check if installing from ADB
8982        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8983            // Do not run verification in a test harness environment
8984            if (ActivityManager.isRunningInTestHarness()) {
8985                return false;
8986            }
8987            if (ensureVerifyAppsEnabled) {
8988                return true;
8989            }
8990            // Check if the developer does not want package verification for ADB installs
8991            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8992                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8993                return false;
8994            }
8995        }
8996
8997        if (ensureVerifyAppsEnabled) {
8998            return true;
8999        }
9000
9001        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9002                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9003    }
9004
9005    @Override
9006    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9007            throws RemoteException {
9008        mContext.enforceCallingOrSelfPermission(
9009                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9010                "Only intentfilter verification agents can verify applications");
9011
9012        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9013        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9014                Binder.getCallingUid(), verificationCode, failedDomains);
9015        msg.arg1 = id;
9016        msg.obj = response;
9017        mHandler.sendMessage(msg);
9018    }
9019
9020    @Override
9021    public int getIntentVerificationStatus(String packageName, int userId) {
9022        synchronized (mPackages) {
9023            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9024        }
9025    }
9026
9027    @Override
9028    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9029        boolean result = false;
9030        synchronized (mPackages) {
9031            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9032        }
9033        scheduleWritePackageRestrictionsLocked(userId);
9034        return result;
9035    }
9036
9037    @Override
9038    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9039        synchronized (mPackages) {
9040            return mSettings.getIntentFilterVerificationsLPr(packageName);
9041        }
9042    }
9043
9044    @Override
9045    public List<IntentFilter> getAllIntentFilters(String packageName) {
9046        if (TextUtils.isEmpty(packageName)) {
9047            return Collections.<IntentFilter>emptyList();
9048        }
9049        synchronized (mPackages) {
9050            PackageParser.Package pkg = mPackages.get(packageName);
9051            if (pkg == null || pkg.activities == null) {
9052                return Collections.<IntentFilter>emptyList();
9053            }
9054            final int count = pkg.activities.size();
9055            ArrayList<IntentFilter> result = new ArrayList<>();
9056            for (int n=0; n<count; n++) {
9057                PackageParser.Activity activity = pkg.activities.get(n);
9058                if (activity.intents != null || activity.intents.size() > 0) {
9059                    result.addAll(activity.intents);
9060                }
9061            }
9062            return result;
9063        }
9064    }
9065
9066    @Override
9067    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9068        synchronized (mPackages) {
9069            return mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9070        }
9071    }
9072
9073    @Override
9074    public String getDefaultBrowserPackageName(int userId) {
9075        synchronized (mPackages) {
9076            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9077        }
9078    }
9079
9080    /**
9081     * Get the "allow unknown sources" setting.
9082     *
9083     * @return the current "allow unknown sources" setting
9084     */
9085    private int getUnknownSourcesSettings() {
9086        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9087                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9088                -1);
9089    }
9090
9091    @Override
9092    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9093        final int uid = Binder.getCallingUid();
9094        // writer
9095        synchronized (mPackages) {
9096            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9097            if (targetPackageSetting == null) {
9098                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9099            }
9100
9101            PackageSetting installerPackageSetting;
9102            if (installerPackageName != null) {
9103                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9104                if (installerPackageSetting == null) {
9105                    throw new IllegalArgumentException("Unknown installer package: "
9106                            + installerPackageName);
9107                }
9108            } else {
9109                installerPackageSetting = null;
9110            }
9111
9112            Signature[] callerSignature;
9113            Object obj = mSettings.getUserIdLPr(uid);
9114            if (obj != null) {
9115                if (obj instanceof SharedUserSetting) {
9116                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9117                } else if (obj instanceof PackageSetting) {
9118                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9119                } else {
9120                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9121                }
9122            } else {
9123                throw new SecurityException("Unknown calling uid " + uid);
9124            }
9125
9126            // Verify: can't set installerPackageName to a package that is
9127            // not signed with the same cert as the caller.
9128            if (installerPackageSetting != null) {
9129                if (compareSignatures(callerSignature,
9130                        installerPackageSetting.signatures.mSignatures)
9131                        != PackageManager.SIGNATURE_MATCH) {
9132                    throw new SecurityException(
9133                            "Caller does not have same cert as new installer package "
9134                            + installerPackageName);
9135                }
9136            }
9137
9138            // Verify: if target already has an installer package, it must
9139            // be signed with the same cert as the caller.
9140            if (targetPackageSetting.installerPackageName != null) {
9141                PackageSetting setting = mSettings.mPackages.get(
9142                        targetPackageSetting.installerPackageName);
9143                // If the currently set package isn't valid, then it's always
9144                // okay to change it.
9145                if (setting != null) {
9146                    if (compareSignatures(callerSignature,
9147                            setting.signatures.mSignatures)
9148                            != PackageManager.SIGNATURE_MATCH) {
9149                        throw new SecurityException(
9150                                "Caller does not have same cert as old installer package "
9151                                + targetPackageSetting.installerPackageName);
9152                    }
9153                }
9154            }
9155
9156            // Okay!
9157            targetPackageSetting.installerPackageName = installerPackageName;
9158            scheduleWriteSettingsLocked();
9159        }
9160    }
9161
9162    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9163        // Queue up an async operation since the package installation may take a little while.
9164        mHandler.post(new Runnable() {
9165            public void run() {
9166                mHandler.removeCallbacks(this);
9167                 // Result object to be returned
9168                PackageInstalledInfo res = new PackageInstalledInfo();
9169                res.returnCode = currentStatus;
9170                res.uid = -1;
9171                res.pkg = null;
9172                res.removedInfo = new PackageRemovedInfo();
9173                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9174                    args.doPreInstall(res.returnCode);
9175                    synchronized (mInstallLock) {
9176                        installPackageLI(args, res);
9177                    }
9178                    args.doPostInstall(res.returnCode, res.uid);
9179                }
9180
9181                // A restore should be performed at this point if (a) the install
9182                // succeeded, (b) the operation is not an update, and (c) the new
9183                // package has not opted out of backup participation.
9184                final boolean update = res.removedInfo.removedPackage != null;
9185                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9186                boolean doRestore = !update
9187                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9188
9189                // Set up the post-install work request bookkeeping.  This will be used
9190                // and cleaned up by the post-install event handling regardless of whether
9191                // there's a restore pass performed.  Token values are >= 1.
9192                int token;
9193                if (mNextInstallToken < 0) mNextInstallToken = 1;
9194                token = mNextInstallToken++;
9195
9196                PostInstallData data = new PostInstallData(args, res);
9197                mRunningInstalls.put(token, data);
9198                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9199
9200                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9201                    // Pass responsibility to the Backup Manager.  It will perform a
9202                    // restore if appropriate, then pass responsibility back to the
9203                    // Package Manager to run the post-install observer callbacks
9204                    // and broadcasts.
9205                    IBackupManager bm = IBackupManager.Stub.asInterface(
9206                            ServiceManager.getService(Context.BACKUP_SERVICE));
9207                    if (bm != null) {
9208                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9209                                + " to BM for possible restore");
9210                        try {
9211                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9212                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9213                            } else {
9214                                doRestore = false;
9215                            }
9216                        } catch (RemoteException e) {
9217                            // can't happen; the backup manager is local
9218                        } catch (Exception e) {
9219                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9220                            doRestore = false;
9221                        }
9222                    } else {
9223                        Slog.e(TAG, "Backup Manager not found!");
9224                        doRestore = false;
9225                    }
9226                }
9227
9228                if (!doRestore) {
9229                    // No restore possible, or the Backup Manager was mysteriously not
9230                    // available -- just fire the post-install work request directly.
9231                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9232                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9233                    mHandler.sendMessage(msg);
9234                }
9235            }
9236        });
9237    }
9238
9239    private abstract class HandlerParams {
9240        private static final int MAX_RETRIES = 4;
9241
9242        /**
9243         * Number of times startCopy() has been attempted and had a non-fatal
9244         * error.
9245         */
9246        private int mRetries = 0;
9247
9248        /** User handle for the user requesting the information or installation. */
9249        private final UserHandle mUser;
9250
9251        HandlerParams(UserHandle user) {
9252            mUser = user;
9253        }
9254
9255        UserHandle getUser() {
9256            return mUser;
9257        }
9258
9259        final boolean startCopy() {
9260            boolean res;
9261            try {
9262                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9263
9264                if (++mRetries > MAX_RETRIES) {
9265                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9266                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9267                    handleServiceError();
9268                    return false;
9269                } else {
9270                    handleStartCopy();
9271                    res = true;
9272                }
9273            } catch (RemoteException e) {
9274                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9275                mHandler.sendEmptyMessage(MCS_RECONNECT);
9276                res = false;
9277            }
9278            handleReturnCode();
9279            return res;
9280        }
9281
9282        final void serviceError() {
9283            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9284            handleServiceError();
9285            handleReturnCode();
9286        }
9287
9288        abstract void handleStartCopy() throws RemoteException;
9289        abstract void handleServiceError();
9290        abstract void handleReturnCode();
9291    }
9292
9293    class MeasureParams extends HandlerParams {
9294        private final PackageStats mStats;
9295        private boolean mSuccess;
9296
9297        private final IPackageStatsObserver mObserver;
9298
9299        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9300            super(new UserHandle(stats.userHandle));
9301            mObserver = observer;
9302            mStats = stats;
9303        }
9304
9305        @Override
9306        public String toString() {
9307            return "MeasureParams{"
9308                + Integer.toHexString(System.identityHashCode(this))
9309                + " " + mStats.packageName + "}";
9310        }
9311
9312        @Override
9313        void handleStartCopy() throws RemoteException {
9314            synchronized (mInstallLock) {
9315                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9316            }
9317
9318            if (mSuccess) {
9319                final boolean mounted;
9320                if (Environment.isExternalStorageEmulated()) {
9321                    mounted = true;
9322                } else {
9323                    final String status = Environment.getExternalStorageState();
9324                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9325                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9326                }
9327
9328                if (mounted) {
9329                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9330
9331                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9332                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9333
9334                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9335                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9336
9337                    // Always subtract cache size, since it's a subdirectory
9338                    mStats.externalDataSize -= mStats.externalCacheSize;
9339
9340                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9341                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9342
9343                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9344                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9345                }
9346            }
9347        }
9348
9349        @Override
9350        void handleReturnCode() {
9351            if (mObserver != null) {
9352                try {
9353                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9354                } catch (RemoteException e) {
9355                    Slog.i(TAG, "Observer no longer exists.");
9356                }
9357            }
9358        }
9359
9360        @Override
9361        void handleServiceError() {
9362            Slog.e(TAG, "Could not measure application " + mStats.packageName
9363                            + " external storage");
9364        }
9365    }
9366
9367    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9368            throws RemoteException {
9369        long result = 0;
9370        for (File path : paths) {
9371            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9372        }
9373        return result;
9374    }
9375
9376    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9377        for (File path : paths) {
9378            try {
9379                mcs.clearDirectory(path.getAbsolutePath());
9380            } catch (RemoteException e) {
9381            }
9382        }
9383    }
9384
9385    static class OriginInfo {
9386        /**
9387         * Location where install is coming from, before it has been
9388         * copied/renamed into place. This could be a single monolithic APK
9389         * file, or a cluster directory. This location may be untrusted.
9390         */
9391        final File file;
9392        final String cid;
9393
9394        /**
9395         * Flag indicating that {@link #file} or {@link #cid} has already been
9396         * staged, meaning downstream users don't need to defensively copy the
9397         * contents.
9398         */
9399        final boolean staged;
9400
9401        /**
9402         * Flag indicating that {@link #file} or {@link #cid} is an already
9403         * installed app that is being moved.
9404         */
9405        final boolean existing;
9406
9407        final String resolvedPath;
9408        final File resolvedFile;
9409
9410        static OriginInfo fromNothing() {
9411            return new OriginInfo(null, null, false, false);
9412        }
9413
9414        static OriginInfo fromUntrustedFile(File file) {
9415            return new OriginInfo(file, null, false, false);
9416        }
9417
9418        static OriginInfo fromExistingFile(File file) {
9419            return new OriginInfo(file, null, false, true);
9420        }
9421
9422        static OriginInfo fromStagedFile(File file) {
9423            return new OriginInfo(file, null, true, false);
9424        }
9425
9426        static OriginInfo fromStagedContainer(String cid) {
9427            return new OriginInfo(null, cid, true, false);
9428        }
9429
9430        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9431            this.file = file;
9432            this.cid = cid;
9433            this.staged = staged;
9434            this.existing = existing;
9435
9436            if (cid != null) {
9437                resolvedPath = PackageHelper.getSdDir(cid);
9438                resolvedFile = new File(resolvedPath);
9439            } else if (file != null) {
9440                resolvedPath = file.getAbsolutePath();
9441                resolvedFile = file;
9442            } else {
9443                resolvedPath = null;
9444                resolvedFile = null;
9445            }
9446        }
9447    }
9448
9449    class InstallParams extends HandlerParams {
9450        final OriginInfo origin;
9451        final IPackageInstallObserver2 observer;
9452        int installFlags;
9453        final String installerPackageName;
9454        final String volumeUuid;
9455        final VerificationParams verificationParams;
9456        private InstallArgs mArgs;
9457        private int mRet;
9458        final String packageAbiOverride;
9459
9460        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9461                String installerPackageName, String volumeUuid,
9462                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9463            super(user);
9464            this.origin = origin;
9465            this.observer = observer;
9466            this.installFlags = installFlags;
9467            this.installerPackageName = installerPackageName;
9468            this.volumeUuid = volumeUuid;
9469            this.verificationParams = verificationParams;
9470            this.packageAbiOverride = packageAbiOverride;
9471        }
9472
9473        @Override
9474        public String toString() {
9475            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9476                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9477        }
9478
9479        public ManifestDigest getManifestDigest() {
9480            if (verificationParams == null) {
9481                return null;
9482            }
9483            return verificationParams.getManifestDigest();
9484        }
9485
9486        private int installLocationPolicy(PackageInfoLite pkgLite) {
9487            String packageName = pkgLite.packageName;
9488            int installLocation = pkgLite.installLocation;
9489            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9490            // reader
9491            synchronized (mPackages) {
9492                PackageParser.Package pkg = mPackages.get(packageName);
9493                if (pkg != null) {
9494                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9495                        // Check for downgrading.
9496                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9497                            try {
9498                                checkDowngrade(pkg, pkgLite);
9499                            } catch (PackageManagerException e) {
9500                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9501                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9502                            }
9503                        }
9504                        // Check for updated system application.
9505                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9506                            if (onSd) {
9507                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9508                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9509                            }
9510                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9511                        } else {
9512                            if (onSd) {
9513                                // Install flag overrides everything.
9514                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9515                            }
9516                            // If current upgrade specifies particular preference
9517                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9518                                // Application explicitly specified internal.
9519                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9520                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9521                                // App explictly prefers external. Let policy decide
9522                            } else {
9523                                // Prefer previous location
9524                                if (isExternal(pkg)) {
9525                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9526                                }
9527                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9528                            }
9529                        }
9530                    } else {
9531                        // Invalid install. Return error code
9532                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9533                    }
9534                }
9535            }
9536            // All the special cases have been taken care of.
9537            // Return result based on recommended install location.
9538            if (onSd) {
9539                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9540            }
9541            return pkgLite.recommendedInstallLocation;
9542        }
9543
9544        /*
9545         * Invoke remote method to get package information and install
9546         * location values. Override install location based on default
9547         * policy if needed and then create install arguments based
9548         * on the install location.
9549         */
9550        public void handleStartCopy() throws RemoteException {
9551            int ret = PackageManager.INSTALL_SUCCEEDED;
9552
9553            // If we're already staged, we've firmly committed to an install location
9554            if (origin.staged) {
9555                if (origin.file != null) {
9556                    installFlags |= PackageManager.INSTALL_INTERNAL;
9557                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9558                } else if (origin.cid != null) {
9559                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9560                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9561                } else {
9562                    throw new IllegalStateException("Invalid stage location");
9563                }
9564            }
9565
9566            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9567            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9568
9569            PackageInfoLite pkgLite = null;
9570
9571            if (onInt && onSd) {
9572                // Check if both bits are set.
9573                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9574                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9575            } else {
9576                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9577                        packageAbiOverride);
9578
9579                /*
9580                 * If we have too little free space, try to free cache
9581                 * before giving up.
9582                 */
9583                if (!origin.staged && pkgLite.recommendedInstallLocation
9584                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9585                    // TODO: focus freeing disk space on the target device
9586                    final StorageManager storage = StorageManager.from(mContext);
9587                    final long lowThreshold = storage.getStorageLowBytes(
9588                            Environment.getDataDirectory());
9589
9590                    final long sizeBytes = mContainerService.calculateInstalledSize(
9591                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9592
9593                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
9594                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9595                                installFlags, packageAbiOverride);
9596                    }
9597
9598                    /*
9599                     * The cache free must have deleted the file we
9600                     * downloaded to install.
9601                     *
9602                     * TODO: fix the "freeCache" call to not delete
9603                     *       the file we care about.
9604                     */
9605                    if (pkgLite.recommendedInstallLocation
9606                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9607                        pkgLite.recommendedInstallLocation
9608                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9609                    }
9610                }
9611            }
9612
9613            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9614                int loc = pkgLite.recommendedInstallLocation;
9615                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9616                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9617                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9618                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9619                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9620                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9621                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9622                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9623                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9624                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9625                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9626                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9627                } else {
9628                    // Override with defaults if needed.
9629                    loc = installLocationPolicy(pkgLite);
9630                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9631                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9632                    } else if (!onSd && !onInt) {
9633                        // Override install location with flags
9634                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9635                            // Set the flag to install on external media.
9636                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9637                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9638                        } else {
9639                            // Make sure the flag for installing on external
9640                            // media is unset
9641                            installFlags |= PackageManager.INSTALL_INTERNAL;
9642                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9643                        }
9644                    }
9645                }
9646            }
9647
9648            final InstallArgs args = createInstallArgs(this);
9649            mArgs = args;
9650
9651            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9652                 /*
9653                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9654                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9655                 */
9656                int userIdentifier = getUser().getIdentifier();
9657                if (userIdentifier == UserHandle.USER_ALL
9658                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9659                    userIdentifier = UserHandle.USER_OWNER;
9660                }
9661
9662                /*
9663                 * Determine if we have any installed package verifiers. If we
9664                 * do, then we'll defer to them to verify the packages.
9665                 */
9666                final int requiredUid = mRequiredVerifierPackage == null ? -1
9667                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9668                if (!origin.existing && requiredUid != -1
9669                        && isVerificationEnabled(userIdentifier, installFlags)) {
9670                    final Intent verification = new Intent(
9671                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9672                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9673                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9674                            PACKAGE_MIME_TYPE);
9675                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9676
9677                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9678                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9679                            0 /* TODO: Which userId? */);
9680
9681                    if (DEBUG_VERIFY) {
9682                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9683                                + verification.toString() + " with " + pkgLite.verifiers.length
9684                                + " optional verifiers");
9685                    }
9686
9687                    final int verificationId = mPendingVerificationToken++;
9688
9689                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9690
9691                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9692                            installerPackageName);
9693
9694                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9695                            installFlags);
9696
9697                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9698                            pkgLite.packageName);
9699
9700                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9701                            pkgLite.versionCode);
9702
9703                    if (verificationParams != null) {
9704                        if (verificationParams.getVerificationURI() != null) {
9705                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9706                                 verificationParams.getVerificationURI());
9707                        }
9708                        if (verificationParams.getOriginatingURI() != null) {
9709                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9710                                  verificationParams.getOriginatingURI());
9711                        }
9712                        if (verificationParams.getReferrer() != null) {
9713                            verification.putExtra(Intent.EXTRA_REFERRER,
9714                                  verificationParams.getReferrer());
9715                        }
9716                        if (verificationParams.getOriginatingUid() >= 0) {
9717                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9718                                  verificationParams.getOriginatingUid());
9719                        }
9720                        if (verificationParams.getInstallerUid() >= 0) {
9721                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9722                                  verificationParams.getInstallerUid());
9723                        }
9724                    }
9725
9726                    final PackageVerificationState verificationState = new PackageVerificationState(
9727                            requiredUid, args);
9728
9729                    mPendingVerification.append(verificationId, verificationState);
9730
9731                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9732                            receivers, verificationState);
9733
9734                    /*
9735                     * If any sufficient verifiers were listed in the package
9736                     * manifest, attempt to ask them.
9737                     */
9738                    if (sufficientVerifiers != null) {
9739                        final int N = sufficientVerifiers.size();
9740                        if (N == 0) {
9741                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9742                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9743                        } else {
9744                            for (int i = 0; i < N; i++) {
9745                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9746
9747                                final Intent sufficientIntent = new Intent(verification);
9748                                sufficientIntent.setComponent(verifierComponent);
9749
9750                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9751                            }
9752                        }
9753                    }
9754
9755                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9756                            mRequiredVerifierPackage, receivers);
9757                    if (ret == PackageManager.INSTALL_SUCCEEDED
9758                            && mRequiredVerifierPackage != null) {
9759                        /*
9760                         * Send the intent to the required verification agent,
9761                         * but only start the verification timeout after the
9762                         * target BroadcastReceivers have run.
9763                         */
9764                        verification.setComponent(requiredVerifierComponent);
9765                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9766                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9767                                new BroadcastReceiver() {
9768                                    @Override
9769                                    public void onReceive(Context context, Intent intent) {
9770                                        final Message msg = mHandler
9771                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9772                                        msg.arg1 = verificationId;
9773                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9774                                    }
9775                                }, null, 0, null, null);
9776
9777                        /*
9778                         * We don't want the copy to proceed until verification
9779                         * succeeds, so null out this field.
9780                         */
9781                        mArgs = null;
9782                    }
9783                } else {
9784                    /*
9785                     * No package verification is enabled, so immediately start
9786                     * the remote call to initiate copy using temporary file.
9787                     */
9788                    ret = args.copyApk(mContainerService, true);
9789                }
9790            }
9791
9792            mRet = ret;
9793        }
9794
9795        @Override
9796        void handleReturnCode() {
9797            // If mArgs is null, then MCS couldn't be reached. When it
9798            // reconnects, it will try again to install. At that point, this
9799            // will succeed.
9800            if (mArgs != null) {
9801                processPendingInstall(mArgs, mRet);
9802            }
9803        }
9804
9805        @Override
9806        void handleServiceError() {
9807            mArgs = createInstallArgs(this);
9808            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9809        }
9810
9811        public boolean isForwardLocked() {
9812            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9813        }
9814    }
9815
9816    /**
9817     * Used during creation of InstallArgs
9818     *
9819     * @param installFlags package installation flags
9820     * @return true if should be installed on external storage
9821     */
9822    private static boolean installOnExternalAsec(int installFlags) {
9823        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9824            return false;
9825        }
9826        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9827            return true;
9828        }
9829        return false;
9830    }
9831
9832    /**
9833     * Used during creation of InstallArgs
9834     *
9835     * @param installFlags package installation flags
9836     * @return true if should be installed as forward locked
9837     */
9838    private static boolean installForwardLocked(int installFlags) {
9839        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9840    }
9841
9842    private InstallArgs createInstallArgs(InstallParams params) {
9843        if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
9844            return new AsecInstallArgs(params);
9845        } else {
9846            return new FileInstallArgs(params);
9847        }
9848    }
9849
9850    /**
9851     * Create args that describe an existing installed package. Typically used
9852     * when cleaning up old installs, or used as a move source.
9853     */
9854    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9855            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9856        final boolean isInAsec;
9857        if (installOnExternalAsec(installFlags)) {
9858            /* Apps on SD card are always in ASEC containers. */
9859            isInAsec = true;
9860        } else if (installForwardLocked(installFlags)
9861                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9862            /*
9863             * Forward-locked apps are only in ASEC containers if they're the
9864             * new style
9865             */
9866            isInAsec = true;
9867        } else {
9868            isInAsec = false;
9869        }
9870
9871        if (isInAsec) {
9872            return new AsecInstallArgs(codePath, instructionSets,
9873                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
9874        } else {
9875            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9876                    instructionSets);
9877        }
9878    }
9879
9880    static abstract class InstallArgs {
9881        /** @see InstallParams#origin */
9882        final OriginInfo origin;
9883
9884        final IPackageInstallObserver2 observer;
9885        // Always refers to PackageManager flags only
9886        final int installFlags;
9887        final String installerPackageName;
9888        final String volumeUuid;
9889        final ManifestDigest manifestDigest;
9890        final UserHandle user;
9891        final String abiOverride;
9892
9893        // The list of instruction sets supported by this app. This is currently
9894        // only used during the rmdex() phase to clean up resources. We can get rid of this
9895        // if we move dex files under the common app path.
9896        /* nullable */ String[] instructionSets;
9897
9898        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9899                String installerPackageName, String volumeUuid, ManifestDigest manifestDigest,
9900                UserHandle user, String[] instructionSets, String abiOverride) {
9901            this.origin = origin;
9902            this.installFlags = installFlags;
9903            this.observer = observer;
9904            this.installerPackageName = installerPackageName;
9905            this.volumeUuid = volumeUuid;
9906            this.manifestDigest = manifestDigest;
9907            this.user = user;
9908            this.instructionSets = instructionSets;
9909            this.abiOverride = abiOverride;
9910        }
9911
9912        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9913        abstract int doPreInstall(int status);
9914
9915        /**
9916         * Rename package into final resting place. All paths on the given
9917         * scanned package should be updated to reflect the rename.
9918         */
9919        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9920        abstract int doPostInstall(int status, int uid);
9921
9922        /** @see PackageSettingBase#codePathString */
9923        abstract String getCodePath();
9924        /** @see PackageSettingBase#resourcePathString */
9925        abstract String getResourcePath();
9926        abstract String getLegacyNativeLibraryPath();
9927
9928        // Need installer lock especially for dex file removal.
9929        abstract void cleanUpResourcesLI();
9930        abstract boolean doPostDeleteLI(boolean delete);
9931        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9932
9933        /**
9934         * Called before the source arguments are copied. This is used mostly
9935         * for MoveParams when it needs to read the source file to put it in the
9936         * destination.
9937         */
9938        int doPreCopy() {
9939            return PackageManager.INSTALL_SUCCEEDED;
9940        }
9941
9942        /**
9943         * Called after the source arguments are copied. This is used mostly for
9944         * MoveParams when it needs to read the source file to put it in the
9945         * destination.
9946         *
9947         * @return
9948         */
9949        int doPostCopy(int uid) {
9950            return PackageManager.INSTALL_SUCCEEDED;
9951        }
9952
9953        protected boolean isFwdLocked() {
9954            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9955        }
9956
9957        protected boolean isExternalAsec() {
9958            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9959        }
9960
9961        UserHandle getUser() {
9962            return user;
9963        }
9964    }
9965
9966    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
9967        if (!allCodePaths.isEmpty()) {
9968            if (instructionSets == null) {
9969                throw new IllegalStateException("instructionSet == null");
9970            }
9971            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9972            for (String codePath : allCodePaths) {
9973                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9974                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9975                    if (retCode < 0) {
9976                        Slog.w(TAG, "Couldn't remove dex file for package: "
9977                                + " at location " + codePath + ", retcode=" + retCode);
9978                        // we don't consider this to be a failure of the core package deletion
9979                    }
9980                }
9981            }
9982        }
9983    }
9984
9985    /**
9986     * Logic to handle installation of non-ASEC applications, including copying
9987     * and renaming logic.
9988     */
9989    class FileInstallArgs extends InstallArgs {
9990        private File codeFile;
9991        private File resourceFile;
9992        private File legacyNativeLibraryPath;
9993
9994        // Example topology:
9995        // /data/app/com.example/base.apk
9996        // /data/app/com.example/split_foo.apk
9997        // /data/app/com.example/lib/arm/libfoo.so
9998        // /data/app/com.example/lib/arm64/libfoo.so
9999        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10000
10001        /** New install */
10002        FileInstallArgs(InstallParams params) {
10003            super(params.origin, params.observer, params.installFlags,
10004                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10005                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10006            if (isFwdLocked()) {
10007                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10008            }
10009        }
10010
10011        /** Existing install */
10012        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
10013                String[] instructionSets) {
10014            super(OriginInfo.fromNothing(), null, 0, null, null, null, null, instructionSets, null);
10015            this.codeFile = (codePath != null) ? new File(codePath) : null;
10016            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10017            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
10018                    new File(legacyNativeLibraryPath) : null;
10019        }
10020
10021        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
10022            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
10023                    isFwdLocked(), abiOverride);
10024
10025            final StorageManager storage = StorageManager.from(mContext);
10026            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
10027        }
10028
10029        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10030            if (origin.staged) {
10031                Slog.d(TAG, origin.file + " already staged; skipping copy");
10032                codeFile = origin.file;
10033                resourceFile = origin.file;
10034                return PackageManager.INSTALL_SUCCEEDED;
10035            }
10036
10037            try {
10038                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10039                codeFile = tempDir;
10040                resourceFile = tempDir;
10041            } catch (IOException e) {
10042                Slog.w(TAG, "Failed to create copy file: " + e);
10043                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10044            }
10045
10046            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10047                @Override
10048                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10049                    if (!FileUtils.isValidExtFilename(name)) {
10050                        throw new IllegalArgumentException("Invalid filename: " + name);
10051                    }
10052                    try {
10053                        final File file = new File(codeFile, name);
10054                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10055                                O_RDWR | O_CREAT, 0644);
10056                        Os.chmod(file.getAbsolutePath(), 0644);
10057                        return new ParcelFileDescriptor(fd);
10058                    } catch (ErrnoException e) {
10059                        throw new RemoteException("Failed to open: " + e.getMessage());
10060                    }
10061                }
10062            };
10063
10064            int ret = PackageManager.INSTALL_SUCCEEDED;
10065            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10066            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10067                Slog.e(TAG, "Failed to copy package");
10068                return ret;
10069            }
10070
10071            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10072            NativeLibraryHelper.Handle handle = null;
10073            try {
10074                handle = NativeLibraryHelper.Handle.create(codeFile);
10075                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10076                        abiOverride);
10077            } catch (IOException e) {
10078                Slog.e(TAG, "Copying native libraries failed", e);
10079                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10080            } finally {
10081                IoUtils.closeQuietly(handle);
10082            }
10083
10084            return ret;
10085        }
10086
10087        int doPreInstall(int status) {
10088            if (status != PackageManager.INSTALL_SUCCEEDED) {
10089                cleanUp();
10090            }
10091            return status;
10092        }
10093
10094        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10095            if (status != PackageManager.INSTALL_SUCCEEDED) {
10096                cleanUp();
10097                return false;
10098            } else {
10099                final File targetDir = codeFile.getParentFile();
10100                final File beforeCodeFile = codeFile;
10101                final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10102
10103                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10104                try {
10105                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10106                } catch (ErrnoException e) {
10107                    Slog.d(TAG, "Failed to rename", e);
10108                    return false;
10109                }
10110
10111                if (!SELinux.restoreconRecursive(afterCodeFile)) {
10112                    Slog.d(TAG, "Failed to restorecon");
10113                    return false;
10114                }
10115
10116                // Reflect the rename internally
10117                codeFile = afterCodeFile;
10118                resourceFile = afterCodeFile;
10119
10120                // Reflect the rename in scanned details
10121                pkg.codePath = afterCodeFile.getAbsolutePath();
10122                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10123                        pkg.baseCodePath);
10124                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10125                        pkg.splitCodePaths);
10126
10127                // Reflect the rename in app info
10128                pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10129                pkg.applicationInfo.setCodePath(pkg.codePath);
10130                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10131                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10132                pkg.applicationInfo.setResourcePath(pkg.codePath);
10133                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10134                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10135
10136                return true;
10137            }
10138        }
10139
10140        int doPostInstall(int status, int uid) {
10141            if (status != PackageManager.INSTALL_SUCCEEDED) {
10142                cleanUp();
10143            }
10144            return status;
10145        }
10146
10147        @Override
10148        String getCodePath() {
10149            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10150        }
10151
10152        @Override
10153        String getResourcePath() {
10154            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10155        }
10156
10157        @Override
10158        String getLegacyNativeLibraryPath() {
10159            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
10160        }
10161
10162        private boolean cleanUp() {
10163            if (codeFile == null || !codeFile.exists()) {
10164                return false;
10165            }
10166
10167            if (codeFile.isDirectory()) {
10168                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10169            } else {
10170                codeFile.delete();
10171            }
10172
10173            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10174                resourceFile.delete();
10175            }
10176
10177            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
10178                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
10179                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
10180                }
10181                legacyNativeLibraryPath.delete();
10182            }
10183
10184            return true;
10185        }
10186
10187        void cleanUpResourcesLI() {
10188            // Try enumerating all code paths before deleting
10189            List<String> allCodePaths = Collections.EMPTY_LIST;
10190            if (codeFile != null && codeFile.exists()) {
10191                try {
10192                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10193                    allCodePaths = pkg.getAllCodePaths();
10194                } catch (PackageParserException e) {
10195                    // Ignored; we tried our best
10196                }
10197            }
10198
10199            cleanUp();
10200            removeDexFiles(allCodePaths, instructionSets);
10201        }
10202
10203        boolean doPostDeleteLI(boolean delete) {
10204            // XXX err, shouldn't we respect the delete flag?
10205            cleanUpResourcesLI();
10206            return true;
10207        }
10208    }
10209
10210    private boolean isAsecExternal(String cid) {
10211        final String asecPath = PackageHelper.getSdFilesystem(cid);
10212        return !asecPath.startsWith(mAsecInternalPath);
10213    }
10214
10215    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10216            PackageManagerException {
10217        if (copyRet < 0) {
10218            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10219                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10220                throw new PackageManagerException(copyRet, message);
10221            }
10222        }
10223    }
10224
10225    /**
10226     * Extract the MountService "container ID" from the full code path of an
10227     * .apk.
10228     */
10229    static String cidFromCodePath(String fullCodePath) {
10230        int eidx = fullCodePath.lastIndexOf("/");
10231        String subStr1 = fullCodePath.substring(0, eidx);
10232        int sidx = subStr1.lastIndexOf("/");
10233        return subStr1.substring(sidx+1, eidx);
10234    }
10235
10236    /**
10237     * Logic to handle installation of ASEC applications, including copying and
10238     * renaming logic.
10239     */
10240    class AsecInstallArgs extends InstallArgs {
10241        static final String RES_FILE_NAME = "pkg.apk";
10242        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10243
10244        String cid;
10245        String packagePath;
10246        String resourcePath;
10247        String legacyNativeLibraryDir;
10248
10249        /** New install */
10250        AsecInstallArgs(InstallParams params) {
10251            super(params.origin, params.observer, params.installFlags,
10252                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10253                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10254        }
10255
10256        /** Existing install */
10257        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10258                        boolean isExternal, boolean isForwardLocked) {
10259            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
10260                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10261                    instructionSets, null);
10262            // Hackily pretend we're still looking at a full code path
10263            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10264                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10265            }
10266
10267            // Extract cid from fullCodePath
10268            int eidx = fullCodePath.lastIndexOf("/");
10269            String subStr1 = fullCodePath.substring(0, eidx);
10270            int sidx = subStr1.lastIndexOf("/");
10271            cid = subStr1.substring(sidx+1, eidx);
10272            setMountPath(subStr1);
10273        }
10274
10275        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10276            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10277                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10278                    instructionSets, null);
10279            this.cid = cid;
10280            setMountPath(PackageHelper.getSdDir(cid));
10281        }
10282
10283        void createCopyFile() {
10284            cid = mInstallerService.allocateExternalStageCidLegacy();
10285        }
10286
10287        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
10288            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
10289                    abiOverride);
10290
10291            final File target;
10292            if (isExternalAsec()) {
10293                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
10294            } else {
10295                target = Environment.getDataDirectory();
10296            }
10297
10298            final StorageManager storage = StorageManager.from(mContext);
10299            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
10300        }
10301
10302        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10303            if (origin.staged) {
10304                Slog.d(TAG, origin.cid + " already staged; skipping copy");
10305                cid = origin.cid;
10306                setMountPath(PackageHelper.getSdDir(cid));
10307                return PackageManager.INSTALL_SUCCEEDED;
10308            }
10309
10310            if (temp) {
10311                createCopyFile();
10312            } else {
10313                /*
10314                 * Pre-emptively destroy the container since it's destroyed if
10315                 * copying fails due to it existing anyway.
10316                 */
10317                PackageHelper.destroySdDir(cid);
10318            }
10319
10320            final String newMountPath = imcs.copyPackageToContainer(
10321                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10322                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10323
10324            if (newMountPath != null) {
10325                setMountPath(newMountPath);
10326                return PackageManager.INSTALL_SUCCEEDED;
10327            } else {
10328                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10329            }
10330        }
10331
10332        @Override
10333        String getCodePath() {
10334            return packagePath;
10335        }
10336
10337        @Override
10338        String getResourcePath() {
10339            return resourcePath;
10340        }
10341
10342        @Override
10343        String getLegacyNativeLibraryPath() {
10344            return legacyNativeLibraryDir;
10345        }
10346
10347        int doPreInstall(int status) {
10348            if (status != PackageManager.INSTALL_SUCCEEDED) {
10349                // Destroy container
10350                PackageHelper.destroySdDir(cid);
10351            } else {
10352                boolean mounted = PackageHelper.isContainerMounted(cid);
10353                if (!mounted) {
10354                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10355                            Process.SYSTEM_UID);
10356                    if (newMountPath != null) {
10357                        setMountPath(newMountPath);
10358                    } else {
10359                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10360                    }
10361                }
10362            }
10363            return status;
10364        }
10365
10366        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10367            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10368            String newMountPath = null;
10369            if (PackageHelper.isContainerMounted(cid)) {
10370                // Unmount the container
10371                if (!PackageHelper.unMountSdDir(cid)) {
10372                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10373                    return false;
10374                }
10375            }
10376            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10377                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10378                        " which might be stale. Will try to clean up.");
10379                // Clean up the stale container and proceed to recreate.
10380                if (!PackageHelper.destroySdDir(newCacheId)) {
10381                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10382                    return false;
10383                }
10384                // Successfully cleaned up stale container. Try to rename again.
10385                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10386                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10387                            + " inspite of cleaning it up.");
10388                    return false;
10389                }
10390            }
10391            if (!PackageHelper.isContainerMounted(newCacheId)) {
10392                Slog.w(TAG, "Mounting container " + newCacheId);
10393                newMountPath = PackageHelper.mountSdDir(newCacheId,
10394                        getEncryptKey(), Process.SYSTEM_UID);
10395            } else {
10396                newMountPath = PackageHelper.getSdDir(newCacheId);
10397            }
10398            if (newMountPath == null) {
10399                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10400                return false;
10401            }
10402            Log.i(TAG, "Succesfully renamed " + cid +
10403                    " to " + newCacheId +
10404                    " at new path: " + newMountPath);
10405            cid = newCacheId;
10406
10407            final File beforeCodeFile = new File(packagePath);
10408            setMountPath(newMountPath);
10409            final File afterCodeFile = new File(packagePath);
10410
10411            // Reflect the rename in scanned details
10412            pkg.codePath = afterCodeFile.getAbsolutePath();
10413            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10414                    pkg.baseCodePath);
10415            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10416                    pkg.splitCodePaths);
10417
10418            // Reflect the rename in app info
10419            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10420            pkg.applicationInfo.setCodePath(pkg.codePath);
10421            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10422            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10423            pkg.applicationInfo.setResourcePath(pkg.codePath);
10424            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10425            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10426
10427            return true;
10428        }
10429
10430        private void setMountPath(String mountPath) {
10431            final File mountFile = new File(mountPath);
10432
10433            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10434            if (monolithicFile.exists()) {
10435                packagePath = monolithicFile.getAbsolutePath();
10436                if (isFwdLocked()) {
10437                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10438                } else {
10439                    resourcePath = packagePath;
10440                }
10441            } else {
10442                packagePath = mountFile.getAbsolutePath();
10443                resourcePath = packagePath;
10444            }
10445
10446            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
10447        }
10448
10449        int doPostInstall(int status, int uid) {
10450            if (status != PackageManager.INSTALL_SUCCEEDED) {
10451                cleanUp();
10452            } else {
10453                final int groupOwner;
10454                final String protectedFile;
10455                if (isFwdLocked()) {
10456                    groupOwner = UserHandle.getSharedAppGid(uid);
10457                    protectedFile = RES_FILE_NAME;
10458                } else {
10459                    groupOwner = -1;
10460                    protectedFile = null;
10461                }
10462
10463                if (uid < Process.FIRST_APPLICATION_UID
10464                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10465                    Slog.e(TAG, "Failed to finalize " + cid);
10466                    PackageHelper.destroySdDir(cid);
10467                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10468                }
10469
10470                boolean mounted = PackageHelper.isContainerMounted(cid);
10471                if (!mounted) {
10472                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10473                }
10474            }
10475            return status;
10476        }
10477
10478        private void cleanUp() {
10479            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10480
10481            // Destroy secure container
10482            PackageHelper.destroySdDir(cid);
10483        }
10484
10485        private List<String> getAllCodePaths() {
10486            final File codeFile = new File(getCodePath());
10487            if (codeFile != null && codeFile.exists()) {
10488                try {
10489                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10490                    return pkg.getAllCodePaths();
10491                } catch (PackageParserException e) {
10492                    // Ignored; we tried our best
10493                }
10494            }
10495            return Collections.EMPTY_LIST;
10496        }
10497
10498        void cleanUpResourcesLI() {
10499            // Enumerate all code paths before deleting
10500            cleanUpResourcesLI(getAllCodePaths());
10501        }
10502
10503        private void cleanUpResourcesLI(List<String> allCodePaths) {
10504            cleanUp();
10505            removeDexFiles(allCodePaths, instructionSets);
10506        }
10507
10508
10509
10510        String getPackageName() {
10511            return getAsecPackageName(cid);
10512        }
10513
10514        boolean doPostDeleteLI(boolean delete) {
10515            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10516            final List<String> allCodePaths = getAllCodePaths();
10517            boolean mounted = PackageHelper.isContainerMounted(cid);
10518            if (mounted) {
10519                // Unmount first
10520                if (PackageHelper.unMountSdDir(cid)) {
10521                    mounted = false;
10522                }
10523            }
10524            if (!mounted && delete) {
10525                cleanUpResourcesLI(allCodePaths);
10526            }
10527            return !mounted;
10528        }
10529
10530        @Override
10531        int doPreCopy() {
10532            if (isFwdLocked()) {
10533                if (!PackageHelper.fixSdPermissions(cid,
10534                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10535                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10536                }
10537            }
10538
10539            return PackageManager.INSTALL_SUCCEEDED;
10540        }
10541
10542        @Override
10543        int doPostCopy(int uid) {
10544            if (isFwdLocked()) {
10545                if (uid < Process.FIRST_APPLICATION_UID
10546                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10547                                RES_FILE_NAME)) {
10548                    Slog.e(TAG, "Failed to finalize " + cid);
10549                    PackageHelper.destroySdDir(cid);
10550                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10551                }
10552            }
10553
10554            return PackageManager.INSTALL_SUCCEEDED;
10555        }
10556    }
10557
10558    static String getAsecPackageName(String packageCid) {
10559        int idx = packageCid.lastIndexOf("-");
10560        if (idx == -1) {
10561            return packageCid;
10562        }
10563        return packageCid.substring(0, idx);
10564    }
10565
10566    // Utility method used to create code paths based on package name and available index.
10567    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
10568        String idxStr = "";
10569        int idx = 1;
10570        // Fall back to default value of idx=1 if prefix is not
10571        // part of oldCodePath
10572        if (oldCodePath != null) {
10573            String subStr = oldCodePath;
10574            // Drop the suffix right away
10575            if (suffix != null && subStr.endsWith(suffix)) {
10576                subStr = subStr.substring(0, subStr.length() - suffix.length());
10577            }
10578            // If oldCodePath already contains prefix find out the
10579            // ending index to either increment or decrement.
10580            int sidx = subStr.lastIndexOf(prefix);
10581            if (sidx != -1) {
10582                subStr = subStr.substring(sidx + prefix.length());
10583                if (subStr != null) {
10584                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10585                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10586                    }
10587                    try {
10588                        idx = Integer.parseInt(subStr);
10589                        if (idx <= 1) {
10590                            idx++;
10591                        } else {
10592                            idx--;
10593                        }
10594                    } catch(NumberFormatException e) {
10595                    }
10596                }
10597            }
10598        }
10599        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10600        return prefix + idxStr;
10601    }
10602
10603    private File getNextCodePath(File targetDir, String packageName) {
10604        int suffix = 1;
10605        File result;
10606        do {
10607            result = new File(targetDir, packageName + "-" + suffix);
10608            suffix++;
10609        } while (result.exists());
10610        return result;
10611    }
10612
10613    // Utility method that returns the relative package path with respect
10614    // to the installation directory. Like say for /data/data/com.test-1.apk
10615    // string com.test-1 is returned.
10616    static String deriveCodePathName(String codePath) {
10617        if (codePath == null) {
10618            return null;
10619        }
10620        final File codeFile = new File(codePath);
10621        final String name = codeFile.getName();
10622        if (codeFile.isDirectory()) {
10623            return name;
10624        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10625            final int lastDot = name.lastIndexOf('.');
10626            return name.substring(0, lastDot);
10627        } else {
10628            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10629            return null;
10630        }
10631    }
10632
10633    class PackageInstalledInfo {
10634        String name;
10635        int uid;
10636        // The set of users that originally had this package installed.
10637        int[] origUsers;
10638        // The set of users that now have this package installed.
10639        int[] newUsers;
10640        PackageParser.Package pkg;
10641        int returnCode;
10642        String returnMsg;
10643        PackageRemovedInfo removedInfo;
10644
10645        public void setError(int code, String msg) {
10646            returnCode = code;
10647            returnMsg = msg;
10648            Slog.w(TAG, msg);
10649        }
10650
10651        public void setError(String msg, PackageParserException e) {
10652            returnCode = e.error;
10653            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10654            Slog.w(TAG, msg, e);
10655        }
10656
10657        public void setError(String msg, PackageManagerException e) {
10658            returnCode = e.error;
10659            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10660            Slog.w(TAG, msg, e);
10661        }
10662
10663        // In some error cases we want to convey more info back to the observer
10664        String origPackage;
10665        String origPermission;
10666    }
10667
10668    /*
10669     * Install a non-existing package.
10670     */
10671    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
10672            UserHandle user, String installerPackageName, String volumeUuid,
10673            PackageInstalledInfo res) {
10674        // Remember this for later, in case we need to rollback this install
10675        String pkgName = pkg.packageName;
10676
10677        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10678        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
10679                UserHandle.USER_OWNER).exists();
10680        synchronized(mPackages) {
10681            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10682                // A package with the same name is already installed, though
10683                // it has been renamed to an older name.  The package we
10684                // are trying to install should be installed as an update to
10685                // the existing one, but that has not been requested, so bail.
10686                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10687                        + " without first uninstalling package running as "
10688                        + mSettings.mRenamedPackages.get(pkgName));
10689                return;
10690            }
10691            if (mPackages.containsKey(pkgName)) {
10692                // Don't allow installation over an existing package with the same name.
10693                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10694                        + " without first uninstalling.");
10695                return;
10696            }
10697        }
10698
10699        try {
10700            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10701                    System.currentTimeMillis(), user);
10702
10703            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
10704            // delete the partially installed application. the data directory will have to be
10705            // restored if it was already existing
10706            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10707                // remove package from internal structures.  Note that we want deletePackageX to
10708                // delete the package data and cache directories that it created in
10709                // scanPackageLocked, unless those directories existed before we even tried to
10710                // install.
10711                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10712                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10713                                res.removedInfo, true);
10714            }
10715
10716        } catch (PackageManagerException e) {
10717            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10718        }
10719    }
10720
10721    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10722        // Upgrade keysets are being used.  Determine if new package has a superset of the
10723        // required keys.
10724        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10725        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10726        for (int i = 0; i < upgradeKeySets.length; i++) {
10727            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10728            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10729                return true;
10730            }
10731        }
10732        return false;
10733    }
10734
10735    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
10736            UserHandle user, String installerPackageName, String volumeUuid,
10737            PackageInstalledInfo res) {
10738        PackageParser.Package oldPackage;
10739        String pkgName = pkg.packageName;
10740        int[] allUsers;
10741        boolean[] perUserInstalled;
10742
10743        // First find the old package info and check signatures
10744        synchronized(mPackages) {
10745            oldPackage = mPackages.get(pkgName);
10746            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10747            PackageSetting ps = mSettings.mPackages.get(pkgName);
10748            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10749                // default to original signature matching
10750                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10751                    != PackageManager.SIGNATURE_MATCH) {
10752                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10753                            "New package has a different signature: " + pkgName);
10754                    return;
10755                }
10756            } else {
10757                if(!checkUpgradeKeySetLP(ps, pkg)) {
10758                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10759                            "New package not signed by keys specified by upgrade-keysets: "
10760                            + pkgName);
10761                    return;
10762                }
10763            }
10764
10765            // In case of rollback, remember per-user/profile install state
10766            allUsers = sUserManager.getUserIds();
10767            perUserInstalled = new boolean[allUsers.length];
10768            for (int i = 0; i < allUsers.length; i++) {
10769                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10770            }
10771        }
10772
10773        boolean sysPkg = (isSystemApp(oldPackage));
10774        if (sysPkg) {
10775            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10776                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
10777        } else {
10778            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10779                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
10780        }
10781    }
10782
10783    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10784            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10785            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
10786            String volumeUuid, PackageInstalledInfo res) {
10787        String pkgName = deletedPackage.packageName;
10788        boolean deletedPkg = true;
10789        boolean updatedSettings = false;
10790
10791        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10792                + deletedPackage);
10793        long origUpdateTime;
10794        if (pkg.mExtras != null) {
10795            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10796        } else {
10797            origUpdateTime = 0;
10798        }
10799
10800        // First delete the existing package while retaining the data directory
10801        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10802                res.removedInfo, true)) {
10803            // If the existing package wasn't successfully deleted
10804            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10805            deletedPkg = false;
10806        } else {
10807            // Successfully deleted the old package; proceed with replace.
10808
10809            // If deleted package lived in a container, give users a chance to
10810            // relinquish resources before killing.
10811            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
10812                if (DEBUG_INSTALL) {
10813                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10814                }
10815                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10816                final ArrayList<String> pkgList = new ArrayList<String>(1);
10817                pkgList.add(deletedPackage.applicationInfo.packageName);
10818                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10819            }
10820
10821            deleteCodeCacheDirsLI(pkgName);
10822            try {
10823                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10824                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10825                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
10826                        perUserInstalled, res, user);
10827                updatedSettings = true;
10828            } catch (PackageManagerException e) {
10829                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10830            }
10831        }
10832
10833        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10834            // remove package from internal structures.  Note that we want deletePackageX to
10835            // delete the package data and cache directories that it created in
10836            // scanPackageLocked, unless those directories existed before we even tried to
10837            // install.
10838            if(updatedSettings) {
10839                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10840                deletePackageLI(
10841                        pkgName, null, true, allUsers, perUserInstalled,
10842                        PackageManager.DELETE_KEEP_DATA,
10843                                res.removedInfo, true);
10844            }
10845            // Since we failed to install the new package we need to restore the old
10846            // package that we deleted.
10847            if (deletedPkg) {
10848                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10849                File restoreFile = new File(deletedPackage.codePath);
10850                // Parse old package
10851                boolean oldExternal = isExternal(deletedPackage);
10852                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10853                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10854                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
10855                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10856                try {
10857                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10858                } catch (PackageManagerException e) {
10859                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10860                            + e.getMessage());
10861                    return;
10862                }
10863                // Restore of old package succeeded. Update permissions.
10864                // writer
10865                synchronized (mPackages) {
10866                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10867                            UPDATE_PERMISSIONS_ALL);
10868                    // can downgrade to reader
10869                    mSettings.writeLPr();
10870                }
10871                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10872            }
10873        }
10874    }
10875
10876    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10877            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10878            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
10879            String volumeUuid, PackageInstalledInfo res) {
10880        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10881                + ", old=" + deletedPackage);
10882        boolean disabledSystem = false;
10883        boolean updatedSettings = false;
10884        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10885        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
10886                != 0) {
10887            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10888        }
10889        String packageName = deletedPackage.packageName;
10890        if (packageName == null) {
10891            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10892                    "Attempt to delete null packageName.");
10893            return;
10894        }
10895        PackageParser.Package oldPkg;
10896        PackageSetting oldPkgSetting;
10897        // reader
10898        synchronized (mPackages) {
10899            oldPkg = mPackages.get(packageName);
10900            oldPkgSetting = mSettings.mPackages.get(packageName);
10901            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10902                    (oldPkgSetting == null)) {
10903                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10904                        "Couldn't find package:" + packageName + " information");
10905                return;
10906            }
10907        }
10908
10909        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10910
10911        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10912        res.removedInfo.removedPackage = packageName;
10913        // Remove existing system package
10914        removePackageLI(oldPkgSetting, true);
10915        // writer
10916        synchronized (mPackages) {
10917            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10918            if (!disabledSystem && deletedPackage != null) {
10919                // We didn't need to disable the .apk as a current system package,
10920                // which means we are replacing another update that is already
10921                // installed.  We need to make sure to delete the older one's .apk.
10922                res.removedInfo.args = createInstallArgsForExisting(0,
10923                        deletedPackage.applicationInfo.getCodePath(),
10924                        deletedPackage.applicationInfo.getResourcePath(),
10925                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10926                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10927            } else {
10928                res.removedInfo.args = null;
10929            }
10930        }
10931
10932        // Successfully disabled the old package. Now proceed with re-installation
10933        deleteCodeCacheDirsLI(packageName);
10934
10935        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10936        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10937
10938        PackageParser.Package newPackage = null;
10939        try {
10940            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10941            if (newPackage.mExtras != null) {
10942                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10943                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10944                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10945
10946                // is the update attempting to change shared user? that isn't going to work...
10947                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10948                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10949                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10950                            + " to " + newPkgSetting.sharedUser);
10951                    updatedSettings = true;
10952                }
10953            }
10954
10955            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10956                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
10957                        perUserInstalled, res, user);
10958                updatedSettings = true;
10959            }
10960
10961        } catch (PackageManagerException e) {
10962            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10963        }
10964
10965        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10966            // Re installation failed. Restore old information
10967            // Remove new pkg information
10968            if (newPackage != null) {
10969                removeInstalledPackageLI(newPackage, true);
10970            }
10971            // Add back the old system package
10972            try {
10973                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10974            } catch (PackageManagerException e) {
10975                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10976            }
10977            // Restore the old system information in Settings
10978            synchronized (mPackages) {
10979                if (disabledSystem) {
10980                    mSettings.enableSystemPackageLPw(packageName);
10981                }
10982                if (updatedSettings) {
10983                    mSettings.setInstallerPackageName(packageName,
10984                            oldPkgSetting.installerPackageName);
10985                }
10986                mSettings.writeLPr();
10987            }
10988        }
10989    }
10990
10991    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10992            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
10993            UserHandle user) {
10994        String pkgName = newPackage.packageName;
10995        synchronized (mPackages) {
10996            //write settings. the installStatus will be incomplete at this stage.
10997            //note that the new package setting would have already been
10998            //added to mPackages. It hasn't been persisted yet.
10999            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11000            mSettings.writeLPr();
11001        }
11002
11003        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11004
11005        synchronized (mPackages) {
11006            updatePermissionsLPw(newPackage.packageName, newPackage,
11007                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11008                            ? UPDATE_PERMISSIONS_ALL : 0));
11009            // For system-bundled packages, we assume that installing an upgraded version
11010            // of the package implies that the user actually wants to run that new code,
11011            // so we enable the package.
11012            PackageSetting ps = mSettings.mPackages.get(pkgName);
11013            if (ps != null) {
11014                if (isSystemApp(newPackage)) {
11015                    // NB: implicit assumption that system package upgrades apply to all users
11016                    if (DEBUG_INSTALL) {
11017                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11018                    }
11019                    if (res.origUsers != null) {
11020                        for (int userHandle : res.origUsers) {
11021                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11022                                    userHandle, installerPackageName);
11023                        }
11024                    }
11025                    // Also convey the prior install/uninstall state
11026                    if (allUsers != null && perUserInstalled != null) {
11027                        for (int i = 0; i < allUsers.length; i++) {
11028                            if (DEBUG_INSTALL) {
11029                                Slog.d(TAG, "    user " + allUsers[i]
11030                                        + " => " + perUserInstalled[i]);
11031                            }
11032                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11033                        }
11034                        // these install state changes will be persisted in the
11035                        // upcoming call to mSettings.writeLPr().
11036                    }
11037                }
11038                // It's implied that when a user requests installation, they want the app to be
11039                // installed and enabled.
11040                int userId = user.getIdentifier();
11041                if (userId != UserHandle.USER_ALL) {
11042                    ps.setInstalled(true, userId);
11043                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11044                }
11045            }
11046            res.name = pkgName;
11047            res.uid = newPackage.applicationInfo.uid;
11048            res.pkg = newPackage;
11049            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11050            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11051            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11052            //to update install status
11053            mSettings.writeLPr();
11054        }
11055    }
11056
11057    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11058        final int installFlags = args.installFlags;
11059        final String installerPackageName = args.installerPackageName;
11060        final String volumeUuid = args.volumeUuid;
11061        final File tmpPackageFile = new File(args.getCodePath());
11062        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11063        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11064                || (args.volumeUuid != null));
11065        boolean replace = false;
11066        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
11067        // Result object to be returned
11068        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11069
11070        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11071        // Retrieve PackageSettings and parse package
11072        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11073                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11074                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11075        PackageParser pp = new PackageParser();
11076        pp.setSeparateProcesses(mSeparateProcesses);
11077        pp.setDisplayMetrics(mMetrics);
11078
11079        final PackageParser.Package pkg;
11080        try {
11081            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11082        } catch (PackageParserException e) {
11083            res.setError("Failed parse during installPackageLI", e);
11084            return;
11085        }
11086
11087        // Mark that we have an install time CPU ABI override.
11088        pkg.cpuAbiOverride = args.abiOverride;
11089
11090        String pkgName = res.name = pkg.packageName;
11091        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11092            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11093                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11094                return;
11095            }
11096        }
11097
11098        try {
11099            pp.collectCertificates(pkg, parseFlags);
11100            pp.collectManifestDigest(pkg);
11101        } catch (PackageParserException e) {
11102            res.setError("Failed collect during installPackageLI", e);
11103            return;
11104        }
11105
11106        /* If the installer passed in a manifest digest, compare it now. */
11107        if (args.manifestDigest != null) {
11108            if (DEBUG_INSTALL) {
11109                final String parsedManifest = pkg.manifestDigest == null ? "null"
11110                        : pkg.manifestDigest.toString();
11111                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11112                        + parsedManifest);
11113            }
11114
11115            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11116                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11117                return;
11118            }
11119        } else if (DEBUG_INSTALL) {
11120            final String parsedManifest = pkg.manifestDigest == null
11121                    ? "null" : pkg.manifestDigest.toString();
11122            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11123        }
11124
11125        // Get rid of all references to package scan path via parser.
11126        pp = null;
11127        String oldCodePath = null;
11128        boolean systemApp = false;
11129        synchronized (mPackages) {
11130            // Check if installing already existing package
11131            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11132                String oldName = mSettings.mRenamedPackages.get(pkgName);
11133                if (pkg.mOriginalPackages != null
11134                        && pkg.mOriginalPackages.contains(oldName)
11135                        && mPackages.containsKey(oldName)) {
11136                    // This package is derived from an original package,
11137                    // and this device has been updating from that original
11138                    // name.  We must continue using the original name, so
11139                    // rename the new package here.
11140                    pkg.setPackageName(oldName);
11141                    pkgName = pkg.packageName;
11142                    replace = true;
11143                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11144                            + oldName + " pkgName=" + pkgName);
11145                } else if (mPackages.containsKey(pkgName)) {
11146                    // This package, under its official name, already exists
11147                    // on the device; we should replace it.
11148                    replace = true;
11149                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11150                }
11151            }
11152
11153            PackageSetting ps = mSettings.mPackages.get(pkgName);
11154            if (ps != null) {
11155                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11156
11157                // Quick sanity check that we're signed correctly if updating;
11158                // we'll check this again later when scanning, but we want to
11159                // bail early here before tripping over redefined permissions.
11160                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11161                    try {
11162                        verifySignaturesLP(ps, pkg);
11163                    } catch (PackageManagerException e) {
11164                        res.setError(e.error, e.getMessage());
11165                        return;
11166                    }
11167                } else {
11168                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11169                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11170                                + pkg.packageName + " upgrade keys do not match the "
11171                                + "previously installed version");
11172                        return;
11173                    }
11174                }
11175
11176                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11177                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11178                    systemApp = (ps.pkg.applicationInfo.flags &
11179                            ApplicationInfo.FLAG_SYSTEM) != 0;
11180                }
11181                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11182            }
11183
11184            // Check whether the newly-scanned package wants to define an already-defined perm
11185            int N = pkg.permissions.size();
11186            for (int i = N-1; i >= 0; i--) {
11187                PackageParser.Permission perm = pkg.permissions.get(i);
11188                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11189                if (bp != null) {
11190                    // If the defining package is signed with our cert, it's okay.  This
11191                    // also includes the "updating the same package" case, of course.
11192                    // "updating same package" could also involve key-rotation.
11193                    final boolean sigsOk;
11194                    if (!bp.sourcePackage.equals(pkg.packageName)
11195                            || !(bp.packageSetting instanceof PackageSetting)
11196                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
11197                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
11198                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11199                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11200                    } else {
11201                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11202                    }
11203                    if (!sigsOk) {
11204                        // If the owning package is the system itself, we log but allow
11205                        // install to proceed; we fail the install on all other permission
11206                        // redefinitions.
11207                        if (!bp.sourcePackage.equals("android")) {
11208                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11209                                    + pkg.packageName + " attempting to redeclare permission "
11210                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11211                            res.origPermission = perm.info.name;
11212                            res.origPackage = bp.sourcePackage;
11213                            return;
11214                        } else {
11215                            Slog.w(TAG, "Package " + pkg.packageName
11216                                    + " attempting to redeclare system permission "
11217                                    + perm.info.name + "; ignoring new declaration");
11218                            pkg.permissions.remove(i);
11219                        }
11220                    }
11221                }
11222            }
11223
11224        }
11225
11226        if (systemApp && onExternal) {
11227            // Disable updates to system apps on sdcard
11228            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11229                    "Cannot install updates to system apps on sdcard");
11230            return;
11231        }
11232
11233        // Run dexopt before old package gets removed, to minimize time when app is not available
11234        int result = mPackageDexOptimizer
11235                .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */,
11236                        false /* defer */, false /* inclDependencies */);
11237        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11238            res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11239            return;
11240        }
11241
11242        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11243            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11244            return;
11245        }
11246
11247        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11248
11249        // Call with SCAN_NO_DEX, since dexopt has already been made
11250        if (replace) {
11251            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING | SCAN_NO_DEX, args.user,
11252                    installerPackageName, volumeUuid, res);
11253        } else {
11254            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES
11255                    | SCAN_NO_DEX, args.user, installerPackageName, volumeUuid, res);
11256        }
11257        synchronized (mPackages) {
11258            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11259            if (ps != null) {
11260                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11261            }
11262        }
11263    }
11264
11265    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11266        if (mIntentFilterVerifierComponent == null) {
11267            Slog.d(TAG, "No IntentFilter verification will not be done as "
11268                    + "there is no IntentFilterVerifier available!");
11269            return;
11270        }
11271
11272        final int verifierUid = getPackageUid(
11273                mIntentFilterVerifierComponent.getPackageName(),
11274                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11275
11276        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11277        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11278        msg.obj = pkg;
11279        msg.arg1 = userId;
11280        msg.arg2 = verifierUid;
11281
11282        mHandler.sendMessage(msg);
11283    }
11284
11285    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11286            PackageParser.Package pkg) {
11287        int size = pkg.activities.size();
11288        if (size == 0) {
11289            Slog.d(TAG, "No activity, so no need to verify any IntentFilter!");
11290            return;
11291        }
11292
11293        final boolean hasDomainURLs = hasDomainURLs(pkg);
11294        if (!hasDomainURLs) {
11295            Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!");
11296            return;
11297        }
11298
11299        Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size
11300                + " Activities needs verification ...");
11301
11302        final int verificationId = mIntentFilterVerificationToken++;
11303        int count = 0;
11304        final String packageName = pkg.packageName;
11305        ArrayList<String> allHosts = new ArrayList<>();
11306
11307        synchronized (mPackages) {
11308            for (PackageParser.Activity a : pkg.activities) {
11309                for (ActivityIntentInfo filter : a.intents) {
11310                    boolean needsFilterVerification = filter.needsVerification();
11311                    if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11312                        Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString());
11313                        mIntentFilterVerifier.addOneIntentFilterVerification(
11314                                verifierUid, userId, verificationId, filter, packageName);
11315                        count++;
11316                    } else if (!needsFilterVerification) {
11317                        Slog.d(TAG, "No verification needed for IntentFilter:"
11318                                + filter.toString());
11319                        if (hasValidDomains(filter)) {
11320                            allHosts.addAll(filter.getHostsList());
11321                        }
11322                    } else {
11323                        Slog.d(TAG, "Verification already done for IntentFilter:"
11324                                + filter.toString());
11325                    }
11326                }
11327            }
11328        }
11329
11330        if (count > 0) {
11331            mIntentFilterVerifier.startVerifications(userId);
11332            Slog.d(TAG, "Started " + count + " IntentFilter verification"
11333                    + (count > 1 ? "s" : "") +  " for userId:" + userId + "!");
11334        } else {
11335            Slog.d(TAG, "No need to start any IntentFilter verification!");
11336            if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw(
11337                    packageName, allHosts) != null) {
11338                scheduleWriteSettingsLocked();
11339            }
11340        }
11341    }
11342
11343    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11344        final ComponentName cn  = filter.activity.getComponentName();
11345        final String packageName = cn.getPackageName();
11346
11347        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11348                packageName);
11349        if (ivi == null) {
11350            return true;
11351        }
11352        int status = ivi.getStatus();
11353        switch (status) {
11354            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11355            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11356                return true;
11357
11358            default:
11359                // Nothing to do
11360                return false;
11361        }
11362    }
11363
11364    private static boolean isMultiArch(PackageSetting ps) {
11365        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11366    }
11367
11368    private static boolean isMultiArch(ApplicationInfo info) {
11369        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11370    }
11371
11372    private static boolean isExternal(PackageParser.Package pkg) {
11373        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11374    }
11375
11376    private static boolean isExternal(PackageSetting ps) {
11377        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11378    }
11379
11380    private static boolean isExternal(ApplicationInfo info) {
11381        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11382    }
11383
11384    private static boolean isSystemApp(PackageParser.Package pkg) {
11385        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11386    }
11387
11388    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11389        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11390    }
11391
11392    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11393        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11394    }
11395
11396    private static boolean isSystemApp(PackageSetting ps) {
11397        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11398    }
11399
11400    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11401        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11402    }
11403
11404    private int packageFlagsToInstallFlags(PackageSetting ps) {
11405        int installFlags = 0;
11406        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11407            // This existing package was an external ASEC install when we have
11408            // the external flag without a UUID
11409            installFlags |= PackageManager.INSTALL_EXTERNAL;
11410        }
11411        if (ps.isForwardLocked()) {
11412            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11413        }
11414        return installFlags;
11415    }
11416
11417    private void deleteTempPackageFiles() {
11418        final FilenameFilter filter = new FilenameFilter() {
11419            public boolean accept(File dir, String name) {
11420                return name.startsWith("vmdl") && name.endsWith(".tmp");
11421            }
11422        };
11423        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11424            file.delete();
11425        }
11426    }
11427
11428    @Override
11429    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11430            int flags) {
11431        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11432                flags);
11433    }
11434
11435    @Override
11436    public void deletePackage(final String packageName,
11437            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11438        mContext.enforceCallingOrSelfPermission(
11439                android.Manifest.permission.DELETE_PACKAGES, null);
11440        final int uid = Binder.getCallingUid();
11441        if (UserHandle.getUserId(uid) != userId) {
11442            mContext.enforceCallingPermission(
11443                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11444                    "deletePackage for user " + userId);
11445        }
11446        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11447            try {
11448                observer.onPackageDeleted(packageName,
11449                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11450            } catch (RemoteException re) {
11451            }
11452            return;
11453        }
11454
11455        boolean uninstallBlocked = false;
11456        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11457            int[] users = sUserManager.getUserIds();
11458            for (int i = 0; i < users.length; ++i) {
11459                if (getBlockUninstallForUser(packageName, users[i])) {
11460                    uninstallBlocked = true;
11461                    break;
11462                }
11463            }
11464        } else {
11465            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11466        }
11467        if (uninstallBlocked) {
11468            try {
11469                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11470                        null);
11471            } catch (RemoteException re) {
11472            }
11473            return;
11474        }
11475
11476        if (DEBUG_REMOVE) {
11477            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
11478        }
11479        // Queue up an async operation since the package deletion may take a little while.
11480        mHandler.post(new Runnable() {
11481            public void run() {
11482                mHandler.removeCallbacks(this);
11483                final int returnCode = deletePackageX(packageName, userId, flags);
11484                if (observer != null) {
11485                    try {
11486                        observer.onPackageDeleted(packageName, returnCode, null);
11487                    } catch (RemoteException e) {
11488                        Log.i(TAG, "Observer no longer exists.");
11489                    } //end catch
11490                } //end if
11491            } //end run
11492        });
11493    }
11494
11495    private boolean isPackageDeviceAdmin(String packageName, int userId) {
11496        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
11497                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
11498        try {
11499            if (dpm != null) {
11500                if (dpm.isDeviceOwner(packageName)) {
11501                    return true;
11502                }
11503                int[] users;
11504                if (userId == UserHandle.USER_ALL) {
11505                    users = sUserManager.getUserIds();
11506                } else {
11507                    users = new int[]{userId};
11508                }
11509                for (int i = 0; i < users.length; ++i) {
11510                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
11511                        return true;
11512                    }
11513                }
11514            }
11515        } catch (RemoteException e) {
11516        }
11517        return false;
11518    }
11519
11520    /**
11521     *  This method is an internal method that could be get invoked either
11522     *  to delete an installed package or to clean up a failed installation.
11523     *  After deleting an installed package, a broadcast is sent to notify any
11524     *  listeners that the package has been installed. For cleaning up a failed
11525     *  installation, the broadcast is not necessary since the package's
11526     *  installation wouldn't have sent the initial broadcast either
11527     *  The key steps in deleting a package are
11528     *  deleting the package information in internal structures like mPackages,
11529     *  deleting the packages base directories through installd
11530     *  updating mSettings to reflect current status
11531     *  persisting settings for later use
11532     *  sending a broadcast if necessary
11533     */
11534    private int deletePackageX(String packageName, int userId, int flags) {
11535        final PackageRemovedInfo info = new PackageRemovedInfo();
11536        final boolean res;
11537
11538        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
11539                ? UserHandle.ALL : new UserHandle(userId);
11540
11541        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
11542            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
11543            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
11544        }
11545
11546        boolean removedForAllUsers = false;
11547        boolean systemUpdate = false;
11548
11549        // for the uninstall-updates case and restricted profiles, remember the per-
11550        // userhandle installed state
11551        int[] allUsers;
11552        boolean[] perUserInstalled;
11553        synchronized (mPackages) {
11554            PackageSetting ps = mSettings.mPackages.get(packageName);
11555            allUsers = sUserManager.getUserIds();
11556            perUserInstalled = new boolean[allUsers.length];
11557            for (int i = 0; i < allUsers.length; i++) {
11558                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11559            }
11560        }
11561
11562        synchronized (mInstallLock) {
11563            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
11564            res = deletePackageLI(packageName, removeForUser,
11565                    true, allUsers, perUserInstalled,
11566                    flags | REMOVE_CHATTY, info, true);
11567            systemUpdate = info.isRemovedPackageSystemUpdate;
11568            if (res && !systemUpdate && mPackages.get(packageName) == null) {
11569                removedForAllUsers = true;
11570            }
11571            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
11572                    + " removedForAllUsers=" + removedForAllUsers);
11573        }
11574
11575        if (res) {
11576            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
11577
11578            // If the removed package was a system update, the old system package
11579            // was re-enabled; we need to broadcast this information
11580            if (systemUpdate) {
11581                Bundle extras = new Bundle(1);
11582                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
11583                        ? info.removedAppId : info.uid);
11584                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11585
11586                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
11587                        extras, null, null, null);
11588                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
11589                        extras, null, null, null);
11590                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
11591                        null, packageName, null, null);
11592            }
11593        }
11594        // Force a gc here.
11595        Runtime.getRuntime().gc();
11596        // Delete the resources here after sending the broadcast to let
11597        // other processes clean up before deleting resources.
11598        if (info.args != null) {
11599            synchronized (mInstallLock) {
11600                info.args.doPostDeleteLI(true);
11601            }
11602        }
11603
11604        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
11605    }
11606
11607    static class PackageRemovedInfo {
11608        String removedPackage;
11609        int uid = -1;
11610        int removedAppId = -1;
11611        int[] removedUsers = null;
11612        boolean isRemovedPackageSystemUpdate = false;
11613        // Clean up resources deleted packages.
11614        InstallArgs args = null;
11615
11616        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
11617            Bundle extras = new Bundle(1);
11618            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
11619            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
11620            if (replacing) {
11621                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11622            }
11623            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
11624            if (removedPackage != null) {
11625                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
11626                        extras, null, null, removedUsers);
11627                if (fullRemove && !replacing) {
11628                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
11629                            extras, null, null, removedUsers);
11630                }
11631            }
11632            if (removedAppId >= 0) {
11633                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
11634                        removedUsers);
11635            }
11636        }
11637    }
11638
11639    /*
11640     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
11641     * flag is not set, the data directory is removed as well.
11642     * make sure this flag is set for partially installed apps. If not its meaningless to
11643     * delete a partially installed application.
11644     */
11645    private void removePackageDataLI(PackageSetting ps,
11646            int[] allUserHandles, boolean[] perUserInstalled,
11647            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
11648        String packageName = ps.name;
11649        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
11650        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
11651        // Retrieve object to delete permissions for shared user later on
11652        final PackageSetting deletedPs;
11653        // reader
11654        synchronized (mPackages) {
11655            deletedPs = mSettings.mPackages.get(packageName);
11656            if (outInfo != null) {
11657                outInfo.removedPackage = packageName;
11658                outInfo.removedUsers = deletedPs != null
11659                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
11660                        : null;
11661            }
11662        }
11663        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11664            removeDataDirsLI(packageName);
11665            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
11666        }
11667        // writer
11668        synchronized (mPackages) {
11669            if (deletedPs != null) {
11670                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11671                    if (outInfo != null) {
11672                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
11673                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
11674                    }
11675                    updatePermissionsLPw(deletedPs.name, null, 0);
11676                    if (deletedPs.sharedUser != null) {
11677                        // Remove permissions associated with package. Since runtime
11678                        // permissions are per user we have to kill the removed package
11679                        // or packages running under the shared user of the removed
11680                        // package if revoking the permissions requested only by the removed
11681                        // package is successful and this causes a change in gids.
11682                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11683                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
11684                                    userId);
11685                            if (userIdToKill == UserHandle.USER_ALL
11686                                    || userIdToKill >= UserHandle.USER_OWNER) {
11687                                // If gids changed for this user, kill all affected packages.
11688                                mHandler.post(new Runnable() {
11689                                    @Override
11690                                    public void run() {
11691                                        // This has to happen with no lock held.
11692                                        killSettingPackagesForUser(deletedPs, userIdToKill,
11693                                                KILL_APP_REASON_GIDS_CHANGED);
11694                                    }
11695                                });
11696                            break;
11697                            }
11698                        }
11699                    }
11700                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
11701                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
11702                }
11703                // make sure to preserve per-user disabled state if this removal was just
11704                // a downgrade of a system app to the factory package
11705                if (allUserHandles != null && perUserInstalled != null) {
11706                    if (DEBUG_REMOVE) {
11707                        Slog.d(TAG, "Propagating install state across downgrade");
11708                    }
11709                    for (int i = 0; i < allUserHandles.length; i++) {
11710                        if (DEBUG_REMOVE) {
11711                            Slog.d(TAG, "    user " + allUserHandles[i]
11712                                    + " => " + perUserInstalled[i]);
11713                        }
11714                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11715                    }
11716                }
11717            }
11718            // can downgrade to reader
11719            if (writeSettings) {
11720                // Save settings now
11721                mSettings.writeLPr();
11722            }
11723        }
11724        if (outInfo != null) {
11725            // A user ID was deleted here. Go through all users and remove it
11726            // from KeyStore.
11727            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
11728        }
11729    }
11730
11731    static boolean locationIsPrivileged(File path) {
11732        try {
11733            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
11734                    .getCanonicalPath();
11735            return path.getCanonicalPath().startsWith(privilegedAppDir);
11736        } catch (IOException e) {
11737            Slog.e(TAG, "Unable to access code path " + path);
11738        }
11739        return false;
11740    }
11741
11742    /*
11743     * Tries to delete system package.
11744     */
11745    private boolean deleteSystemPackageLI(PackageSetting newPs,
11746            int[] allUserHandles, boolean[] perUserInstalled,
11747            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
11748        final boolean applyUserRestrictions
11749                = (allUserHandles != null) && (perUserInstalled != null);
11750        PackageSetting disabledPs = null;
11751        // Confirm if the system package has been updated
11752        // An updated system app can be deleted. This will also have to restore
11753        // the system pkg from system partition
11754        // reader
11755        synchronized (mPackages) {
11756            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
11757        }
11758        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
11759                + " disabledPs=" + disabledPs);
11760        if (disabledPs == null) {
11761            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
11762            return false;
11763        } else if (DEBUG_REMOVE) {
11764            Slog.d(TAG, "Deleting system pkg from data partition");
11765        }
11766        if (DEBUG_REMOVE) {
11767            if (applyUserRestrictions) {
11768                Slog.d(TAG, "Remembering install states:");
11769                for (int i = 0; i < allUserHandles.length; i++) {
11770                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
11771                }
11772            }
11773        }
11774        // Delete the updated package
11775        outInfo.isRemovedPackageSystemUpdate = true;
11776        if (disabledPs.versionCode < newPs.versionCode) {
11777            // Delete data for downgrades
11778            flags &= ~PackageManager.DELETE_KEEP_DATA;
11779        } else {
11780            // Preserve data by setting flag
11781            flags |= PackageManager.DELETE_KEEP_DATA;
11782        }
11783        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
11784                allUserHandles, perUserInstalled, outInfo, writeSettings);
11785        if (!ret) {
11786            return false;
11787        }
11788        // writer
11789        synchronized (mPackages) {
11790            // Reinstate the old system package
11791            mSettings.enableSystemPackageLPw(newPs.name);
11792            // Remove any native libraries from the upgraded package.
11793            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
11794        }
11795        // Install the system package
11796        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
11797        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
11798        if (locationIsPrivileged(disabledPs.codePath)) {
11799            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11800        }
11801
11802        final PackageParser.Package newPkg;
11803        try {
11804            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
11805        } catch (PackageManagerException e) {
11806            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
11807            return false;
11808        }
11809
11810        // writer
11811        synchronized (mPackages) {
11812            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
11813            updatePermissionsLPw(newPkg.packageName, newPkg,
11814                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
11815            if (applyUserRestrictions) {
11816                if (DEBUG_REMOVE) {
11817                    Slog.d(TAG, "Propagating install state across reinstall");
11818                }
11819                for (int i = 0; i < allUserHandles.length; i++) {
11820                    if (DEBUG_REMOVE) {
11821                        Slog.d(TAG, "    user " + allUserHandles[i]
11822                                + " => " + perUserInstalled[i]);
11823                    }
11824                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11825                }
11826                // Regardless of writeSettings we need to ensure that this restriction
11827                // state propagation is persisted
11828                mSettings.writeAllUsersPackageRestrictionsLPr();
11829            }
11830            // can downgrade to reader here
11831            if (writeSettings) {
11832                mSettings.writeLPr();
11833            }
11834        }
11835        return true;
11836    }
11837
11838    private boolean deleteInstalledPackageLI(PackageSetting ps,
11839            boolean deleteCodeAndResources, int flags,
11840            int[] allUserHandles, boolean[] perUserInstalled,
11841            PackageRemovedInfo outInfo, boolean writeSettings) {
11842        if (outInfo != null) {
11843            outInfo.uid = ps.appId;
11844        }
11845
11846        // Delete package data from internal structures and also remove data if flag is set
11847        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
11848
11849        // Delete application code and resources
11850        if (deleteCodeAndResources && (outInfo != null)) {
11851            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
11852                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
11853                    getAppDexInstructionSets(ps));
11854            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
11855        }
11856        return true;
11857    }
11858
11859    @Override
11860    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
11861            int userId) {
11862        mContext.enforceCallingOrSelfPermission(
11863                android.Manifest.permission.DELETE_PACKAGES, null);
11864        synchronized (mPackages) {
11865            PackageSetting ps = mSettings.mPackages.get(packageName);
11866            if (ps == null) {
11867                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
11868                return false;
11869            }
11870            if (!ps.getInstalled(userId)) {
11871                // Can't block uninstall for an app that is not installed or enabled.
11872                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11873                return false;
11874            }
11875            ps.setBlockUninstall(blockUninstall, userId);
11876            mSettings.writePackageRestrictionsLPr(userId);
11877        }
11878        return true;
11879    }
11880
11881    @Override
11882    public boolean getBlockUninstallForUser(String packageName, int userId) {
11883        synchronized (mPackages) {
11884            PackageSetting ps = mSettings.mPackages.get(packageName);
11885            if (ps == null) {
11886                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11887                return false;
11888            }
11889            return ps.getBlockUninstall(userId);
11890        }
11891    }
11892
11893    /*
11894     * This method handles package deletion in general
11895     */
11896    private boolean deletePackageLI(String packageName, UserHandle user,
11897            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11898            int flags, PackageRemovedInfo outInfo,
11899            boolean writeSettings) {
11900        if (packageName == null) {
11901            Slog.w(TAG, "Attempt to delete null packageName.");
11902            return false;
11903        }
11904        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11905        PackageSetting ps;
11906        boolean dataOnly = false;
11907        int removeUser = -1;
11908        int appId = -1;
11909        synchronized (mPackages) {
11910            ps = mSettings.mPackages.get(packageName);
11911            if (ps == null) {
11912                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11913                return false;
11914            }
11915            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11916                    && user.getIdentifier() != UserHandle.USER_ALL) {
11917                // The caller is asking that the package only be deleted for a single
11918                // user.  To do this, we just mark its uninstalled state and delete
11919                // its data.  If this is a system app, we only allow this to happen if
11920                // they have set the special DELETE_SYSTEM_APP which requests different
11921                // semantics than normal for uninstalling system apps.
11922                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11923                ps.setUserState(user.getIdentifier(),
11924                        COMPONENT_ENABLED_STATE_DEFAULT,
11925                        false, //installed
11926                        true,  //stopped
11927                        true,  //notLaunched
11928                        false, //hidden
11929                        null, null, null,
11930                        false, // blockUninstall
11931                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
11932                if (!isSystemApp(ps)) {
11933                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11934                        // Other user still have this package installed, so all
11935                        // we need to do is clear this user's data and save that
11936                        // it is uninstalled.
11937                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11938                        removeUser = user.getIdentifier();
11939                        appId = ps.appId;
11940                        scheduleWritePackageRestrictionsLocked(removeUser);
11941                    } else {
11942                        // We need to set it back to 'installed' so the uninstall
11943                        // broadcasts will be sent correctly.
11944                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11945                        ps.setInstalled(true, user.getIdentifier());
11946                    }
11947                } else {
11948                    // This is a system app, so we assume that the
11949                    // other users still have this package installed, so all
11950                    // we need to do is clear this user's data and save that
11951                    // it is uninstalled.
11952                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11953                    removeUser = user.getIdentifier();
11954                    appId = ps.appId;
11955                    scheduleWritePackageRestrictionsLocked(removeUser);
11956                }
11957            }
11958        }
11959
11960        if (removeUser >= 0) {
11961            // From above, we determined that we are deleting this only
11962            // for a single user.  Continue the work here.
11963            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11964            if (outInfo != null) {
11965                outInfo.removedPackage = packageName;
11966                outInfo.removedAppId = appId;
11967                outInfo.removedUsers = new int[] {removeUser};
11968            }
11969            mInstaller.clearUserData(packageName, removeUser);
11970            removeKeystoreDataIfNeeded(removeUser, appId);
11971            schedulePackageCleaning(packageName, removeUser, false);
11972            synchronized (mPackages) {
11973                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
11974                    scheduleWritePackageRestrictionsLocked(removeUser);
11975                }
11976            }
11977            return true;
11978        }
11979
11980        if (dataOnly) {
11981            // Delete application data first
11982            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11983            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11984            return true;
11985        }
11986
11987        boolean ret = false;
11988        if (isSystemApp(ps)) {
11989            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11990            // When an updated system application is deleted we delete the existing resources as well and
11991            // fall back to existing code in system partition
11992            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11993                    flags, outInfo, writeSettings);
11994        } else {
11995            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11996            // Kill application pre-emptively especially for apps on sd.
11997            killApplication(packageName, ps.appId, "uninstall pkg");
11998            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11999                    allUserHandles, perUserInstalled,
12000                    outInfo, writeSettings);
12001        }
12002
12003        return ret;
12004    }
12005
12006    private final class ClearStorageConnection implements ServiceConnection {
12007        IMediaContainerService mContainerService;
12008
12009        @Override
12010        public void onServiceConnected(ComponentName name, IBinder service) {
12011            synchronized (this) {
12012                mContainerService = IMediaContainerService.Stub.asInterface(service);
12013                notifyAll();
12014            }
12015        }
12016
12017        @Override
12018        public void onServiceDisconnected(ComponentName name) {
12019        }
12020    }
12021
12022    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12023        final boolean mounted;
12024        if (Environment.isExternalStorageEmulated()) {
12025            mounted = true;
12026        } else {
12027            final String status = Environment.getExternalStorageState();
12028
12029            mounted = status.equals(Environment.MEDIA_MOUNTED)
12030                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12031        }
12032
12033        if (!mounted) {
12034            return;
12035        }
12036
12037        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12038        int[] users;
12039        if (userId == UserHandle.USER_ALL) {
12040            users = sUserManager.getUserIds();
12041        } else {
12042            users = new int[] { userId };
12043        }
12044        final ClearStorageConnection conn = new ClearStorageConnection();
12045        if (mContext.bindServiceAsUser(
12046                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12047            try {
12048                for (int curUser : users) {
12049                    long timeout = SystemClock.uptimeMillis() + 5000;
12050                    synchronized (conn) {
12051                        long now = SystemClock.uptimeMillis();
12052                        while (conn.mContainerService == null && now < timeout) {
12053                            try {
12054                                conn.wait(timeout - now);
12055                            } catch (InterruptedException e) {
12056                            }
12057                        }
12058                    }
12059                    if (conn.mContainerService == null) {
12060                        return;
12061                    }
12062
12063                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12064                    clearDirectory(conn.mContainerService,
12065                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12066                    if (allData) {
12067                        clearDirectory(conn.mContainerService,
12068                                userEnv.buildExternalStorageAppDataDirs(packageName));
12069                        clearDirectory(conn.mContainerService,
12070                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12071                    }
12072                }
12073            } finally {
12074                mContext.unbindService(conn);
12075            }
12076        }
12077    }
12078
12079    @Override
12080    public void clearApplicationUserData(final String packageName,
12081            final IPackageDataObserver observer, final int userId) {
12082        mContext.enforceCallingOrSelfPermission(
12083                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12084        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12085        // Queue up an async operation since the package deletion may take a little while.
12086        mHandler.post(new Runnable() {
12087            public void run() {
12088                mHandler.removeCallbacks(this);
12089                final boolean succeeded;
12090                synchronized (mInstallLock) {
12091                    succeeded = clearApplicationUserDataLI(packageName, userId);
12092                }
12093                clearExternalStorageDataSync(packageName, userId, true);
12094                if (succeeded) {
12095                    // invoke DeviceStorageMonitor's update method to clear any notifications
12096                    DeviceStorageMonitorInternal
12097                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12098                    if (dsm != null) {
12099                        dsm.checkMemory();
12100                    }
12101                }
12102                if(observer != null) {
12103                    try {
12104                        observer.onRemoveCompleted(packageName, succeeded);
12105                    } catch (RemoteException e) {
12106                        Log.i(TAG, "Observer no longer exists.");
12107                    }
12108                } //end if observer
12109            } //end run
12110        });
12111    }
12112
12113    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12114        if (packageName == null) {
12115            Slog.w(TAG, "Attempt to delete null packageName.");
12116            return false;
12117        }
12118
12119        // Try finding details about the requested package
12120        PackageParser.Package pkg;
12121        synchronized (mPackages) {
12122            pkg = mPackages.get(packageName);
12123            if (pkg == null) {
12124                final PackageSetting ps = mSettings.mPackages.get(packageName);
12125                if (ps != null) {
12126                    pkg = ps.pkg;
12127                }
12128            }
12129        }
12130
12131        if (pkg == null) {
12132            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12133        }
12134
12135        // Always delete data directories for package, even if we found no other
12136        // record of app. This helps users recover from UID mismatches without
12137        // resorting to a full data wipe.
12138        int retCode = mInstaller.clearUserData(packageName, userId);
12139        if (retCode < 0) {
12140            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12141            return false;
12142        }
12143
12144        if (pkg == null) {
12145            return false;
12146        }
12147
12148        if (pkg != null && pkg.applicationInfo != null) {
12149            final int appId = pkg.applicationInfo.uid;
12150            removeKeystoreDataIfNeeded(userId, appId);
12151        }
12152
12153        // Create a native library symlink only if we have native libraries
12154        // and if the native libraries are 32 bit libraries. We do not provide
12155        // this symlink for 64 bit libraries.
12156        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
12157                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12158            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12159            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
12160                Slog.w(TAG, "Failed linking native library dir");
12161                return false;
12162            }
12163        }
12164
12165        return true;
12166    }
12167
12168    /**
12169     * Remove entries from the keystore daemon. Will only remove it if the
12170     * {@code appId} is valid.
12171     */
12172    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12173        if (appId < 0) {
12174            return;
12175        }
12176
12177        final KeyStore keyStore = KeyStore.getInstance();
12178        if (keyStore != null) {
12179            if (userId == UserHandle.USER_ALL) {
12180                for (final int individual : sUserManager.getUserIds()) {
12181                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12182                }
12183            } else {
12184                keyStore.clearUid(UserHandle.getUid(userId, appId));
12185            }
12186        } else {
12187            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12188        }
12189    }
12190
12191    @Override
12192    public void deleteApplicationCacheFiles(final String packageName,
12193            final IPackageDataObserver observer) {
12194        mContext.enforceCallingOrSelfPermission(
12195                android.Manifest.permission.DELETE_CACHE_FILES, null);
12196        // Queue up an async operation since the package deletion may take a little while.
12197        final int userId = UserHandle.getCallingUserId();
12198        mHandler.post(new Runnable() {
12199            public void run() {
12200                mHandler.removeCallbacks(this);
12201                final boolean succeded;
12202                synchronized (mInstallLock) {
12203                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12204                }
12205                clearExternalStorageDataSync(packageName, userId, false);
12206                if(observer != null) {
12207                    try {
12208                        observer.onRemoveCompleted(packageName, succeded);
12209                    } catch (RemoteException e) {
12210                        Log.i(TAG, "Observer no longer exists.");
12211                    }
12212                } //end if observer
12213            } //end run
12214        });
12215    }
12216
12217    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12218        if (packageName == null) {
12219            Slog.w(TAG, "Attempt to delete null packageName.");
12220            return false;
12221        }
12222        PackageParser.Package p;
12223        synchronized (mPackages) {
12224            p = mPackages.get(packageName);
12225        }
12226        if (p == null) {
12227            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12228            return false;
12229        }
12230        final ApplicationInfo applicationInfo = p.applicationInfo;
12231        if (applicationInfo == null) {
12232            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12233            return false;
12234        }
12235        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
12236        if (retCode < 0) {
12237            Slog.w(TAG, "Couldn't remove cache files for package: "
12238                       + packageName + " u" + userId);
12239            return false;
12240        }
12241        return true;
12242    }
12243
12244    @Override
12245    public void getPackageSizeInfo(final String packageName, int userHandle,
12246            final IPackageStatsObserver observer) {
12247        mContext.enforceCallingOrSelfPermission(
12248                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12249        if (packageName == null) {
12250            throw new IllegalArgumentException("Attempt to get size of null packageName");
12251        }
12252
12253        PackageStats stats = new PackageStats(packageName, userHandle);
12254
12255        /*
12256         * Queue up an async operation since the package measurement may take a
12257         * little while.
12258         */
12259        Message msg = mHandler.obtainMessage(INIT_COPY);
12260        msg.obj = new MeasureParams(stats, observer);
12261        mHandler.sendMessage(msg);
12262    }
12263
12264    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12265            PackageStats pStats) {
12266        if (packageName == null) {
12267            Slog.w(TAG, "Attempt to get size of null packageName.");
12268            return false;
12269        }
12270        PackageParser.Package p;
12271        boolean dataOnly = false;
12272        String libDirRoot = null;
12273        String asecPath = null;
12274        PackageSetting ps = null;
12275        synchronized (mPackages) {
12276            p = mPackages.get(packageName);
12277            ps = mSettings.mPackages.get(packageName);
12278            if(p == null) {
12279                dataOnly = true;
12280                if((ps == null) || (ps.pkg == null)) {
12281                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12282                    return false;
12283                }
12284                p = ps.pkg;
12285            }
12286            if (ps != null) {
12287                libDirRoot = ps.legacyNativeLibraryPathString;
12288            }
12289            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12290                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12291                if (secureContainerId != null) {
12292                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12293                }
12294            }
12295        }
12296        String publicSrcDir = null;
12297        if(!dataOnly) {
12298            final ApplicationInfo applicationInfo = p.applicationInfo;
12299            if (applicationInfo == null) {
12300                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12301                return false;
12302            }
12303            if (p.isForwardLocked()) {
12304                publicSrcDir = applicationInfo.getBaseResourcePath();
12305            }
12306        }
12307        // TODO: extend to measure size of split APKs
12308        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12309        // not just the first level.
12310        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12311        // just the primary.
12312        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12313        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
12314                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12315        if (res < 0) {
12316            return false;
12317        }
12318
12319        // Fix-up for forward-locked applications in ASEC containers.
12320        if (!isExternal(p)) {
12321            pStats.codeSize += pStats.externalCodeSize;
12322            pStats.externalCodeSize = 0L;
12323        }
12324
12325        return true;
12326    }
12327
12328
12329    @Override
12330    public void addPackageToPreferred(String packageName) {
12331        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12332    }
12333
12334    @Override
12335    public void removePackageFromPreferred(String packageName) {
12336        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12337    }
12338
12339    @Override
12340    public List<PackageInfo> getPreferredPackages(int flags) {
12341        return new ArrayList<PackageInfo>();
12342    }
12343
12344    private int getUidTargetSdkVersionLockedLPr(int uid) {
12345        Object obj = mSettings.getUserIdLPr(uid);
12346        if (obj instanceof SharedUserSetting) {
12347            final SharedUserSetting sus = (SharedUserSetting) obj;
12348            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12349            final Iterator<PackageSetting> it = sus.packages.iterator();
12350            while (it.hasNext()) {
12351                final PackageSetting ps = it.next();
12352                if (ps.pkg != null) {
12353                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12354                    if (v < vers) vers = v;
12355                }
12356            }
12357            return vers;
12358        } else if (obj instanceof PackageSetting) {
12359            final PackageSetting ps = (PackageSetting) obj;
12360            if (ps.pkg != null) {
12361                return ps.pkg.applicationInfo.targetSdkVersion;
12362            }
12363        }
12364        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12365    }
12366
12367    @Override
12368    public void addPreferredActivity(IntentFilter filter, int match,
12369            ComponentName[] set, ComponentName activity, int userId) {
12370        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12371                "Adding preferred");
12372    }
12373
12374    private void addPreferredActivityInternal(IntentFilter filter, int match,
12375            ComponentName[] set, ComponentName activity, boolean always, int userId,
12376            String opname) {
12377        // writer
12378        int callingUid = Binder.getCallingUid();
12379        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12380        if (filter.countActions() == 0) {
12381            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12382            return;
12383        }
12384        synchronized (mPackages) {
12385            if (mContext.checkCallingOrSelfPermission(
12386                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12387                    != PackageManager.PERMISSION_GRANTED) {
12388                if (getUidTargetSdkVersionLockedLPr(callingUid)
12389                        < Build.VERSION_CODES.FROYO) {
12390                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12391                            + callingUid);
12392                    return;
12393                }
12394                mContext.enforceCallingOrSelfPermission(
12395                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12396            }
12397
12398            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12399            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12400                    + userId + ":");
12401            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12402            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12403            scheduleWritePackageRestrictionsLocked(userId);
12404        }
12405    }
12406
12407    @Override
12408    public void replacePreferredActivity(IntentFilter filter, int match,
12409            ComponentName[] set, ComponentName activity, int userId) {
12410        if (filter.countActions() != 1) {
12411            throw new IllegalArgumentException(
12412                    "replacePreferredActivity expects filter to have only 1 action.");
12413        }
12414        if (filter.countDataAuthorities() != 0
12415                || filter.countDataPaths() != 0
12416                || filter.countDataSchemes() > 1
12417                || filter.countDataTypes() != 0) {
12418            throw new IllegalArgumentException(
12419                    "replacePreferredActivity expects filter to have no data authorities, " +
12420                    "paths, or types; and at most one scheme.");
12421        }
12422
12423        final int callingUid = Binder.getCallingUid();
12424        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12425        synchronized (mPackages) {
12426            if (mContext.checkCallingOrSelfPermission(
12427                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12428                    != PackageManager.PERMISSION_GRANTED) {
12429                if (getUidTargetSdkVersionLockedLPr(callingUid)
12430                        < Build.VERSION_CODES.FROYO) {
12431                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12432                            + Binder.getCallingUid());
12433                    return;
12434                }
12435                mContext.enforceCallingOrSelfPermission(
12436                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12437            }
12438
12439            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12440            if (pir != null) {
12441                // Get all of the existing entries that exactly match this filter.
12442                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
12443                if (existing != null && existing.size() == 1) {
12444                    PreferredActivity cur = existing.get(0);
12445                    if (DEBUG_PREFERRED) {
12446                        Slog.i(TAG, "Checking replace of preferred:");
12447                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12448                        if (!cur.mPref.mAlways) {
12449                            Slog.i(TAG, "  -- CUR; not mAlways!");
12450                        } else {
12451                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
12452                            Slog.i(TAG, "  -- CUR: mSet="
12453                                    + Arrays.toString(cur.mPref.mSetComponents));
12454                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
12455                            Slog.i(TAG, "  -- NEW: mMatch="
12456                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
12457                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
12458                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
12459                        }
12460                    }
12461                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
12462                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
12463                            && cur.mPref.sameSet(set)) {
12464                        // Setting the preferred activity to what it happens to be already
12465                        if (DEBUG_PREFERRED) {
12466                            Slog.i(TAG, "Replacing with same preferred activity "
12467                                    + cur.mPref.mShortComponent + " for user "
12468                                    + userId + ":");
12469                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12470                        }
12471                        return;
12472                    }
12473                }
12474
12475                if (existing != null) {
12476                    if (DEBUG_PREFERRED) {
12477                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
12478                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12479                    }
12480                    for (int i = 0; i < existing.size(); i++) {
12481                        PreferredActivity pa = existing.get(i);
12482                        if (DEBUG_PREFERRED) {
12483                            Slog.i(TAG, "Removing existing preferred activity "
12484                                    + pa.mPref.mComponent + ":");
12485                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
12486                        }
12487                        pir.removeFilter(pa);
12488                    }
12489                }
12490            }
12491            addPreferredActivityInternal(filter, match, set, activity, true, userId,
12492                    "Replacing preferred");
12493        }
12494    }
12495
12496    @Override
12497    public void clearPackagePreferredActivities(String packageName) {
12498        final int uid = Binder.getCallingUid();
12499        // writer
12500        synchronized (mPackages) {
12501            PackageParser.Package pkg = mPackages.get(packageName);
12502            if (pkg == null || pkg.applicationInfo.uid != uid) {
12503                if (mContext.checkCallingOrSelfPermission(
12504                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12505                        != PackageManager.PERMISSION_GRANTED) {
12506                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
12507                            < Build.VERSION_CODES.FROYO) {
12508                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
12509                                + Binder.getCallingUid());
12510                        return;
12511                    }
12512                    mContext.enforceCallingOrSelfPermission(
12513                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12514                }
12515            }
12516
12517            int user = UserHandle.getCallingUserId();
12518            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
12519                scheduleWritePackageRestrictionsLocked(user);
12520            }
12521        }
12522    }
12523
12524    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12525    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
12526        ArrayList<PreferredActivity> removed = null;
12527        boolean changed = false;
12528        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12529            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
12530            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12531            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
12532                continue;
12533            }
12534            Iterator<PreferredActivity> it = pir.filterIterator();
12535            while (it.hasNext()) {
12536                PreferredActivity pa = it.next();
12537                // Mark entry for removal only if it matches the package name
12538                // and the entry is of type "always".
12539                if (packageName == null ||
12540                        (pa.mPref.mComponent.getPackageName().equals(packageName)
12541                                && pa.mPref.mAlways)) {
12542                    if (removed == null) {
12543                        removed = new ArrayList<PreferredActivity>();
12544                    }
12545                    removed.add(pa);
12546                }
12547            }
12548            if (removed != null) {
12549                for (int j=0; j<removed.size(); j++) {
12550                    PreferredActivity pa = removed.get(j);
12551                    pir.removeFilter(pa);
12552                }
12553                changed = true;
12554            }
12555        }
12556        return changed;
12557    }
12558
12559    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12560    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
12561        if (userId == UserHandle.USER_ALL) {
12562            mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds());
12563            for (int oneUserId : sUserManager.getUserIds()) {
12564                scheduleWritePackageRestrictionsLocked(oneUserId);
12565            }
12566        } else {
12567            mSettings.removeIntentFilterVerificationLPw(packageName, userId);
12568            scheduleWritePackageRestrictionsLocked(userId);
12569        }
12570    }
12571
12572    @Override
12573    public void resetPreferredActivities(int userId) {
12574        /* TODO: Actually use userId. Why is it being passed in? */
12575        mContext.enforceCallingOrSelfPermission(
12576                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12577        // writer
12578        synchronized (mPackages) {
12579            int user = UserHandle.getCallingUserId();
12580            clearPackagePreferredActivitiesLPw(null, user);
12581            mSettings.readDefaultPreferredAppsLPw(this, user);
12582            scheduleWritePackageRestrictionsLocked(user);
12583        }
12584    }
12585
12586    @Override
12587    public int getPreferredActivities(List<IntentFilter> outFilters,
12588            List<ComponentName> outActivities, String packageName) {
12589
12590        int num = 0;
12591        final int userId = UserHandle.getCallingUserId();
12592        // reader
12593        synchronized (mPackages) {
12594            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12595            if (pir != null) {
12596                final Iterator<PreferredActivity> it = pir.filterIterator();
12597                while (it.hasNext()) {
12598                    final PreferredActivity pa = it.next();
12599                    if (packageName == null
12600                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
12601                                    && pa.mPref.mAlways)) {
12602                        if (outFilters != null) {
12603                            outFilters.add(new IntentFilter(pa));
12604                        }
12605                        if (outActivities != null) {
12606                            outActivities.add(pa.mPref.mComponent);
12607                        }
12608                    }
12609                }
12610            }
12611        }
12612
12613        return num;
12614    }
12615
12616    @Override
12617    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
12618            int userId) {
12619        int callingUid = Binder.getCallingUid();
12620        if (callingUid != Process.SYSTEM_UID) {
12621            throw new SecurityException(
12622                    "addPersistentPreferredActivity can only be run by the system");
12623        }
12624        if (filter.countActions() == 0) {
12625            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12626            return;
12627        }
12628        synchronized (mPackages) {
12629            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
12630                    " :");
12631            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12632            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
12633                    new PersistentPreferredActivity(filter, activity));
12634            scheduleWritePackageRestrictionsLocked(userId);
12635        }
12636    }
12637
12638    @Override
12639    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
12640        int callingUid = Binder.getCallingUid();
12641        if (callingUid != Process.SYSTEM_UID) {
12642            throw new SecurityException(
12643                    "clearPackagePersistentPreferredActivities can only be run by the system");
12644        }
12645        ArrayList<PersistentPreferredActivity> removed = null;
12646        boolean changed = false;
12647        synchronized (mPackages) {
12648            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
12649                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
12650                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
12651                        .valueAt(i);
12652                if (userId != thisUserId) {
12653                    continue;
12654                }
12655                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
12656                while (it.hasNext()) {
12657                    PersistentPreferredActivity ppa = it.next();
12658                    // Mark entry for removal only if it matches the package name.
12659                    if (ppa.mComponent.getPackageName().equals(packageName)) {
12660                        if (removed == null) {
12661                            removed = new ArrayList<PersistentPreferredActivity>();
12662                        }
12663                        removed.add(ppa);
12664                    }
12665                }
12666                if (removed != null) {
12667                    for (int j=0; j<removed.size(); j++) {
12668                        PersistentPreferredActivity ppa = removed.get(j);
12669                        ppir.removeFilter(ppa);
12670                    }
12671                    changed = true;
12672                }
12673            }
12674
12675            if (changed) {
12676                scheduleWritePackageRestrictionsLocked(userId);
12677            }
12678        }
12679    }
12680
12681    /**
12682     * Non-Binder method, support for the backup/restore mechanism: write the
12683     * full set of preferred activities in its canonical XML format.  Returns true
12684     * on success; false otherwise.
12685     */
12686    @Override
12687    public byte[] getPreferredActivityBackup(int userId) {
12688        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
12689            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
12690        }
12691
12692        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
12693        try {
12694            final XmlSerializer serializer = new FastXmlSerializer();
12695            serializer.setOutput(dataStream, "utf-8");
12696            serializer.startDocument(null, true);
12697            serializer.startTag(null, TAG_PREFERRED_BACKUP);
12698
12699            synchronized (mPackages) {
12700                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
12701            }
12702
12703            serializer.endTag(null, TAG_PREFERRED_BACKUP);
12704            serializer.endDocument();
12705            serializer.flush();
12706        } catch (Exception e) {
12707            if (DEBUG_BACKUP) {
12708                Slog.e(TAG, "Unable to write preferred activities for backup", e);
12709            }
12710            return null;
12711        }
12712
12713        return dataStream.toByteArray();
12714    }
12715
12716    @Override
12717    public void restorePreferredActivities(byte[] backup, int userId) {
12718        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
12719            throw new SecurityException("Only the system may call restorePreferredActivities()");
12720        }
12721
12722        try {
12723            final XmlPullParser parser = Xml.newPullParser();
12724            parser.setInput(new ByteArrayInputStream(backup), null);
12725
12726            int type;
12727            while ((type = parser.next()) != XmlPullParser.START_TAG
12728                    && type != XmlPullParser.END_DOCUMENT) {
12729            }
12730            if (type != XmlPullParser.START_TAG) {
12731                // oops didn't find a start tag?!
12732                if (DEBUG_BACKUP) {
12733                    Slog.e(TAG, "Didn't find start tag during restore");
12734                }
12735                return;
12736            }
12737
12738            // this is supposed to be TAG_PREFERRED_BACKUP
12739            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
12740                if (DEBUG_BACKUP) {
12741                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
12742                }
12743                return;
12744            }
12745
12746            // skip interfering stuff, then we're aligned with the backing implementation
12747            while ((type = parser.next()) == XmlPullParser.TEXT) { }
12748            synchronized (mPackages) {
12749                mSettings.readPreferredActivitiesLPw(parser, userId);
12750            }
12751        } catch (Exception e) {
12752            if (DEBUG_BACKUP) {
12753                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
12754            }
12755        }
12756    }
12757
12758    @Override
12759    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
12760            int sourceUserId, int targetUserId, int flags) {
12761        mContext.enforceCallingOrSelfPermission(
12762                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12763        int callingUid = Binder.getCallingUid();
12764        enforceOwnerRights(ownerPackage, callingUid);
12765        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12766        if (intentFilter.countActions() == 0) {
12767            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
12768            return;
12769        }
12770        synchronized (mPackages) {
12771            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
12772                    ownerPackage, targetUserId, flags);
12773            CrossProfileIntentResolver resolver =
12774                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12775            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
12776            // We have all those whose filter is equal. Now checking if the rest is equal as well.
12777            if (existing != null) {
12778                int size = existing.size();
12779                for (int i = 0; i < size; i++) {
12780                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
12781                        return;
12782                    }
12783                }
12784            }
12785            resolver.addFilter(newFilter);
12786            scheduleWritePackageRestrictionsLocked(sourceUserId);
12787        }
12788    }
12789
12790    @Override
12791    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
12792        mContext.enforceCallingOrSelfPermission(
12793                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12794        int callingUid = Binder.getCallingUid();
12795        enforceOwnerRights(ownerPackage, callingUid);
12796        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12797        synchronized (mPackages) {
12798            CrossProfileIntentResolver resolver =
12799                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12800            ArraySet<CrossProfileIntentFilter> set =
12801                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
12802            for (CrossProfileIntentFilter filter : set) {
12803                if (filter.getOwnerPackage().equals(ownerPackage)) {
12804                    resolver.removeFilter(filter);
12805                }
12806            }
12807            scheduleWritePackageRestrictionsLocked(sourceUserId);
12808        }
12809    }
12810
12811    // Enforcing that callingUid is owning pkg on userId
12812    private void enforceOwnerRights(String pkg, int callingUid) {
12813        // The system owns everything.
12814        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
12815            return;
12816        }
12817        int callingUserId = UserHandle.getUserId(callingUid);
12818        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
12819        if (pi == null) {
12820            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
12821                    + callingUserId);
12822        }
12823        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
12824            throw new SecurityException("Calling uid " + callingUid
12825                    + " does not own package " + pkg);
12826        }
12827    }
12828
12829    @Override
12830    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
12831        Intent intent = new Intent(Intent.ACTION_MAIN);
12832        intent.addCategory(Intent.CATEGORY_HOME);
12833
12834        final int callingUserId = UserHandle.getCallingUserId();
12835        List<ResolveInfo> list = queryIntentActivities(intent, null,
12836                PackageManager.GET_META_DATA, callingUserId);
12837        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
12838                true, false, false, callingUserId);
12839
12840        allHomeCandidates.clear();
12841        if (list != null) {
12842            for (ResolveInfo ri : list) {
12843                allHomeCandidates.add(ri);
12844            }
12845        }
12846        return (preferred == null || preferred.activityInfo == null)
12847                ? null
12848                : new ComponentName(preferred.activityInfo.packageName,
12849                        preferred.activityInfo.name);
12850    }
12851
12852    @Override
12853    public void setApplicationEnabledSetting(String appPackageName,
12854            int newState, int flags, int userId, String callingPackage) {
12855        if (!sUserManager.exists(userId)) return;
12856        if (callingPackage == null) {
12857            callingPackage = Integer.toString(Binder.getCallingUid());
12858        }
12859        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
12860    }
12861
12862    @Override
12863    public void setComponentEnabledSetting(ComponentName componentName,
12864            int newState, int flags, int userId) {
12865        if (!sUserManager.exists(userId)) return;
12866        setEnabledSetting(componentName.getPackageName(),
12867                componentName.getClassName(), newState, flags, userId, null);
12868    }
12869
12870    private void setEnabledSetting(final String packageName, String className, int newState,
12871            final int flags, int userId, String callingPackage) {
12872        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
12873              || newState == COMPONENT_ENABLED_STATE_ENABLED
12874              || newState == COMPONENT_ENABLED_STATE_DISABLED
12875              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
12876              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
12877            throw new IllegalArgumentException("Invalid new component state: "
12878                    + newState);
12879        }
12880        PackageSetting pkgSetting;
12881        final int uid = Binder.getCallingUid();
12882        final int permission = mContext.checkCallingOrSelfPermission(
12883                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12884        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
12885        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12886        boolean sendNow = false;
12887        boolean isApp = (className == null);
12888        String componentName = isApp ? packageName : className;
12889        int packageUid = -1;
12890        ArrayList<String> components;
12891
12892        // writer
12893        synchronized (mPackages) {
12894            pkgSetting = mSettings.mPackages.get(packageName);
12895            if (pkgSetting == null) {
12896                if (className == null) {
12897                    throw new IllegalArgumentException(
12898                            "Unknown package: " + packageName);
12899                }
12900                throw new IllegalArgumentException(
12901                        "Unknown component: " + packageName
12902                        + "/" + className);
12903            }
12904            // Allow root and verify that userId is not being specified by a different user
12905            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
12906                throw new SecurityException(
12907                        "Permission Denial: attempt to change component state from pid="
12908                        + Binder.getCallingPid()
12909                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
12910            }
12911            if (className == null) {
12912                // We're dealing with an application/package level state change
12913                if (pkgSetting.getEnabled(userId) == newState) {
12914                    // Nothing to do
12915                    return;
12916                }
12917                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
12918                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
12919                    // Don't care about who enables an app.
12920                    callingPackage = null;
12921                }
12922                pkgSetting.setEnabled(newState, userId, callingPackage);
12923                // pkgSetting.pkg.mSetEnabled = newState;
12924            } else {
12925                // We're dealing with a component level state change
12926                // First, verify that this is a valid class name.
12927                PackageParser.Package pkg = pkgSetting.pkg;
12928                if (pkg == null || !pkg.hasComponentClassName(className)) {
12929                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
12930                        throw new IllegalArgumentException("Component class " + className
12931                                + " does not exist in " + packageName);
12932                    } else {
12933                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
12934                                + className + " does not exist in " + packageName);
12935                    }
12936                }
12937                switch (newState) {
12938                case COMPONENT_ENABLED_STATE_ENABLED:
12939                    if (!pkgSetting.enableComponentLPw(className, userId)) {
12940                        return;
12941                    }
12942                    break;
12943                case COMPONENT_ENABLED_STATE_DISABLED:
12944                    if (!pkgSetting.disableComponentLPw(className, userId)) {
12945                        return;
12946                    }
12947                    break;
12948                case COMPONENT_ENABLED_STATE_DEFAULT:
12949                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
12950                        return;
12951                    }
12952                    break;
12953                default:
12954                    Slog.e(TAG, "Invalid new component state: " + newState);
12955                    return;
12956                }
12957            }
12958            scheduleWritePackageRestrictionsLocked(userId);
12959            components = mPendingBroadcasts.get(userId, packageName);
12960            final boolean newPackage = components == null;
12961            if (newPackage) {
12962                components = new ArrayList<String>();
12963            }
12964            if (!components.contains(componentName)) {
12965                components.add(componentName);
12966            }
12967            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12968                sendNow = true;
12969                // Purge entry from pending broadcast list if another one exists already
12970                // since we are sending one right away.
12971                mPendingBroadcasts.remove(userId, packageName);
12972            } else {
12973                if (newPackage) {
12974                    mPendingBroadcasts.put(userId, packageName, components);
12975                }
12976                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12977                    // Schedule a message
12978                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12979                }
12980            }
12981        }
12982
12983        long callingId = Binder.clearCallingIdentity();
12984        try {
12985            if (sendNow) {
12986                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12987                sendPackageChangedBroadcast(packageName,
12988                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12989            }
12990        } finally {
12991            Binder.restoreCallingIdentity(callingId);
12992        }
12993    }
12994
12995    private void sendPackageChangedBroadcast(String packageName,
12996            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12997        if (DEBUG_INSTALL)
12998            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12999                    + componentNames);
13000        Bundle extras = new Bundle(4);
13001        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13002        String nameList[] = new String[componentNames.size()];
13003        componentNames.toArray(nameList);
13004        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13005        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13006        extras.putInt(Intent.EXTRA_UID, packageUid);
13007        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13008                new int[] {UserHandle.getUserId(packageUid)});
13009    }
13010
13011    @Override
13012    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13013        if (!sUserManager.exists(userId)) return;
13014        final int uid = Binder.getCallingUid();
13015        final int permission = mContext.checkCallingOrSelfPermission(
13016                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13017        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13018        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13019        // writer
13020        synchronized (mPackages) {
13021            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
13022                    uid, userId)) {
13023                scheduleWritePackageRestrictionsLocked(userId);
13024            }
13025        }
13026    }
13027
13028    @Override
13029    public String getInstallerPackageName(String packageName) {
13030        // reader
13031        synchronized (mPackages) {
13032            return mSettings.getInstallerPackageNameLPr(packageName);
13033        }
13034    }
13035
13036    @Override
13037    public int getApplicationEnabledSetting(String packageName, int userId) {
13038        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13039        int uid = Binder.getCallingUid();
13040        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13041        // reader
13042        synchronized (mPackages) {
13043            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13044        }
13045    }
13046
13047    @Override
13048    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13049        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13050        int uid = Binder.getCallingUid();
13051        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13052        // reader
13053        synchronized (mPackages) {
13054            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13055        }
13056    }
13057
13058    @Override
13059    public void enterSafeMode() {
13060        enforceSystemOrRoot("Only the system can request entering safe mode");
13061
13062        if (!mSystemReady) {
13063            mSafeMode = true;
13064        }
13065    }
13066
13067    @Override
13068    public void systemReady() {
13069        mSystemReady = true;
13070
13071        // Read the compatibilty setting when the system is ready.
13072        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13073                mContext.getContentResolver(),
13074                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13075        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13076        if (DEBUG_SETTINGS) {
13077            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13078        }
13079
13080        synchronized (mPackages) {
13081            // Verify that all of the preferred activity components actually
13082            // exist.  It is possible for applications to be updated and at
13083            // that point remove a previously declared activity component that
13084            // had been set as a preferred activity.  We try to clean this up
13085            // the next time we encounter that preferred activity, but it is
13086            // possible for the user flow to never be able to return to that
13087            // situation so here we do a sanity check to make sure we haven't
13088            // left any junk around.
13089            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13090            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13091                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13092                removed.clear();
13093                for (PreferredActivity pa : pir.filterSet()) {
13094                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13095                        removed.add(pa);
13096                    }
13097                }
13098                if (removed.size() > 0) {
13099                    for (int r=0; r<removed.size(); r++) {
13100                        PreferredActivity pa = removed.get(r);
13101                        Slog.w(TAG, "Removing dangling preferred activity: "
13102                                + pa.mPref.mComponent);
13103                        pir.removeFilter(pa);
13104                    }
13105                    mSettings.writePackageRestrictionsLPr(
13106                            mSettings.mPreferredActivities.keyAt(i));
13107                }
13108            }
13109        }
13110        sUserManager.systemReady();
13111
13112        // Kick off any messages waiting for system ready
13113        if (mPostSystemReadyMessages != null) {
13114            for (Message msg : mPostSystemReadyMessages) {
13115                msg.sendToTarget();
13116            }
13117            mPostSystemReadyMessages = null;
13118        }
13119
13120        // Watch for external volumes that come and go over time
13121        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13122        storage.registerListener(mStorageListener);
13123
13124        mInstallerService.systemReady();
13125    }
13126
13127    @Override
13128    public boolean isSafeMode() {
13129        return mSafeMode;
13130    }
13131
13132    @Override
13133    public boolean hasSystemUidErrors() {
13134        return mHasSystemUidErrors;
13135    }
13136
13137    static String arrayToString(int[] array) {
13138        StringBuffer buf = new StringBuffer(128);
13139        buf.append('[');
13140        if (array != null) {
13141            for (int i=0; i<array.length; i++) {
13142                if (i > 0) buf.append(", ");
13143                buf.append(array[i]);
13144            }
13145        }
13146        buf.append(']');
13147        return buf.toString();
13148    }
13149
13150    static class DumpState {
13151        public static final int DUMP_LIBS = 1 << 0;
13152        public static final int DUMP_FEATURES = 1 << 1;
13153        public static final int DUMP_RESOLVERS = 1 << 2;
13154        public static final int DUMP_PERMISSIONS = 1 << 3;
13155        public static final int DUMP_PACKAGES = 1 << 4;
13156        public static final int DUMP_SHARED_USERS = 1 << 5;
13157        public static final int DUMP_MESSAGES = 1 << 6;
13158        public static final int DUMP_PROVIDERS = 1 << 7;
13159        public static final int DUMP_VERIFIERS = 1 << 8;
13160        public static final int DUMP_PREFERRED = 1 << 9;
13161        public static final int DUMP_PREFERRED_XML = 1 << 10;
13162        public static final int DUMP_KEYSETS = 1 << 11;
13163        public static final int DUMP_VERSION = 1 << 12;
13164        public static final int DUMP_INSTALLS = 1 << 13;
13165        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13166        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13167
13168        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13169
13170        private int mTypes;
13171
13172        private int mOptions;
13173
13174        private boolean mTitlePrinted;
13175
13176        private SharedUserSetting mSharedUser;
13177
13178        public boolean isDumping(int type) {
13179            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13180                return true;
13181            }
13182
13183            return (mTypes & type) != 0;
13184        }
13185
13186        public void setDump(int type) {
13187            mTypes |= type;
13188        }
13189
13190        public boolean isOptionEnabled(int option) {
13191            return (mOptions & option) != 0;
13192        }
13193
13194        public void setOptionEnabled(int option) {
13195            mOptions |= option;
13196        }
13197
13198        public boolean onTitlePrinted() {
13199            final boolean printed = mTitlePrinted;
13200            mTitlePrinted = true;
13201            return printed;
13202        }
13203
13204        public boolean getTitlePrinted() {
13205            return mTitlePrinted;
13206        }
13207
13208        public void setTitlePrinted(boolean enabled) {
13209            mTitlePrinted = enabled;
13210        }
13211
13212        public SharedUserSetting getSharedUser() {
13213            return mSharedUser;
13214        }
13215
13216        public void setSharedUser(SharedUserSetting user) {
13217            mSharedUser = user;
13218        }
13219    }
13220
13221    @Override
13222    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13223        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13224                != PackageManager.PERMISSION_GRANTED) {
13225            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13226                    + Binder.getCallingPid()
13227                    + ", uid=" + Binder.getCallingUid()
13228                    + " without permission "
13229                    + android.Manifest.permission.DUMP);
13230            return;
13231        }
13232
13233        DumpState dumpState = new DumpState();
13234        boolean fullPreferred = false;
13235        boolean checkin = false;
13236
13237        String packageName = null;
13238
13239        int opti = 0;
13240        while (opti < args.length) {
13241            String opt = args[opti];
13242            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13243                break;
13244            }
13245            opti++;
13246
13247            if ("-a".equals(opt)) {
13248                // Right now we only know how to print all.
13249            } else if ("-h".equals(opt)) {
13250                pw.println("Package manager dump options:");
13251                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13252                pw.println("    --checkin: dump for a checkin");
13253                pw.println("    -f: print details of intent filters");
13254                pw.println("    -h: print this help");
13255                pw.println("  cmd may be one of:");
13256                pw.println("    l[ibraries]: list known shared libraries");
13257                pw.println("    f[ibraries]: list device features");
13258                pw.println("    k[eysets]: print known keysets");
13259                pw.println("    r[esolvers]: dump intent resolvers");
13260                pw.println("    perm[issions]: dump permissions");
13261                pw.println("    pref[erred]: print preferred package settings");
13262                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13263                pw.println("    prov[iders]: dump content providers");
13264                pw.println("    p[ackages]: dump installed packages");
13265                pw.println("    s[hared-users]: dump shared user IDs");
13266                pw.println("    m[essages]: print collected runtime messages");
13267                pw.println("    v[erifiers]: print package verifier info");
13268                pw.println("    version: print database version info");
13269                pw.println("    write: write current settings now");
13270                pw.println("    <package.name>: info about given package");
13271                pw.println("    installs: details about install sessions");
13272                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13273                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13274                return;
13275            } else if ("--checkin".equals(opt)) {
13276                checkin = true;
13277            } else if ("-f".equals(opt)) {
13278                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13279            } else {
13280                pw.println("Unknown argument: " + opt + "; use -h for help");
13281            }
13282        }
13283
13284        // Is the caller requesting to dump a particular piece of data?
13285        if (opti < args.length) {
13286            String cmd = args[opti];
13287            opti++;
13288            // Is this a package name?
13289            if ("android".equals(cmd) || cmd.contains(".")) {
13290                packageName = cmd;
13291                // When dumping a single package, we always dump all of its
13292                // filter information since the amount of data will be reasonable.
13293                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13294            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13295                dumpState.setDump(DumpState.DUMP_LIBS);
13296            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13297                dumpState.setDump(DumpState.DUMP_FEATURES);
13298            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13299                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13300            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13301                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13302            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13303                dumpState.setDump(DumpState.DUMP_PREFERRED);
13304            } else if ("preferred-xml".equals(cmd)) {
13305                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13306                if (opti < args.length && "--full".equals(args[opti])) {
13307                    fullPreferred = true;
13308                    opti++;
13309                }
13310            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13311                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13312            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13313                dumpState.setDump(DumpState.DUMP_PACKAGES);
13314            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13315                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13316            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13317                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13318            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13319                dumpState.setDump(DumpState.DUMP_MESSAGES);
13320            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13321                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13322            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13323                    || "intent-filter-verifiers".equals(cmd)) {
13324                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13325            } else if ("version".equals(cmd)) {
13326                dumpState.setDump(DumpState.DUMP_VERSION);
13327            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13328                dumpState.setDump(DumpState.DUMP_KEYSETS);
13329            } else if ("installs".equals(cmd)) {
13330                dumpState.setDump(DumpState.DUMP_INSTALLS);
13331            } else if ("write".equals(cmd)) {
13332                synchronized (mPackages) {
13333                    mSettings.writeLPr();
13334                    pw.println("Settings written.");
13335                    return;
13336                }
13337            }
13338        }
13339
13340        if (checkin) {
13341            pw.println("vers,1");
13342        }
13343
13344        // reader
13345        synchronized (mPackages) {
13346            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13347                if (!checkin) {
13348                    if (dumpState.onTitlePrinted())
13349                        pw.println();
13350                    pw.println("Database versions:");
13351                    pw.print("  SDK Version:");
13352                    pw.print(" internal=");
13353                    pw.print(mSettings.mInternalSdkPlatform);
13354                    pw.print(" external=");
13355                    pw.println(mSettings.mExternalSdkPlatform);
13356                    pw.print("  DB Version:");
13357                    pw.print(" internal=");
13358                    pw.print(mSettings.mInternalDatabaseVersion);
13359                    pw.print(" external=");
13360                    pw.println(mSettings.mExternalDatabaseVersion);
13361                }
13362            }
13363
13364            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13365                if (!checkin) {
13366                    if (dumpState.onTitlePrinted())
13367                        pw.println();
13368                    pw.println("Verifiers:");
13369                    pw.print("  Required: ");
13370                    pw.print(mRequiredVerifierPackage);
13371                    pw.print(" (uid=");
13372                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13373                    pw.println(")");
13374                } else if (mRequiredVerifierPackage != null) {
13375                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13376                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13377                }
13378            }
13379
13380            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13381                    packageName == null) {
13382                if (mIntentFilterVerifierComponent != null) {
13383                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13384                    if (!checkin) {
13385                        if (dumpState.onTitlePrinted())
13386                            pw.println();
13387                        pw.println("Intent Filter Verifier:");
13388                        pw.print("  Using: ");
13389                        pw.print(verifierPackageName);
13390                        pw.print(" (uid=");
13391                        pw.print(getPackageUid(verifierPackageName, 0));
13392                        pw.println(")");
13393                    } else if (verifierPackageName != null) {
13394                        pw.print("ifv,"); pw.print(verifierPackageName);
13395                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13396                    }
13397                } else {
13398                    pw.println();
13399                    pw.println("No Intent Filter Verifier available!");
13400                }
13401            }
13402
13403            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13404                boolean printedHeader = false;
13405                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13406                while (it.hasNext()) {
13407                    String name = it.next();
13408                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13409                    if (!checkin) {
13410                        if (!printedHeader) {
13411                            if (dumpState.onTitlePrinted())
13412                                pw.println();
13413                            pw.println("Libraries:");
13414                            printedHeader = true;
13415                        }
13416                        pw.print("  ");
13417                    } else {
13418                        pw.print("lib,");
13419                    }
13420                    pw.print(name);
13421                    if (!checkin) {
13422                        pw.print(" -> ");
13423                    }
13424                    if (ent.path != null) {
13425                        if (!checkin) {
13426                            pw.print("(jar) ");
13427                            pw.print(ent.path);
13428                        } else {
13429                            pw.print(",jar,");
13430                            pw.print(ent.path);
13431                        }
13432                    } else {
13433                        if (!checkin) {
13434                            pw.print("(apk) ");
13435                            pw.print(ent.apk);
13436                        } else {
13437                            pw.print(",apk,");
13438                            pw.print(ent.apk);
13439                        }
13440                    }
13441                    pw.println();
13442                }
13443            }
13444
13445            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
13446                if (dumpState.onTitlePrinted())
13447                    pw.println();
13448                if (!checkin) {
13449                    pw.println("Features:");
13450                }
13451                Iterator<String> it = mAvailableFeatures.keySet().iterator();
13452                while (it.hasNext()) {
13453                    String name = it.next();
13454                    if (!checkin) {
13455                        pw.print("  ");
13456                    } else {
13457                        pw.print("feat,");
13458                    }
13459                    pw.println(name);
13460                }
13461            }
13462
13463            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
13464                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
13465                        : "Activity Resolver Table:", "  ", packageName,
13466                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13467                    dumpState.setTitlePrinted(true);
13468                }
13469                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
13470                        : "Receiver Resolver Table:", "  ", packageName,
13471                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13472                    dumpState.setTitlePrinted(true);
13473                }
13474                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
13475                        : "Service Resolver Table:", "  ", packageName,
13476                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13477                    dumpState.setTitlePrinted(true);
13478                }
13479                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
13480                        : "Provider Resolver Table:", "  ", packageName,
13481                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13482                    dumpState.setTitlePrinted(true);
13483                }
13484            }
13485
13486            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
13487                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13488                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13489                    int user = mSettings.mPreferredActivities.keyAt(i);
13490                    if (pir.dump(pw,
13491                            dumpState.getTitlePrinted()
13492                                ? "\nPreferred Activities User " + user + ":"
13493                                : "Preferred Activities User " + user + ":", "  ",
13494                            packageName, true, false)) {
13495                        dumpState.setTitlePrinted(true);
13496                    }
13497                }
13498            }
13499
13500            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
13501                pw.flush();
13502                FileOutputStream fout = new FileOutputStream(fd);
13503                BufferedOutputStream str = new BufferedOutputStream(fout);
13504                XmlSerializer serializer = new FastXmlSerializer();
13505                try {
13506                    serializer.setOutput(str, "utf-8");
13507                    serializer.startDocument(null, true);
13508                    serializer.setFeature(
13509                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
13510                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
13511                    serializer.endDocument();
13512                    serializer.flush();
13513                } catch (IllegalArgumentException e) {
13514                    pw.println("Failed writing: " + e);
13515                } catch (IllegalStateException e) {
13516                    pw.println("Failed writing: " + e);
13517                } catch (IOException e) {
13518                    pw.println("Failed writing: " + e);
13519                }
13520            }
13521
13522            if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) {
13523                pw.println();
13524                int count = mSettings.mPackages.size();
13525                if (count == 0) {
13526                    pw.println("No domain preferred apps!");
13527                    pw.println();
13528                } else {
13529                    final String prefix = "  ";
13530                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
13531                    if (allPackageSettings.size() == 0) {
13532                        pw.println("No domain preferred apps!");
13533                        pw.println();
13534                    } else {
13535                        pw.println("Domain preferred apps status:");
13536                        pw.println();
13537                        count = 0;
13538                        for (PackageSetting ps : allPackageSettings) {
13539                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13540                            if (ivi == null || ivi.getPackageName() == null) continue;
13541                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
13542                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
13543                            pw.println(prefix + "Status: " + ivi.getStatusString());
13544                            pw.println();
13545                            count++;
13546                        }
13547                        if (count == 0) {
13548                            pw.println(prefix + "No domain preferred app status!");
13549                            pw.println();
13550                        }
13551                        for (int userId : sUserManager.getUserIds()) {
13552                            pw.println("Domain preferred apps for User " + userId + ":");
13553                            pw.println();
13554                            count = 0;
13555                            for (PackageSetting ps : allPackageSettings) {
13556                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13557                                if (ivi == null || ivi.getPackageName() == null) {
13558                                    continue;
13559                                }
13560                                final int status = ps.getDomainVerificationStatusForUser(userId);
13561                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
13562                                    continue;
13563                                }
13564                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
13565                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
13566                                String statusStr = IntentFilterVerificationInfo.
13567                                        getStatusStringFromValue(status);
13568                                pw.println(prefix + "Status: " + statusStr);
13569                                pw.println();
13570                                count++;
13571                            }
13572                            if (count == 0) {
13573                                pw.println(prefix + "No domain preferred apps!");
13574                                pw.println();
13575                            }
13576                        }
13577                    }
13578                }
13579            }
13580
13581            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
13582                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
13583                if (packageName == null) {
13584                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
13585                        if (iperm == 0) {
13586                            if (dumpState.onTitlePrinted())
13587                                pw.println();
13588                            pw.println("AppOp Permissions:");
13589                        }
13590                        pw.print("  AppOp Permission ");
13591                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
13592                        pw.println(":");
13593                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
13594                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
13595                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
13596                        }
13597                    }
13598                }
13599            }
13600
13601            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
13602                boolean printedSomething = false;
13603                for (PackageParser.Provider p : mProviders.mProviders.values()) {
13604                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13605                        continue;
13606                    }
13607                    if (!printedSomething) {
13608                        if (dumpState.onTitlePrinted())
13609                            pw.println();
13610                        pw.println("Registered ContentProviders:");
13611                        printedSomething = true;
13612                    }
13613                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
13614                    pw.print("    "); pw.println(p.toString());
13615                }
13616                printedSomething = false;
13617                for (Map.Entry<String, PackageParser.Provider> entry :
13618                        mProvidersByAuthority.entrySet()) {
13619                    PackageParser.Provider p = entry.getValue();
13620                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13621                        continue;
13622                    }
13623                    if (!printedSomething) {
13624                        if (dumpState.onTitlePrinted())
13625                            pw.println();
13626                        pw.println("ContentProvider Authorities:");
13627                        printedSomething = true;
13628                    }
13629                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
13630                    pw.print("    "); pw.println(p.toString());
13631                    if (p.info != null && p.info.applicationInfo != null) {
13632                        final String appInfo = p.info.applicationInfo.toString();
13633                        pw.print("      applicationInfo="); pw.println(appInfo);
13634                    }
13635                }
13636            }
13637
13638            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
13639                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
13640            }
13641
13642            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
13643                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
13644            }
13645
13646            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
13647                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
13648            }
13649
13650            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
13651                // XXX should handle packageName != null by dumping only install data that
13652                // the given package is involved with.
13653                if (dumpState.onTitlePrinted()) pw.println();
13654                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
13655            }
13656
13657            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
13658                if (dumpState.onTitlePrinted()) pw.println();
13659                mSettings.dumpReadMessagesLPr(pw, dumpState);
13660
13661                pw.println();
13662                pw.println("Package warning messages:");
13663                BufferedReader in = null;
13664                String line = null;
13665                try {
13666                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
13667                    while ((line = in.readLine()) != null) {
13668                        if (line.contains("ignored: updated version")) continue;
13669                        pw.println(line);
13670                    }
13671                } catch (IOException ignored) {
13672                } finally {
13673                    IoUtils.closeQuietly(in);
13674                }
13675            }
13676
13677            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
13678                BufferedReader in = null;
13679                String line = null;
13680                try {
13681                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
13682                    while ((line = in.readLine()) != null) {
13683                        if (line.contains("ignored: updated version")) continue;
13684                        pw.print("msg,");
13685                        pw.println(line);
13686                    }
13687                } catch (IOException ignored) {
13688                } finally {
13689                    IoUtils.closeQuietly(in);
13690                }
13691            }
13692        }
13693    }
13694
13695    // ------- apps on sdcard specific code -------
13696    static final boolean DEBUG_SD_INSTALL = false;
13697
13698    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
13699
13700    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
13701
13702    private boolean mMediaMounted = false;
13703
13704    static String getEncryptKey() {
13705        try {
13706            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
13707                    SD_ENCRYPTION_KEYSTORE_NAME);
13708            if (sdEncKey == null) {
13709                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
13710                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
13711                if (sdEncKey == null) {
13712                    Slog.e(TAG, "Failed to create encryption keys");
13713                    return null;
13714                }
13715            }
13716            return sdEncKey;
13717        } catch (NoSuchAlgorithmException nsae) {
13718            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
13719            return null;
13720        } catch (IOException ioe) {
13721            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
13722            return null;
13723        }
13724    }
13725
13726    /*
13727     * Update media status on PackageManager.
13728     */
13729    @Override
13730    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
13731        int callingUid = Binder.getCallingUid();
13732        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
13733            throw new SecurityException("Media status can only be updated by the system");
13734        }
13735        // reader; this apparently protects mMediaMounted, but should probably
13736        // be a different lock in that case.
13737        synchronized (mPackages) {
13738            Log.i(TAG, "Updating external media status from "
13739                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
13740                    + (mediaStatus ? "mounted" : "unmounted"));
13741            if (DEBUG_SD_INSTALL)
13742                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
13743                        + ", mMediaMounted=" + mMediaMounted);
13744            if (mediaStatus == mMediaMounted) {
13745                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
13746                        : 0, -1);
13747                mHandler.sendMessage(msg);
13748                return;
13749            }
13750            mMediaMounted = mediaStatus;
13751        }
13752        // Queue up an async operation since the package installation may take a
13753        // little while.
13754        mHandler.post(new Runnable() {
13755            public void run() {
13756                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
13757            }
13758        });
13759    }
13760
13761    /**
13762     * Called by MountService when the initial ASECs to scan are available.
13763     * Should block until all the ASEC containers are finished being scanned.
13764     */
13765    public void scanAvailableAsecs() {
13766        updateExternalMediaStatusInner(true, false, false);
13767        if (mShouldRestoreconData) {
13768            SELinuxMMAC.setRestoreconDone();
13769            mShouldRestoreconData = false;
13770        }
13771    }
13772
13773    /*
13774     * Collect information of applications on external media, map them against
13775     * existing containers and update information based on current mount status.
13776     * Please note that we always have to report status if reportStatus has been
13777     * set to true especially when unloading packages.
13778     */
13779    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
13780            boolean externalStorage) {
13781        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
13782        int[] uidArr = EmptyArray.INT;
13783
13784        final String[] list = PackageHelper.getSecureContainerList();
13785        if (ArrayUtils.isEmpty(list)) {
13786            Log.i(TAG, "No secure containers found");
13787        } else {
13788            // Process list of secure containers and categorize them
13789            // as active or stale based on their package internal state.
13790
13791            // reader
13792            synchronized (mPackages) {
13793                for (String cid : list) {
13794                    // Leave stages untouched for now; installer service owns them
13795                    if (PackageInstallerService.isStageName(cid)) continue;
13796
13797                    if (DEBUG_SD_INSTALL)
13798                        Log.i(TAG, "Processing container " + cid);
13799                    String pkgName = getAsecPackageName(cid);
13800                    if (pkgName == null) {
13801                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
13802                        continue;
13803                    }
13804                    if (DEBUG_SD_INSTALL)
13805                        Log.i(TAG, "Looking for pkg : " + pkgName);
13806
13807                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
13808                    if (ps == null) {
13809                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
13810                        continue;
13811                    }
13812
13813                    /*
13814                     * Skip packages that are not external if we're unmounting
13815                     * external storage.
13816                     */
13817                    if (externalStorage && !isMounted && !isExternal(ps)) {
13818                        continue;
13819                    }
13820
13821                    final AsecInstallArgs args = new AsecInstallArgs(cid,
13822                            getAppDexInstructionSets(ps), ps.isForwardLocked());
13823                    // The package status is changed only if the code path
13824                    // matches between settings and the container id.
13825                    if (ps.codePathString != null
13826                            && ps.codePathString.startsWith(args.getCodePath())) {
13827                        if (DEBUG_SD_INSTALL) {
13828                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
13829                                    + " at code path: " + ps.codePathString);
13830                        }
13831
13832                        // We do have a valid package installed on sdcard
13833                        processCids.put(args, ps.codePathString);
13834                        final int uid = ps.appId;
13835                        if (uid != -1) {
13836                            uidArr = ArrayUtils.appendInt(uidArr, uid);
13837                        }
13838                    } else {
13839                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
13840                                + ps.codePathString);
13841                    }
13842                }
13843            }
13844
13845            Arrays.sort(uidArr);
13846        }
13847
13848        // Process packages with valid entries.
13849        if (isMounted) {
13850            if (DEBUG_SD_INSTALL)
13851                Log.i(TAG, "Loading packages");
13852            loadMediaPackages(processCids, uidArr);
13853            startCleaningPackages();
13854            mInstallerService.onSecureContainersAvailable();
13855        } else {
13856            if (DEBUG_SD_INSTALL)
13857                Log.i(TAG, "Unloading packages");
13858            unloadMediaPackages(processCids, uidArr, reportStatus);
13859        }
13860    }
13861
13862    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13863            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
13864        final int size = infos.size();
13865        final String[] packageNames = new String[size];
13866        final int[] packageUids = new int[size];
13867        for (int i = 0; i < size; i++) {
13868            final ApplicationInfo info = infos.get(i);
13869            packageNames[i] = info.packageName;
13870            packageUids[i] = info.uid;
13871        }
13872        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
13873                finishedReceiver);
13874    }
13875
13876    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13877            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
13878        sendResourcesChangedBroadcast(mediaStatus, replacing,
13879                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
13880    }
13881
13882    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13883            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
13884        int size = pkgList.length;
13885        if (size > 0) {
13886            // Send broadcasts here
13887            Bundle extras = new Bundle();
13888            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13889            if (uidArr != null) {
13890                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
13891            }
13892            if (replacing) {
13893                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
13894            }
13895            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
13896                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
13897            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
13898        }
13899    }
13900
13901   /*
13902     * Look at potentially valid container ids from processCids If package
13903     * information doesn't match the one on record or package scanning fails,
13904     * the cid is added to list of removeCids. We currently don't delete stale
13905     * containers.
13906     */
13907    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
13908        ArrayList<String> pkgList = new ArrayList<String>();
13909        Set<AsecInstallArgs> keys = processCids.keySet();
13910
13911        for (AsecInstallArgs args : keys) {
13912            String codePath = processCids.get(args);
13913            if (DEBUG_SD_INSTALL)
13914                Log.i(TAG, "Loading container : " + args.cid);
13915            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13916            try {
13917                // Make sure there are no container errors first.
13918                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
13919                    Slog.e(TAG, "Failed to mount cid : " + args.cid
13920                            + " when installing from sdcard");
13921                    continue;
13922                }
13923                // Check code path here.
13924                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
13925                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
13926                            + " does not match one in settings " + codePath);
13927                    continue;
13928                }
13929                // Parse package
13930                int parseFlags = mDefParseFlags;
13931                if (args.isExternalAsec()) {
13932                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
13933                }
13934                if (args.isFwdLocked()) {
13935                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
13936                }
13937
13938                synchronized (mInstallLock) {
13939                    PackageParser.Package pkg = null;
13940                    try {
13941                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
13942                    } catch (PackageManagerException e) {
13943                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
13944                    }
13945                    // Scan the package
13946                    if (pkg != null) {
13947                        /*
13948                         * TODO why is the lock being held? doPostInstall is
13949                         * called in other places without the lock. This needs
13950                         * to be straightened out.
13951                         */
13952                        // writer
13953                        synchronized (mPackages) {
13954                            retCode = PackageManager.INSTALL_SUCCEEDED;
13955                            pkgList.add(pkg.packageName);
13956                            // Post process args
13957                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
13958                                    pkg.applicationInfo.uid);
13959                        }
13960                    } else {
13961                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
13962                    }
13963                }
13964
13965            } finally {
13966                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
13967                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
13968                }
13969            }
13970        }
13971        // writer
13972        synchronized (mPackages) {
13973            // If the platform SDK has changed since the last time we booted,
13974            // we need to re-grant app permission to catch any new ones that
13975            // appear. This is really a hack, and means that apps can in some
13976            // cases get permissions that the user didn't initially explicitly
13977            // allow... it would be nice to have some better way to handle
13978            // this situation.
13979            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
13980            if (regrantPermissions)
13981                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
13982                        + mSdkVersion + "; regranting permissions for external storage");
13983            mSettings.mExternalSdkPlatform = mSdkVersion;
13984
13985            // Make sure group IDs have been assigned, and any permission
13986            // changes in other apps are accounted for
13987            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
13988                    | (regrantPermissions
13989                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
13990                            : 0));
13991
13992            mSettings.updateExternalDatabaseVersion();
13993
13994            // can downgrade to reader
13995            // Persist settings
13996            mSettings.writeLPr();
13997        }
13998        // Send a broadcast to let everyone know we are done processing
13999        if (pkgList.size() > 0) {
14000            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14001        }
14002    }
14003
14004   /*
14005     * Utility method to unload a list of specified containers
14006     */
14007    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14008        // Just unmount all valid containers.
14009        for (AsecInstallArgs arg : cidArgs) {
14010            synchronized (mInstallLock) {
14011                arg.doPostDeleteLI(false);
14012           }
14013       }
14014   }
14015
14016    /*
14017     * Unload packages mounted on external media. This involves deleting package
14018     * data from internal structures, sending broadcasts about diabled packages,
14019     * gc'ing to free up references, unmounting all secure containers
14020     * corresponding to packages on external media, and posting a
14021     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14022     * that we always have to post this message if status has been requested no
14023     * matter what.
14024     */
14025    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14026            final boolean reportStatus) {
14027        if (DEBUG_SD_INSTALL)
14028            Log.i(TAG, "unloading media packages");
14029        ArrayList<String> pkgList = new ArrayList<String>();
14030        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14031        final Set<AsecInstallArgs> keys = processCids.keySet();
14032        for (AsecInstallArgs args : keys) {
14033            String pkgName = args.getPackageName();
14034            if (DEBUG_SD_INSTALL)
14035                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14036            // Delete package internally
14037            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14038            synchronized (mInstallLock) {
14039                boolean res = deletePackageLI(pkgName, null, false, null, null,
14040                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14041                if (res) {
14042                    pkgList.add(pkgName);
14043                } else {
14044                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14045                    failedList.add(args);
14046                }
14047            }
14048        }
14049
14050        // reader
14051        synchronized (mPackages) {
14052            // We didn't update the settings after removing each package;
14053            // write them now for all packages.
14054            mSettings.writeLPr();
14055        }
14056
14057        // We have to absolutely send UPDATED_MEDIA_STATUS only
14058        // after confirming that all the receivers processed the ordered
14059        // broadcast when packages get disabled, force a gc to clean things up.
14060        // and unload all the containers.
14061        if (pkgList.size() > 0) {
14062            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14063                    new IIntentReceiver.Stub() {
14064                public void performReceive(Intent intent, int resultCode, String data,
14065                        Bundle extras, boolean ordered, boolean sticky,
14066                        int sendingUser) throws RemoteException {
14067                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14068                            reportStatus ? 1 : 0, 1, keys);
14069                    mHandler.sendMessage(msg);
14070                }
14071            });
14072        } else {
14073            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14074                    keys);
14075            mHandler.sendMessage(msg);
14076        }
14077    }
14078
14079    private void loadPrivatePackages(VolumeInfo vol) {
14080        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14081        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14082        synchronized (mPackages) {
14083            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14084            for (PackageSetting ps : packages) {
14085                synchronized (mInstallLock) {
14086                    final PackageParser.Package pkg;
14087                    try {
14088                        pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14089                        loaded.add(pkg.applicationInfo);
14090                    } catch (PackageManagerException e) {
14091                        Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14092                    }
14093                }
14094            }
14095
14096            // TODO: regrant any permissions that changed based since original install
14097
14098            mSettings.writeLPr();
14099        }
14100
14101        Slog.d(TAG, "Loaded packages " + loaded);
14102        sendResourcesChangedBroadcast(true, false, loaded, null);
14103    }
14104
14105    private void unloadPrivatePackages(VolumeInfo vol) {
14106        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14107        synchronized (mPackages) {
14108            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14109            for (PackageSetting ps : packages) {
14110                if (ps.pkg == null) continue;
14111                synchronized (mInstallLock) {
14112                    final ApplicationInfo info = ps.pkg.applicationInfo;
14113                    final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14114                    if (deletePackageLI(ps.name, null, false, null, null,
14115                            PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14116                        unloaded.add(info);
14117                    } else {
14118                        Slog.w(TAG, "Failed to unload " + ps.codePath);
14119                    }
14120                }
14121            }
14122
14123            mSettings.writeLPr();
14124        }
14125
14126        Slog.d(TAG, "Unloaded packages " + unloaded);
14127        sendResourcesChangedBroadcast(false, false, unloaded, null);
14128    }
14129
14130    @Override
14131    public void movePackage(final String packageName, final IPackageMoveObserver observer,
14132            final int flags) {
14133        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14134
14135        final int installFlags;
14136        if ((flags & MOVE_INTERNAL) != 0) {
14137            installFlags = INSTALL_INTERNAL;
14138        } else if ((flags & MOVE_EXTERNAL_MEDIA) != 0) {
14139            installFlags = INSTALL_EXTERNAL;
14140        } else {
14141            throw new IllegalArgumentException("Unsupported move flags " + flags);
14142        }
14143
14144        try {
14145            movePackageInternal(packageName, null, installFlags, false, observer);
14146        } catch (PackageManagerException e) {
14147            Slog.d(TAG, "Failed to move " + packageName, e);
14148            try {
14149                observer.packageMoved(packageName, e.error);
14150            } catch (RemoteException ignored) {
14151            }
14152        }
14153    }
14154
14155    @Override
14156    public void movePackageAndData(final String packageName, final String volumeUuid,
14157            final IPackageMoveObserver observer) {
14158        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14159        try {
14160            movePackageInternal(packageName, volumeUuid, INSTALL_INTERNAL, true, observer);
14161        } catch (PackageManagerException e) {
14162            Slog.d(TAG, "Failed to move " + packageName, e);
14163            try {
14164                observer.packageMoved(packageName, e.error);
14165            } catch (RemoteException ignored) {
14166            }
14167        }
14168    }
14169
14170    private void movePackageInternal(final String packageName, String volumeUuid, int installFlags,
14171            boolean andData, final IPackageMoveObserver observer) throws PackageManagerException {
14172        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14173
14174        final String currentVolumeUuid;
14175        final File codeFile;
14176        final String installerPackageName;
14177        final String packageAbiOverride;
14178        final int appId;
14179        final String seinfo;
14180
14181        // reader
14182        synchronized (mPackages) {
14183            final PackageParser.Package pkg = mPackages.get(packageName);
14184            final PackageSetting ps = mSettings.mPackages.get(packageName);
14185            if (pkg == null || ps == null) {
14186                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14187            }
14188
14189            if (pkg.applicationInfo.isSystemApp()) {
14190                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14191                        "Cannot move system application");
14192            } else if (pkg.mOperationPending) {
14193                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14194                        "Attempt to move package which has pending operations");
14195            }
14196
14197            // TODO: yell if already in desired location
14198
14199            pkg.mOperationPending = true;
14200
14201            currentVolumeUuid = ps.volumeUuid;
14202            codeFile = new File(pkg.codePath);
14203            installerPackageName = ps.installerPackageName;
14204            packageAbiOverride = ps.cpuAbiOverrideString;
14205            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14206            seinfo = pkg.applicationInfo.seinfo;
14207        }
14208
14209        if (andData) {
14210            Slog.d(TAG, "Moving " + packageName + " private data from " + currentVolumeUuid + " to "
14211                    + volumeUuid);
14212            synchronized (mInstallLock) {
14213                if (mInstaller.moveUserDataDirs(currentVolumeUuid, volumeUuid, packageName, appId,
14214                        seinfo) != 0) {
14215                    synchronized (mPackages) {
14216                        final PackageParser.Package pkg = mPackages.get(packageName);
14217                        if (pkg != null) {
14218                            pkg.mOperationPending = false;
14219                        }
14220                    }
14221
14222                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14223                            "Failed to move private data");
14224                }
14225            }
14226        }
14227
14228        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14229            @Override
14230            public void onUserActionRequired(Intent intent) throws RemoteException {
14231                throw new IllegalStateException();
14232            }
14233
14234            @Override
14235            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14236                    Bundle extras) throws RemoteException {
14237                Slog.d(TAG, "Install result for move: "
14238                        + PackageManager.installStatusToString(returnCode, msg));
14239
14240                // We usually have a new package now after the install, but if
14241                // we failed we need to clear the pending flag on the original
14242                // package object.
14243                synchronized (mPackages) {
14244                    final PackageParser.Package pkg = mPackages.get(packageName);
14245                    if (pkg != null) {
14246                        pkg.mOperationPending = false;
14247                    }
14248                }
14249
14250                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14251                switch (status) {
14252                    case PackageInstaller.STATUS_SUCCESS:
14253                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
14254                        break;
14255                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14256                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14257                        break;
14258                    default:
14259                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14260                        break;
14261                }
14262            }
14263        };
14264
14265        // Treat a move like reinstalling an existing app, which ensures that we
14266        // process everythign uniformly, like unpacking native libraries.
14267        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14268
14269        final Message msg = mHandler.obtainMessage(INIT_COPY);
14270        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14271        msg.obj = new InstallParams(origin, installObserver, installFlags,
14272                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14273        mHandler.sendMessage(msg);
14274    }
14275
14276    @Override
14277    public boolean setInstallLocation(int loc) {
14278        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14279                null);
14280        if (getInstallLocation() == loc) {
14281            return true;
14282        }
14283        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14284                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14285            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14286                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14287            return true;
14288        }
14289        return false;
14290   }
14291
14292    @Override
14293    public int getInstallLocation() {
14294        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14295                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14296                PackageHelper.APP_INSTALL_AUTO);
14297    }
14298
14299    /** Called by UserManagerService */
14300    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14301        mDirtyUsers.remove(userHandle);
14302        mSettings.removeUserLPw(userHandle);
14303        mPendingBroadcasts.remove(userHandle);
14304        if (mInstaller != null) {
14305            // Technically, we shouldn't be doing this with the package lock
14306            // held.  However, this is very rare, and there is already so much
14307            // other disk I/O going on, that we'll let it slide for now.
14308            mInstaller.removeUserDataDirs(userHandle);
14309        }
14310        mUserNeedsBadging.delete(userHandle);
14311        removeUnusedPackagesLILPw(userManager, userHandle);
14312    }
14313
14314    /**
14315     * We're removing userHandle and would like to remove any downloaded packages
14316     * that are no longer in use by any other user.
14317     * @param userHandle the user being removed
14318     */
14319    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
14320        final boolean DEBUG_CLEAN_APKS = false;
14321        int [] users = userManager.getUserIdsLPr();
14322        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
14323        while (psit.hasNext()) {
14324            PackageSetting ps = psit.next();
14325            if (ps.pkg == null) {
14326                continue;
14327            }
14328            final String packageName = ps.pkg.packageName;
14329            // Skip over if system app
14330            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14331                continue;
14332            }
14333            if (DEBUG_CLEAN_APKS) {
14334                Slog.i(TAG, "Checking package " + packageName);
14335            }
14336            boolean keep = false;
14337            for (int i = 0; i < users.length; i++) {
14338                if (users[i] != userHandle && ps.getInstalled(users[i])) {
14339                    keep = true;
14340                    if (DEBUG_CLEAN_APKS) {
14341                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
14342                                + users[i]);
14343                    }
14344                    break;
14345                }
14346            }
14347            if (!keep) {
14348                if (DEBUG_CLEAN_APKS) {
14349                    Slog.i(TAG, "  Removing package " + packageName);
14350                }
14351                mHandler.post(new Runnable() {
14352                    public void run() {
14353                        deletePackageX(packageName, userHandle, 0);
14354                    } //end run
14355                });
14356            }
14357        }
14358    }
14359
14360    /** Called by UserManagerService */
14361    void createNewUserLILPw(int userHandle, File path) {
14362        if (mInstaller != null) {
14363            mInstaller.createUserConfig(userHandle);
14364            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
14365        }
14366    }
14367
14368    void newUserCreatedLILPw(int userHandle) {
14369        // Adding a user requires updating runtime permissions for system apps.
14370        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
14371    }
14372
14373    @Override
14374    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
14375        mContext.enforceCallingOrSelfPermission(
14376                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14377                "Only package verification agents can read the verifier device identity");
14378
14379        synchronized (mPackages) {
14380            return mSettings.getVerifierDeviceIdentityLPw();
14381        }
14382    }
14383
14384    @Override
14385    public void setPermissionEnforced(String permission, boolean enforced) {
14386        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
14387        if (READ_EXTERNAL_STORAGE.equals(permission)) {
14388            synchronized (mPackages) {
14389                if (mSettings.mReadExternalStorageEnforced == null
14390                        || mSettings.mReadExternalStorageEnforced != enforced) {
14391                    mSettings.mReadExternalStorageEnforced = enforced;
14392                    mSettings.writeLPr();
14393                }
14394            }
14395            // kill any non-foreground processes so we restart them and
14396            // grant/revoke the GID.
14397            final IActivityManager am = ActivityManagerNative.getDefault();
14398            if (am != null) {
14399                final long token = Binder.clearCallingIdentity();
14400                try {
14401                    am.killProcessesBelowForeground("setPermissionEnforcement");
14402                } catch (RemoteException e) {
14403                } finally {
14404                    Binder.restoreCallingIdentity(token);
14405                }
14406            }
14407        } else {
14408            throw new IllegalArgumentException("No selective enforcement for " + permission);
14409        }
14410    }
14411
14412    @Override
14413    @Deprecated
14414    public boolean isPermissionEnforced(String permission) {
14415        return true;
14416    }
14417
14418    @Override
14419    public boolean isStorageLow() {
14420        final long token = Binder.clearCallingIdentity();
14421        try {
14422            final DeviceStorageMonitorInternal
14423                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14424            if (dsm != null) {
14425                return dsm.isMemoryLow();
14426            } else {
14427                return false;
14428            }
14429        } finally {
14430            Binder.restoreCallingIdentity(token);
14431        }
14432    }
14433
14434    @Override
14435    public IPackageInstaller getPackageInstaller() {
14436        return mInstallerService;
14437    }
14438
14439    private boolean userNeedsBadging(int userId) {
14440        int index = mUserNeedsBadging.indexOfKey(userId);
14441        if (index < 0) {
14442            final UserInfo userInfo;
14443            final long token = Binder.clearCallingIdentity();
14444            try {
14445                userInfo = sUserManager.getUserInfo(userId);
14446            } finally {
14447                Binder.restoreCallingIdentity(token);
14448            }
14449            final boolean b;
14450            if (userInfo != null && userInfo.isManagedProfile()) {
14451                b = true;
14452            } else {
14453                b = false;
14454            }
14455            mUserNeedsBadging.put(userId, b);
14456            return b;
14457        }
14458        return mUserNeedsBadging.valueAt(index);
14459    }
14460
14461    @Override
14462    public KeySet getKeySetByAlias(String packageName, String alias) {
14463        if (packageName == null || alias == null) {
14464            return null;
14465        }
14466        synchronized(mPackages) {
14467            final PackageParser.Package pkg = mPackages.get(packageName);
14468            if (pkg == null) {
14469                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14470                throw new IllegalArgumentException("Unknown package: " + packageName);
14471            }
14472            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14473            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
14474        }
14475    }
14476
14477    @Override
14478    public KeySet getSigningKeySet(String packageName) {
14479        if (packageName == null) {
14480            return null;
14481        }
14482        synchronized(mPackages) {
14483            final PackageParser.Package pkg = mPackages.get(packageName);
14484            if (pkg == null) {
14485                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14486                throw new IllegalArgumentException("Unknown package: " + packageName);
14487            }
14488            if (pkg.applicationInfo.uid != Binder.getCallingUid()
14489                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
14490                throw new SecurityException("May not access signing KeySet of other apps.");
14491            }
14492            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14493            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
14494        }
14495    }
14496
14497    @Override
14498    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
14499        if (packageName == null || ks == null) {
14500            return false;
14501        }
14502        synchronized(mPackages) {
14503            final PackageParser.Package pkg = mPackages.get(packageName);
14504            if (pkg == null) {
14505                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14506                throw new IllegalArgumentException("Unknown package: " + packageName);
14507            }
14508            IBinder ksh = ks.getToken();
14509            if (ksh instanceof KeySetHandle) {
14510                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14511                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
14512            }
14513            return false;
14514        }
14515    }
14516
14517    @Override
14518    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
14519        if (packageName == null || ks == null) {
14520            return false;
14521        }
14522        synchronized(mPackages) {
14523            final PackageParser.Package pkg = mPackages.get(packageName);
14524            if (pkg == null) {
14525                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14526                throw new IllegalArgumentException("Unknown package: " + packageName);
14527            }
14528            IBinder ksh = ks.getToken();
14529            if (ksh instanceof KeySetHandle) {
14530                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14531                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
14532            }
14533            return false;
14534        }
14535    }
14536
14537    public void getUsageStatsIfNoPackageUsageInfo() {
14538        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
14539            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
14540            if (usm == null) {
14541                throw new IllegalStateException("UsageStatsManager must be initialized");
14542            }
14543            long now = System.currentTimeMillis();
14544            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
14545            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
14546                String packageName = entry.getKey();
14547                PackageParser.Package pkg = mPackages.get(packageName);
14548                if (pkg == null) {
14549                    continue;
14550                }
14551                UsageStats usage = entry.getValue();
14552                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
14553                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
14554            }
14555        }
14556    }
14557
14558    /**
14559     * Check and throw if the given before/after packages would be considered a
14560     * downgrade.
14561     */
14562    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
14563            throws PackageManagerException {
14564        if (after.versionCode < before.mVersionCode) {
14565            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14566                    "Update version code " + after.versionCode + " is older than current "
14567                    + before.mVersionCode);
14568        } else if (after.versionCode == before.mVersionCode) {
14569            if (after.baseRevisionCode < before.baseRevisionCode) {
14570                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14571                        "Update base revision code " + after.baseRevisionCode
14572                        + " is older than current " + before.baseRevisionCode);
14573            }
14574
14575            if (!ArrayUtils.isEmpty(after.splitNames)) {
14576                for (int i = 0; i < after.splitNames.length; i++) {
14577                    final String splitName = after.splitNames[i];
14578                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
14579                    if (j != -1) {
14580                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
14581                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14582                                    "Update split " + splitName + " revision code "
14583                                    + after.splitRevisionCodes[i] + " is older than current "
14584                                    + before.splitRevisionCodes[j]);
14585                        }
14586                    }
14587                }
14588            }
14589        }
14590    }
14591}
14592