PackageManagerService.java revision afd1fc3ccc7c5627c0a10d4b61fb4e87b0e18cd9
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_UNMOUNTING) {
1538                    unloadPrivatePackages(vol);
1539                }
1540            }
1541
1542            if (vol.isPrimary() && vol.type == VolumeInfo.TYPE_PUBLIC) {
1543                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1544                    updateExternalMediaStatus(true, false);
1545                } else if (vol.state == VolumeInfo.STATE_UNMOUNTING) {
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.packageName, nativeLibPath, userId) < 0) {
6284                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6285                                    "Failed linking native library dir (user=" + userId + ")");
6286                        }
6287                    }
6288                }
6289            }
6290        }
6291
6292        // This is a special case for the "system" package, where the ABI is
6293        // dictated by the zygote configuration (and init.rc). We should keep track
6294        // of this ABI so that we can deal with "normal" applications that run under
6295        // the same UID correctly.
6296        if (mPlatformPackage == pkg) {
6297            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6298                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6299        }
6300
6301        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6302        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6303        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6304        // Copy the derived override back to the parsed package, so that we can
6305        // update the package settings accordingly.
6306        pkg.cpuAbiOverride = cpuAbiOverride;
6307
6308        if (DEBUG_ABI_SELECTION) {
6309            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6310                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6311                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6312        }
6313
6314        // Push the derived path down into PackageSettings so we know what to
6315        // clean up at uninstall time.
6316        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6317
6318        if (DEBUG_ABI_SELECTION) {
6319            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6320                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6321                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6322        }
6323
6324        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6325            // We don't do this here during boot because we can do it all
6326            // at once after scanning all existing packages.
6327            //
6328            // We also do this *before* we perform dexopt on this package, so that
6329            // we can avoid redundant dexopts, and also to make sure we've got the
6330            // code and package path correct.
6331            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6332                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6333        }
6334
6335        if ((scanFlags & SCAN_NO_DEX) == 0) {
6336            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6337                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6338            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6339                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6340            }
6341        }
6342        if (mFactoryTest && pkg.requestedPermissions.contains(
6343                android.Manifest.permission.FACTORY_TEST)) {
6344            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6345        }
6346
6347        ArrayList<PackageParser.Package> clientLibPkgs = null;
6348
6349        // writer
6350        synchronized (mPackages) {
6351            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6352                // Only system apps can add new shared libraries.
6353                if (pkg.libraryNames != null) {
6354                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6355                        String name = pkg.libraryNames.get(i);
6356                        boolean allowed = false;
6357                        if (pkg.isUpdatedSystemApp()) {
6358                            // New library entries can only be added through the
6359                            // system image.  This is important to get rid of a lot
6360                            // of nasty edge cases: for example if we allowed a non-
6361                            // system update of the app to add a library, then uninstalling
6362                            // the update would make the library go away, and assumptions
6363                            // we made such as through app install filtering would now
6364                            // have allowed apps on the device which aren't compatible
6365                            // with it.  Better to just have the restriction here, be
6366                            // conservative, and create many fewer cases that can negatively
6367                            // impact the user experience.
6368                            final PackageSetting sysPs = mSettings
6369                                    .getDisabledSystemPkgLPr(pkg.packageName);
6370                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6371                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6372                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6373                                        allowed = true;
6374                                        allowed = true;
6375                                        break;
6376                                    }
6377                                }
6378                            }
6379                        } else {
6380                            allowed = true;
6381                        }
6382                        if (allowed) {
6383                            if (!mSharedLibraries.containsKey(name)) {
6384                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6385                            } else if (!name.equals(pkg.packageName)) {
6386                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6387                                        + name + " already exists; skipping");
6388                            }
6389                        } else {
6390                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6391                                    + name + " that is not declared on system image; skipping");
6392                        }
6393                    }
6394                    if ((scanFlags&SCAN_BOOTING) == 0) {
6395                        // If we are not booting, we need to update any applications
6396                        // that are clients of our shared library.  If we are booting,
6397                        // this will all be done once the scan is complete.
6398                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6399                    }
6400                }
6401            }
6402        }
6403
6404        // We also need to dexopt any apps that are dependent on this library.  Note that
6405        // if these fail, we should abort the install since installing the library will
6406        // result in some apps being broken.
6407        if (clientLibPkgs != null) {
6408            if ((scanFlags & SCAN_NO_DEX) == 0) {
6409                for (int i = 0; i < clientLibPkgs.size(); i++) {
6410                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6411                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6412                            null /* instruction sets */, forceDex,
6413                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6414                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6415                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6416                                "scanPackageLI failed to dexopt clientLibPkgs");
6417                    }
6418                }
6419            }
6420        }
6421
6422        // Request the ActivityManager to kill the process(only for existing packages)
6423        // so that we do not end up in a confused state while the user is still using the older
6424        // version of the application while the new one gets installed.
6425        if ((scanFlags & SCAN_REPLACING) != 0) {
6426            killApplication(pkg.applicationInfo.packageName,
6427                        pkg.applicationInfo.uid, "update pkg");
6428        }
6429
6430        // Also need to kill any apps that are dependent on the library.
6431        if (clientLibPkgs != null) {
6432            for (int i=0; i<clientLibPkgs.size(); i++) {
6433                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6434                killApplication(clientPkg.applicationInfo.packageName,
6435                        clientPkg.applicationInfo.uid, "update lib");
6436            }
6437        }
6438
6439        // writer
6440        synchronized (mPackages) {
6441            // We don't expect installation to fail beyond this point
6442
6443            // Add the new setting to mSettings
6444            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6445            // Add the new setting to mPackages
6446            mPackages.put(pkg.applicationInfo.packageName, pkg);
6447            // Make sure we don't accidentally delete its data.
6448            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6449            while (iter.hasNext()) {
6450                PackageCleanItem item = iter.next();
6451                if (pkgName.equals(item.packageName)) {
6452                    iter.remove();
6453                }
6454            }
6455
6456            // Take care of first install / last update times.
6457            if (currentTime != 0) {
6458                if (pkgSetting.firstInstallTime == 0) {
6459                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6460                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6461                    pkgSetting.lastUpdateTime = currentTime;
6462                }
6463            } else if (pkgSetting.firstInstallTime == 0) {
6464                // We need *something*.  Take time time stamp of the file.
6465                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6466            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6467                if (scanFileTime != pkgSetting.timeStamp) {
6468                    // A package on the system image has changed; consider this
6469                    // to be an update.
6470                    pkgSetting.lastUpdateTime = scanFileTime;
6471                }
6472            }
6473
6474            // Add the package's KeySets to the global KeySetManagerService
6475            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6476            try {
6477                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6478                if (pkg.mKeySetMapping != null) {
6479                    ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping);
6480                    if (pkg.mUpgradeKeySets != null) {
6481                        ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets);
6482                    }
6483                }
6484            } catch (NullPointerException e) {
6485                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6486            } catch (IllegalArgumentException e) {
6487                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6488            }
6489
6490            int N = pkg.providers.size();
6491            StringBuilder r = null;
6492            int i;
6493            for (i=0; i<N; i++) {
6494                PackageParser.Provider p = pkg.providers.get(i);
6495                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6496                        p.info.processName, pkg.applicationInfo.uid);
6497                mProviders.addProvider(p);
6498                p.syncable = p.info.isSyncable;
6499                if (p.info.authority != null) {
6500                    String names[] = p.info.authority.split(";");
6501                    p.info.authority = null;
6502                    for (int j = 0; j < names.length; j++) {
6503                        if (j == 1 && p.syncable) {
6504                            // We only want the first authority for a provider to possibly be
6505                            // syncable, so if we already added this provider using a different
6506                            // authority clear the syncable flag. We copy the provider before
6507                            // changing it because the mProviders object contains a reference
6508                            // to a provider that we don't want to change.
6509                            // Only do this for the second authority since the resulting provider
6510                            // object can be the same for all future authorities for this provider.
6511                            p = new PackageParser.Provider(p);
6512                            p.syncable = false;
6513                        }
6514                        if (!mProvidersByAuthority.containsKey(names[j])) {
6515                            mProvidersByAuthority.put(names[j], p);
6516                            if (p.info.authority == null) {
6517                                p.info.authority = names[j];
6518                            } else {
6519                                p.info.authority = p.info.authority + ";" + names[j];
6520                            }
6521                            if (DEBUG_PACKAGE_SCANNING) {
6522                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6523                                    Log.d(TAG, "Registered content provider: " + names[j]
6524                                            + ", className = " + p.info.name + ", isSyncable = "
6525                                            + p.info.isSyncable);
6526                            }
6527                        } else {
6528                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6529                            Slog.w(TAG, "Skipping provider name " + names[j] +
6530                                    " (in package " + pkg.applicationInfo.packageName +
6531                                    "): name already used by "
6532                                    + ((other != null && other.getComponentName() != null)
6533                                            ? other.getComponentName().getPackageName() : "?"));
6534                        }
6535                    }
6536                }
6537                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6538                    if (r == null) {
6539                        r = new StringBuilder(256);
6540                    } else {
6541                        r.append(' ');
6542                    }
6543                    r.append(p.info.name);
6544                }
6545            }
6546            if (r != null) {
6547                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6548            }
6549
6550            N = pkg.services.size();
6551            r = null;
6552            for (i=0; i<N; i++) {
6553                PackageParser.Service s = pkg.services.get(i);
6554                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6555                        s.info.processName, pkg.applicationInfo.uid);
6556                mServices.addService(s);
6557                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6558                    if (r == null) {
6559                        r = new StringBuilder(256);
6560                    } else {
6561                        r.append(' ');
6562                    }
6563                    r.append(s.info.name);
6564                }
6565            }
6566            if (r != null) {
6567                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6568            }
6569
6570            N = pkg.receivers.size();
6571            r = null;
6572            for (i=0; i<N; i++) {
6573                PackageParser.Activity a = pkg.receivers.get(i);
6574                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6575                        a.info.processName, pkg.applicationInfo.uid);
6576                mReceivers.addActivity(a, "receiver");
6577                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6578                    if (r == null) {
6579                        r = new StringBuilder(256);
6580                    } else {
6581                        r.append(' ');
6582                    }
6583                    r.append(a.info.name);
6584                }
6585            }
6586            if (r != null) {
6587                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6588            }
6589
6590            N = pkg.activities.size();
6591            r = null;
6592            for (i=0; i<N; i++) {
6593                PackageParser.Activity a = pkg.activities.get(i);
6594                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6595                        a.info.processName, pkg.applicationInfo.uid);
6596                mActivities.addActivity(a, "activity");
6597                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6598                    if (r == null) {
6599                        r = new StringBuilder(256);
6600                    } else {
6601                        r.append(' ');
6602                    }
6603                    r.append(a.info.name);
6604                }
6605            }
6606            if (r != null) {
6607                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6608            }
6609
6610            N = pkg.permissionGroups.size();
6611            r = null;
6612            for (i=0; i<N; i++) {
6613                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6614                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6615                if (cur == null) {
6616                    mPermissionGroups.put(pg.info.name, pg);
6617                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6618                        if (r == null) {
6619                            r = new StringBuilder(256);
6620                        } else {
6621                            r.append(' ');
6622                        }
6623                        r.append(pg.info.name);
6624                    }
6625                } else {
6626                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6627                            + pg.info.packageName + " ignored: original from "
6628                            + cur.info.packageName);
6629                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6630                        if (r == null) {
6631                            r = new StringBuilder(256);
6632                        } else {
6633                            r.append(' ');
6634                        }
6635                        r.append("DUP:");
6636                        r.append(pg.info.name);
6637                    }
6638                }
6639            }
6640            if (r != null) {
6641                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6642            }
6643
6644            N = pkg.permissions.size();
6645            r = null;
6646            for (i=0; i<N; i++) {
6647                PackageParser.Permission p = pkg.permissions.get(i);
6648
6649                // Now that permission groups have a special meaning, we ignore permission
6650                // groups for legacy apps to prevent unexpected behavior. In particular,
6651                // permissions for one app being granted to someone just becuase they happen
6652                // to be in a group defined by another app (before this had no implications).
6653                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6654                    p.group = mPermissionGroups.get(p.info.group);
6655                    // Warn for a permission in an unknown group.
6656                    if (p.info.group != null && p.group == null) {
6657                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6658                                + p.info.packageName + " in an unknown group " + p.info.group);
6659                    }
6660                }
6661
6662                ArrayMap<String, BasePermission> permissionMap =
6663                        p.tree ? mSettings.mPermissionTrees
6664                                : mSettings.mPermissions;
6665                BasePermission bp = permissionMap.get(p.info.name);
6666
6667                // Allow system apps to redefine non-system permissions
6668                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6669                    final boolean currentOwnerIsSystem = (bp.perm != null
6670                            && isSystemApp(bp.perm.owner));
6671                    if (isSystemApp(p.owner)) {
6672                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6673                            // It's a built-in permission and no owner, take ownership now
6674                            bp.packageSetting = pkgSetting;
6675                            bp.perm = p;
6676                            bp.uid = pkg.applicationInfo.uid;
6677                            bp.sourcePackage = p.info.packageName;
6678                        } else if (!currentOwnerIsSystem) {
6679                            String msg = "New decl " + p.owner + " of permission  "
6680                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6681                            reportSettingsProblem(Log.WARN, msg);
6682                            bp = null;
6683                        }
6684                    }
6685                }
6686
6687                if (bp == null) {
6688                    bp = new BasePermission(p.info.name, p.info.packageName,
6689                            BasePermission.TYPE_NORMAL);
6690                    permissionMap.put(p.info.name, bp);
6691                }
6692
6693                if (bp.perm == null) {
6694                    if (bp.sourcePackage == null
6695                            || bp.sourcePackage.equals(p.info.packageName)) {
6696                        BasePermission tree = findPermissionTreeLP(p.info.name);
6697                        if (tree == null
6698                                || tree.sourcePackage.equals(p.info.packageName)) {
6699                            bp.packageSetting = pkgSetting;
6700                            bp.perm = p;
6701                            bp.uid = pkg.applicationInfo.uid;
6702                            bp.sourcePackage = p.info.packageName;
6703                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6704                                if (r == null) {
6705                                    r = new StringBuilder(256);
6706                                } else {
6707                                    r.append(' ');
6708                                }
6709                                r.append(p.info.name);
6710                            }
6711                        } else {
6712                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6713                                    + p.info.packageName + " ignored: base tree "
6714                                    + tree.name + " is from package "
6715                                    + tree.sourcePackage);
6716                        }
6717                    } else {
6718                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6719                                + p.info.packageName + " ignored: original from "
6720                                + bp.sourcePackage);
6721                    }
6722                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6723                    if (r == null) {
6724                        r = new StringBuilder(256);
6725                    } else {
6726                        r.append(' ');
6727                    }
6728                    r.append("DUP:");
6729                    r.append(p.info.name);
6730                }
6731                if (bp.perm == p) {
6732                    bp.protectionLevel = p.info.protectionLevel;
6733                }
6734            }
6735
6736            if (r != null) {
6737                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6738            }
6739
6740            N = pkg.instrumentation.size();
6741            r = null;
6742            for (i=0; i<N; i++) {
6743                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6744                a.info.packageName = pkg.applicationInfo.packageName;
6745                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6746                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6747                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6748                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6749                a.info.dataDir = pkg.applicationInfo.dataDir;
6750
6751                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6752                // need other information about the application, like the ABI and what not ?
6753                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6754                mInstrumentation.put(a.getComponentName(), a);
6755                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6756                    if (r == null) {
6757                        r = new StringBuilder(256);
6758                    } else {
6759                        r.append(' ');
6760                    }
6761                    r.append(a.info.name);
6762                }
6763            }
6764            if (r != null) {
6765                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6766            }
6767
6768            if (pkg.protectedBroadcasts != null) {
6769                N = pkg.protectedBroadcasts.size();
6770                for (i=0; i<N; i++) {
6771                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6772                }
6773            }
6774
6775            pkgSetting.setTimeStamp(scanFileTime);
6776
6777            // Create idmap files for pairs of (packages, overlay packages).
6778            // Note: "android", ie framework-res.apk, is handled by native layers.
6779            if (pkg.mOverlayTarget != null) {
6780                // This is an overlay package.
6781                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6782                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6783                        mOverlays.put(pkg.mOverlayTarget,
6784                                new ArrayMap<String, PackageParser.Package>());
6785                    }
6786                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6787                    map.put(pkg.packageName, pkg);
6788                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6789                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6790                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6791                                "scanPackageLI failed to createIdmap");
6792                    }
6793                }
6794            } else if (mOverlays.containsKey(pkg.packageName) &&
6795                    !pkg.packageName.equals("android")) {
6796                // This is a regular package, with one or more known overlay packages.
6797                createIdmapsForPackageLI(pkg);
6798            }
6799        }
6800
6801        return pkg;
6802    }
6803
6804    /**
6805     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6806     * i.e, so that all packages can be run inside a single process if required.
6807     *
6808     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6809     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6810     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6811     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6812     * updating a package that belongs to a shared user.
6813     *
6814     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6815     * adds unnecessary complexity.
6816     */
6817    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6818            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6819        String requiredInstructionSet = null;
6820        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6821            requiredInstructionSet = VMRuntime.getInstructionSet(
6822                     scannedPackage.applicationInfo.primaryCpuAbi);
6823        }
6824
6825        PackageSetting requirer = null;
6826        for (PackageSetting ps : packagesForUser) {
6827            // If packagesForUser contains scannedPackage, we skip it. This will happen
6828            // when scannedPackage is an update of an existing package. Without this check,
6829            // we will never be able to change the ABI of any package belonging to a shared
6830            // user, even if it's compatible with other packages.
6831            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6832                if (ps.primaryCpuAbiString == null) {
6833                    continue;
6834                }
6835
6836                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6837                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6838                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6839                    // this but there's not much we can do.
6840                    String errorMessage = "Instruction set mismatch, "
6841                            + ((requirer == null) ? "[caller]" : requirer)
6842                            + " requires " + requiredInstructionSet + " whereas " + ps
6843                            + " requires " + instructionSet;
6844                    Slog.w(TAG, errorMessage);
6845                }
6846
6847                if (requiredInstructionSet == null) {
6848                    requiredInstructionSet = instructionSet;
6849                    requirer = ps;
6850                }
6851            }
6852        }
6853
6854        if (requiredInstructionSet != null) {
6855            String adjustedAbi;
6856            if (requirer != null) {
6857                // requirer != null implies that either scannedPackage was null or that scannedPackage
6858                // did not require an ABI, in which case we have to adjust scannedPackage to match
6859                // the ABI of the set (which is the same as requirer's ABI)
6860                adjustedAbi = requirer.primaryCpuAbiString;
6861                if (scannedPackage != null) {
6862                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6863                }
6864            } else {
6865                // requirer == null implies that we're updating all ABIs in the set to
6866                // match scannedPackage.
6867                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6868            }
6869
6870            for (PackageSetting ps : packagesForUser) {
6871                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6872                    if (ps.primaryCpuAbiString != null) {
6873                        continue;
6874                    }
6875
6876                    ps.primaryCpuAbiString = adjustedAbi;
6877                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6878                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6879                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6880
6881                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
6882                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
6883                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6884                            ps.primaryCpuAbiString = null;
6885                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6886                            return;
6887                        } else {
6888                            mInstaller.rmdex(ps.codePathString,
6889                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
6890                        }
6891                    }
6892                }
6893            }
6894        }
6895    }
6896
6897    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6898        synchronized (mPackages) {
6899            mResolverReplaced = true;
6900            // Set up information for custom user intent resolution activity.
6901            mResolveActivity.applicationInfo = pkg.applicationInfo;
6902            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6903            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6904            mResolveActivity.processName = pkg.applicationInfo.packageName;
6905            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6906            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6907                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6908            mResolveActivity.theme = 0;
6909            mResolveActivity.exported = true;
6910            mResolveActivity.enabled = true;
6911            mResolveInfo.activityInfo = mResolveActivity;
6912            mResolveInfo.priority = 0;
6913            mResolveInfo.preferredOrder = 0;
6914            mResolveInfo.match = 0;
6915            mResolveComponentName = mCustomResolverComponentName;
6916            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6917                    mResolveComponentName);
6918        }
6919    }
6920
6921    private static String calculateBundledApkRoot(final String codePathString) {
6922        final File codePath = new File(codePathString);
6923        final File codeRoot;
6924        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6925            codeRoot = Environment.getRootDirectory();
6926        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6927            codeRoot = Environment.getOemDirectory();
6928        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6929            codeRoot = Environment.getVendorDirectory();
6930        } else {
6931            // Unrecognized code path; take its top real segment as the apk root:
6932            // e.g. /something/app/blah.apk => /something
6933            try {
6934                File f = codePath.getCanonicalFile();
6935                File parent = f.getParentFile();    // non-null because codePath is a file
6936                File tmp;
6937                while ((tmp = parent.getParentFile()) != null) {
6938                    f = parent;
6939                    parent = tmp;
6940                }
6941                codeRoot = f;
6942                Slog.w(TAG, "Unrecognized code path "
6943                        + codePath + " - using " + codeRoot);
6944            } catch (IOException e) {
6945                // Can't canonicalize the code path -- shenanigans?
6946                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6947                return Environment.getRootDirectory().getPath();
6948            }
6949        }
6950        return codeRoot.getPath();
6951    }
6952
6953    /**
6954     * Derive and set the location of native libraries for the given package,
6955     * which varies depending on where and how the package was installed.
6956     */
6957    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6958        final ApplicationInfo info = pkg.applicationInfo;
6959        final String codePath = pkg.codePath;
6960        final File codeFile = new File(codePath);
6961        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
6962        final boolean asecApp = info.isForwardLocked() || isExternal(info);
6963
6964        info.nativeLibraryRootDir = null;
6965        info.nativeLibraryRootRequiresIsa = false;
6966        info.nativeLibraryDir = null;
6967        info.secondaryNativeLibraryDir = null;
6968
6969        if (isApkFile(codeFile)) {
6970            // Monolithic install
6971            if (bundledApp) {
6972                // If "/system/lib64/apkname" exists, assume that is the per-package
6973                // native library directory to use; otherwise use "/system/lib/apkname".
6974                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6975                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6976                        getPrimaryInstructionSet(info));
6977
6978                // This is a bundled system app so choose the path based on the ABI.
6979                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6980                // is just the default path.
6981                final String apkName = deriveCodePathName(codePath);
6982                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6983                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6984                        apkName).getAbsolutePath();
6985
6986                if (info.secondaryCpuAbi != null) {
6987                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6988                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6989                            secondaryLibDir, apkName).getAbsolutePath();
6990                }
6991            } else if (asecApp) {
6992                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6993                        .getAbsolutePath();
6994            } else {
6995                final String apkName = deriveCodePathName(codePath);
6996                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6997                        .getAbsolutePath();
6998            }
6999
7000            info.nativeLibraryRootRequiresIsa = false;
7001            info.nativeLibraryDir = info.nativeLibraryRootDir;
7002        } else {
7003            // Cluster install
7004            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7005            info.nativeLibraryRootRequiresIsa = true;
7006
7007            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7008                    getPrimaryInstructionSet(info)).getAbsolutePath();
7009
7010            if (info.secondaryCpuAbi != null) {
7011                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7012                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7013            }
7014        }
7015    }
7016
7017    /**
7018     * Calculate the abis and roots for a bundled app. These can uniquely
7019     * be determined from the contents of the system partition, i.e whether
7020     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7021     * of this information, and instead assume that the system was built
7022     * sensibly.
7023     */
7024    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7025                                           PackageSetting pkgSetting) {
7026        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7027
7028        // If "/system/lib64/apkname" exists, assume that is the per-package
7029        // native library directory to use; otherwise use "/system/lib/apkname".
7030        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7031        setBundledAppAbi(pkg, apkRoot, apkName);
7032        // pkgSetting might be null during rescan following uninstall of updates
7033        // to a bundled app, so accommodate that possibility.  The settings in
7034        // that case will be established later from the parsed package.
7035        //
7036        // If the settings aren't null, sync them up with what we've just derived.
7037        // note that apkRoot isn't stored in the package settings.
7038        if (pkgSetting != null) {
7039            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7040            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7041        }
7042    }
7043
7044    /**
7045     * Deduces the ABI of a bundled app and sets the relevant fields on the
7046     * parsed pkg object.
7047     *
7048     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7049     *        under which system libraries are installed.
7050     * @param apkName the name of the installed package.
7051     */
7052    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7053        final File codeFile = new File(pkg.codePath);
7054
7055        final boolean has64BitLibs;
7056        final boolean has32BitLibs;
7057        if (isApkFile(codeFile)) {
7058            // Monolithic install
7059            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7060            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7061        } else {
7062            // Cluster install
7063            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7064            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7065                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7066                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7067                has64BitLibs = (new File(rootDir, isa)).exists();
7068            } else {
7069                has64BitLibs = false;
7070            }
7071            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7072                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7073                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7074                has32BitLibs = (new File(rootDir, isa)).exists();
7075            } else {
7076                has32BitLibs = false;
7077            }
7078        }
7079
7080        if (has64BitLibs && !has32BitLibs) {
7081            // The package has 64 bit libs, but not 32 bit libs. Its primary
7082            // ABI should be 64 bit. We can safely assume here that the bundled
7083            // native libraries correspond to the most preferred ABI in the list.
7084
7085            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7086            pkg.applicationInfo.secondaryCpuAbi = null;
7087        } else if (has32BitLibs && !has64BitLibs) {
7088            // The package has 32 bit libs but not 64 bit libs. Its primary
7089            // ABI should be 32 bit.
7090
7091            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7092            pkg.applicationInfo.secondaryCpuAbi = null;
7093        } else if (has32BitLibs && has64BitLibs) {
7094            // The application has both 64 and 32 bit bundled libraries. We check
7095            // here that the app declares multiArch support, and warn if it doesn't.
7096            //
7097            // We will be lenient here and record both ABIs. The primary will be the
7098            // ABI that's higher on the list, i.e, a device that's configured to prefer
7099            // 64 bit apps will see a 64 bit primary ABI,
7100
7101            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7102                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7103            }
7104
7105            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7106                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7107                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7108            } else {
7109                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7110                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7111            }
7112        } else {
7113            pkg.applicationInfo.primaryCpuAbi = null;
7114            pkg.applicationInfo.secondaryCpuAbi = null;
7115        }
7116    }
7117
7118    private void killApplication(String pkgName, int appId, String reason) {
7119        // Request the ActivityManager to kill the process(only for existing packages)
7120        // so that we do not end up in a confused state while the user is still using the older
7121        // version of the application while the new one gets installed.
7122        IActivityManager am = ActivityManagerNative.getDefault();
7123        if (am != null) {
7124            try {
7125                am.killApplicationWithAppId(pkgName, appId, reason);
7126            } catch (RemoteException e) {
7127            }
7128        }
7129    }
7130
7131    void removePackageLI(PackageSetting ps, boolean chatty) {
7132        if (DEBUG_INSTALL) {
7133            if (chatty)
7134                Log.d(TAG, "Removing package " + ps.name);
7135        }
7136
7137        // writer
7138        synchronized (mPackages) {
7139            mPackages.remove(ps.name);
7140            final PackageParser.Package pkg = ps.pkg;
7141            if (pkg != null) {
7142                cleanPackageDataStructuresLILPw(pkg, chatty);
7143            }
7144        }
7145    }
7146
7147    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7148        if (DEBUG_INSTALL) {
7149            if (chatty)
7150                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7151        }
7152
7153        // writer
7154        synchronized (mPackages) {
7155            mPackages.remove(pkg.applicationInfo.packageName);
7156            cleanPackageDataStructuresLILPw(pkg, chatty);
7157        }
7158    }
7159
7160    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7161        int N = pkg.providers.size();
7162        StringBuilder r = null;
7163        int i;
7164        for (i=0; i<N; i++) {
7165            PackageParser.Provider p = pkg.providers.get(i);
7166            mProviders.removeProvider(p);
7167            if (p.info.authority == null) {
7168
7169                /* There was another ContentProvider with this authority when
7170                 * this app was installed so this authority is null,
7171                 * Ignore it as we don't have to unregister the provider.
7172                 */
7173                continue;
7174            }
7175            String names[] = p.info.authority.split(";");
7176            for (int j = 0; j < names.length; j++) {
7177                if (mProvidersByAuthority.get(names[j]) == p) {
7178                    mProvidersByAuthority.remove(names[j]);
7179                    if (DEBUG_REMOVE) {
7180                        if (chatty)
7181                            Log.d(TAG, "Unregistered content provider: " + names[j]
7182                                    + ", className = " + p.info.name + ", isSyncable = "
7183                                    + p.info.isSyncable);
7184                    }
7185                }
7186            }
7187            if (DEBUG_REMOVE && chatty) {
7188                if (r == null) {
7189                    r = new StringBuilder(256);
7190                } else {
7191                    r.append(' ');
7192                }
7193                r.append(p.info.name);
7194            }
7195        }
7196        if (r != null) {
7197            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7198        }
7199
7200        N = pkg.services.size();
7201        r = null;
7202        for (i=0; i<N; i++) {
7203            PackageParser.Service s = pkg.services.get(i);
7204            mServices.removeService(s);
7205            if (chatty) {
7206                if (r == null) {
7207                    r = new StringBuilder(256);
7208                } else {
7209                    r.append(' ');
7210                }
7211                r.append(s.info.name);
7212            }
7213        }
7214        if (r != null) {
7215            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7216        }
7217
7218        N = pkg.receivers.size();
7219        r = null;
7220        for (i=0; i<N; i++) {
7221            PackageParser.Activity a = pkg.receivers.get(i);
7222            mReceivers.removeActivity(a, "receiver");
7223            if (DEBUG_REMOVE && chatty) {
7224                if (r == null) {
7225                    r = new StringBuilder(256);
7226                } else {
7227                    r.append(' ');
7228                }
7229                r.append(a.info.name);
7230            }
7231        }
7232        if (r != null) {
7233            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7234        }
7235
7236        N = pkg.activities.size();
7237        r = null;
7238        for (i=0; i<N; i++) {
7239            PackageParser.Activity a = pkg.activities.get(i);
7240            mActivities.removeActivity(a, "activity");
7241            if (DEBUG_REMOVE && chatty) {
7242                if (r == null) {
7243                    r = new StringBuilder(256);
7244                } else {
7245                    r.append(' ');
7246                }
7247                r.append(a.info.name);
7248            }
7249        }
7250        if (r != null) {
7251            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7252        }
7253
7254        N = pkg.permissions.size();
7255        r = null;
7256        for (i=0; i<N; i++) {
7257            PackageParser.Permission p = pkg.permissions.get(i);
7258            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7259            if (bp == null) {
7260                bp = mSettings.mPermissionTrees.get(p.info.name);
7261            }
7262            if (bp != null && bp.perm == p) {
7263                bp.perm = null;
7264                if (DEBUG_REMOVE && chatty) {
7265                    if (r == null) {
7266                        r = new StringBuilder(256);
7267                    } else {
7268                        r.append(' ');
7269                    }
7270                    r.append(p.info.name);
7271                }
7272            }
7273            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7274                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7275                if (appOpPerms != null) {
7276                    appOpPerms.remove(pkg.packageName);
7277                }
7278            }
7279        }
7280        if (r != null) {
7281            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7282        }
7283
7284        N = pkg.requestedPermissions.size();
7285        r = null;
7286        for (i=0; i<N; i++) {
7287            String perm = pkg.requestedPermissions.get(i);
7288            BasePermission bp = mSettings.mPermissions.get(perm);
7289            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7290                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7291                if (appOpPerms != null) {
7292                    appOpPerms.remove(pkg.packageName);
7293                    if (appOpPerms.isEmpty()) {
7294                        mAppOpPermissionPackages.remove(perm);
7295                    }
7296                }
7297            }
7298        }
7299        if (r != null) {
7300            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7301        }
7302
7303        N = pkg.instrumentation.size();
7304        r = null;
7305        for (i=0; i<N; i++) {
7306            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7307            mInstrumentation.remove(a.getComponentName());
7308            if (DEBUG_REMOVE && chatty) {
7309                if (r == null) {
7310                    r = new StringBuilder(256);
7311                } else {
7312                    r.append(' ');
7313                }
7314                r.append(a.info.name);
7315            }
7316        }
7317        if (r != null) {
7318            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7319        }
7320
7321        r = null;
7322        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7323            // Only system apps can hold shared libraries.
7324            if (pkg.libraryNames != null) {
7325                for (i=0; i<pkg.libraryNames.size(); i++) {
7326                    String name = pkg.libraryNames.get(i);
7327                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7328                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7329                        mSharedLibraries.remove(name);
7330                        if (DEBUG_REMOVE && chatty) {
7331                            if (r == null) {
7332                                r = new StringBuilder(256);
7333                            } else {
7334                                r.append(' ');
7335                            }
7336                            r.append(name);
7337                        }
7338                    }
7339                }
7340            }
7341        }
7342        if (r != null) {
7343            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7344        }
7345    }
7346
7347    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7348        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7349            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7350                return true;
7351            }
7352        }
7353        return false;
7354    }
7355
7356    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7357    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7358    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7359
7360    private void updatePermissionsLPw(String changingPkg,
7361            PackageParser.Package pkgInfo, int flags) {
7362        // Make sure there are no dangling permission trees.
7363        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7364        while (it.hasNext()) {
7365            final BasePermission bp = it.next();
7366            if (bp.packageSetting == null) {
7367                // We may not yet have parsed the package, so just see if
7368                // we still know about its settings.
7369                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7370            }
7371            if (bp.packageSetting == null) {
7372                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7373                        + " from package " + bp.sourcePackage);
7374                it.remove();
7375            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7376                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7377                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7378                            + " from package " + bp.sourcePackage);
7379                    flags |= UPDATE_PERMISSIONS_ALL;
7380                    it.remove();
7381                }
7382            }
7383        }
7384
7385        // Make sure all dynamic permissions have been assigned to a package,
7386        // and make sure there are no dangling permissions.
7387        it = mSettings.mPermissions.values().iterator();
7388        while (it.hasNext()) {
7389            final BasePermission bp = it.next();
7390            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7391                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7392                        + bp.name + " pkg=" + bp.sourcePackage
7393                        + " info=" + bp.pendingInfo);
7394                if (bp.packageSetting == null && bp.pendingInfo != null) {
7395                    final BasePermission tree = findPermissionTreeLP(bp.name);
7396                    if (tree != null && tree.perm != null) {
7397                        bp.packageSetting = tree.packageSetting;
7398                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7399                                new PermissionInfo(bp.pendingInfo));
7400                        bp.perm.info.packageName = tree.perm.info.packageName;
7401                        bp.perm.info.name = bp.name;
7402                        bp.uid = tree.uid;
7403                    }
7404                }
7405            }
7406            if (bp.packageSetting == null) {
7407                // We may not yet have parsed the package, so just see if
7408                // we still know about its settings.
7409                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7410            }
7411            if (bp.packageSetting == null) {
7412                Slog.w(TAG, "Removing dangling permission: " + bp.name
7413                        + " from package " + bp.sourcePackage);
7414                it.remove();
7415            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7416                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7417                    Slog.i(TAG, "Removing old permission: " + bp.name
7418                            + " from package " + bp.sourcePackage);
7419                    flags |= UPDATE_PERMISSIONS_ALL;
7420                    it.remove();
7421                }
7422            }
7423        }
7424
7425        // Now update the permissions for all packages, in particular
7426        // replace the granted permissions of the system packages.
7427        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7428            for (PackageParser.Package pkg : mPackages.values()) {
7429                if (pkg != pkgInfo) {
7430                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7431                            changingPkg);
7432                }
7433            }
7434        }
7435
7436        if (pkgInfo != null) {
7437            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7438        }
7439    }
7440
7441    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7442            String packageOfInterest) {
7443        // IMPORTANT: There are two types of permissions: install and runtime.
7444        // Install time permissions are granted when the app is installed to
7445        // all device users and users added in the future. Runtime permissions
7446        // are granted at runtime explicitly to specific users. Normal and signature
7447        // protected permissions are install time permissions. Dangerous permissions
7448        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7449        // otherwise they are runtime permissions. This function does not manage
7450        // runtime permissions except for the case an app targeting Lollipop MR1
7451        // being upgraded to target a newer SDK, in which case dangerous permissions
7452        // are transformed from install time to runtime ones.
7453
7454        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7455        if (ps == null) {
7456            return;
7457        }
7458
7459        PermissionsState permissionsState = ps.getPermissionsState();
7460        PermissionsState origPermissions = permissionsState;
7461
7462        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7463
7464        int[] upgradeUserIds = PermissionsState.USERS_NONE;
7465        int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE;
7466
7467        boolean changedInstallPermission = false;
7468
7469        if (replace) {
7470            ps.installPermissionsFixed = false;
7471            if (!ps.isSharedUser()) {
7472                origPermissions = new PermissionsState(permissionsState);
7473                permissionsState.reset();
7474            }
7475        }
7476
7477        permissionsState.setGlobalGids(mGlobalGids);
7478
7479        final int N = pkg.requestedPermissions.size();
7480        for (int i=0; i<N; i++) {
7481            final String name = pkg.requestedPermissions.get(i);
7482            final BasePermission bp = mSettings.mPermissions.get(name);
7483
7484            if (DEBUG_INSTALL) {
7485                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7486            }
7487
7488            if (bp == null || bp.packageSetting == null) {
7489                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7490                    Slog.w(TAG, "Unknown permission " + name
7491                            + " in package " + pkg.packageName);
7492                }
7493                continue;
7494            }
7495
7496            final String perm = bp.name;
7497            boolean allowedSig = false;
7498            int grant = GRANT_DENIED;
7499
7500            // Keep track of app op permissions.
7501            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7502                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7503                if (pkgs == null) {
7504                    pkgs = new ArraySet<>();
7505                    mAppOpPermissionPackages.put(bp.name, pkgs);
7506                }
7507                pkgs.add(pkg.packageName);
7508            }
7509
7510            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7511            switch (level) {
7512                case PermissionInfo.PROTECTION_NORMAL: {
7513                    // For all apps normal permissions are install time ones.
7514                    grant = GRANT_INSTALL;
7515                } break;
7516
7517                case PermissionInfo.PROTECTION_DANGEROUS: {
7518                    if (!RUNTIME_PERMISSIONS_ENABLED
7519                            || pkg.applicationInfo.targetSdkVersion
7520                                    <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7521                        // For legacy apps dangerous permissions are install time ones.
7522                        grant = GRANT_INSTALL;
7523                    } else if (ps.isSystem()) {
7524                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7525                        if (origPermissions.hasInstallPermission(bp.name)) {
7526                            // If a system app had an install permission, then the app was
7527                            // upgraded and we grant the permissions as runtime to all users.
7528                            grant = GRANT_UPGRADE;
7529                            upgradeUserIds = currentUserIds;
7530                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7531                            // If users changed since the last permissions update for a
7532                            // system app, we grant the permission as runtime to the new users.
7533                            grant = GRANT_UPGRADE;
7534                            upgradeUserIds = currentUserIds;
7535                            for (int userId : updatedUserIds) {
7536                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7537                            }
7538                        } else {
7539                            // Otherwise, we grant the permission as runtime if the app
7540                            // already had it, i.e. we preserve runtime permissions.
7541                            grant = GRANT_RUNTIME;
7542                        }
7543                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7544                        // For legacy apps that became modern, install becomes runtime.
7545                        grant = GRANT_UPGRADE;
7546                        upgradeUserIds = currentUserIds;
7547                    } else if (replace) {
7548                        // For upgraded modern apps keep runtime permissions unchanged.
7549                        grant = GRANT_RUNTIME;
7550                    }
7551                } break;
7552
7553                case PermissionInfo.PROTECTION_SIGNATURE: {
7554                    // For all apps signature permissions are install time ones.
7555                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7556                    if (allowedSig) {
7557                        grant = GRANT_INSTALL;
7558                    }
7559                } break;
7560            }
7561
7562            if (DEBUG_INSTALL) {
7563                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7564            }
7565
7566            if (grant != GRANT_DENIED) {
7567                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7568                    // If this is an existing, non-system package, then
7569                    // we can't add any new permissions to it.
7570                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7571                        // Except...  if this is a permission that was added
7572                        // to the platform (note: need to only do this when
7573                        // updating the platform).
7574                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7575                            grant = GRANT_DENIED;
7576                        }
7577                    }
7578                }
7579
7580                switch (grant) {
7581                    case GRANT_INSTALL: {
7582                        // Grant an install permission.
7583                        if (permissionsState.grantInstallPermission(bp) !=
7584                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7585                            changedInstallPermission = true;
7586                        }
7587                    } break;
7588
7589                    case GRANT_RUNTIME: {
7590                        // Grant previously granted runtime permissions.
7591                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7592                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7593                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7594                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7595                                    // If we cannot put the permission as it was, we have to write.
7596                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7597                                            changedRuntimePermissionUserIds, userId);
7598                                }
7599                            }
7600                        }
7601                    } break;
7602
7603                    case GRANT_UPGRADE: {
7604                        // Grant runtime permissions for a previously held install permission.
7605                        permissionsState.revokeInstallPermission(bp);
7606                        for (int userId : upgradeUserIds) {
7607                            if (permissionsState.grantRuntimePermission(bp, userId) !=
7608                                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
7609                                // If we granted the permission, we have to write.
7610                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7611                                        changedRuntimePermissionUserIds, userId);
7612                            }
7613                        }
7614                    } break;
7615
7616                    default: {
7617                        if (packageOfInterest == null
7618                                || packageOfInterest.equals(pkg.packageName)) {
7619                            Slog.w(TAG, "Not granting permission " + perm
7620                                    + " to package " + pkg.packageName
7621                                    + " because it was previously installed without");
7622                        }
7623                    } break;
7624                }
7625            } else {
7626                if (permissionsState.revokeInstallPermission(bp) !=
7627                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7628                    changedInstallPermission = true;
7629                    Slog.i(TAG, "Un-granting permission " + perm
7630                            + " from package " + pkg.packageName
7631                            + " (protectionLevel=" + bp.protectionLevel
7632                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7633                            + ")");
7634                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7635                    // Don't print warning for app op permissions, since it is fine for them
7636                    // not to be granted, there is a UI for the user to decide.
7637                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7638                        Slog.w(TAG, "Not granting permission " + perm
7639                                + " to package " + pkg.packageName
7640                                + " (protectionLevel=" + bp.protectionLevel
7641                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7642                                + ")");
7643                    }
7644                }
7645            }
7646        }
7647
7648        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7649                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7650            // This is the first that we have heard about this package, so the
7651            // permissions we have now selected are fixed until explicitly
7652            // changed.
7653            ps.installPermissionsFixed = true;
7654        }
7655
7656        ps.setPermissionsUpdatedForUserIds(currentUserIds);
7657
7658        // Persist the runtime permissions state for users with changes.
7659        if (RUNTIME_PERMISSIONS_ENABLED) {
7660            for (int userId : changedRuntimePermissionUserIds) {
7661                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
7662            }
7663        }
7664    }
7665
7666    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7667        boolean allowed = false;
7668        final int NP = PackageParser.NEW_PERMISSIONS.length;
7669        for (int ip=0; ip<NP; ip++) {
7670            final PackageParser.NewPermissionInfo npi
7671                    = PackageParser.NEW_PERMISSIONS[ip];
7672            if (npi.name.equals(perm)
7673                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7674                allowed = true;
7675                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7676                        + pkg.packageName);
7677                break;
7678            }
7679        }
7680        return allowed;
7681    }
7682
7683    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7684            BasePermission bp, PermissionsState origPermissions) {
7685        boolean allowed;
7686        allowed = (compareSignatures(
7687                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7688                        == PackageManager.SIGNATURE_MATCH)
7689                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7690                        == PackageManager.SIGNATURE_MATCH);
7691        if (!allowed && (bp.protectionLevel
7692                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7693            if (isSystemApp(pkg)) {
7694                // For updated system applications, a system permission
7695                // is granted only if it had been defined by the original application.
7696                if (pkg.isUpdatedSystemApp()) {
7697                    final PackageSetting sysPs = mSettings
7698                            .getDisabledSystemPkgLPr(pkg.packageName);
7699                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
7700                        // If the original was granted this permission, we take
7701                        // that grant decision as read and propagate it to the
7702                        // update.
7703                        if (sysPs.isPrivileged()) {
7704                            allowed = true;
7705                        }
7706                    } else {
7707                        // The system apk may have been updated with an older
7708                        // version of the one on the data partition, but which
7709                        // granted a new system permission that it didn't have
7710                        // before.  In this case we do want to allow the app to
7711                        // now get the new permission if the ancestral apk is
7712                        // privileged to get it.
7713                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7714                            for (int j=0;
7715                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7716                                if (perm.equals(
7717                                        sysPs.pkg.requestedPermissions.get(j))) {
7718                                    allowed = true;
7719                                    break;
7720                                }
7721                            }
7722                        }
7723                    }
7724                } else {
7725                    allowed = isPrivilegedApp(pkg);
7726                }
7727            }
7728        }
7729        if (!allowed && (bp.protectionLevel
7730                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7731            // For development permissions, a development permission
7732            // is granted only if it was already granted.
7733            allowed = origPermissions.hasInstallPermission(perm);
7734        }
7735        return allowed;
7736    }
7737
7738    final class ActivityIntentResolver
7739            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7740        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7741                boolean defaultOnly, int userId) {
7742            if (!sUserManager.exists(userId)) return null;
7743            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7744            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7745        }
7746
7747        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7748                int userId) {
7749            if (!sUserManager.exists(userId)) return null;
7750            mFlags = flags;
7751            return super.queryIntent(intent, resolvedType,
7752                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7753        }
7754
7755        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7756                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7757            if (!sUserManager.exists(userId)) return null;
7758            if (packageActivities == null) {
7759                return null;
7760            }
7761            mFlags = flags;
7762            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7763            final int N = packageActivities.size();
7764            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7765                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7766
7767            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7768            for (int i = 0; i < N; ++i) {
7769                intentFilters = packageActivities.get(i).intents;
7770                if (intentFilters != null && intentFilters.size() > 0) {
7771                    PackageParser.ActivityIntentInfo[] array =
7772                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7773                    intentFilters.toArray(array);
7774                    listCut.add(array);
7775                }
7776            }
7777            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7778        }
7779
7780        public final void addActivity(PackageParser.Activity a, String type) {
7781            final boolean systemApp = a.info.applicationInfo.isSystemApp();
7782            mActivities.put(a.getComponentName(), a);
7783            if (DEBUG_SHOW_INFO)
7784                Log.v(
7785                TAG, "  " + type + " " +
7786                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7787            if (DEBUG_SHOW_INFO)
7788                Log.v(TAG, "    Class=" + a.info.name);
7789            final int NI = a.intents.size();
7790            for (int j=0; j<NI; j++) {
7791                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7792                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7793                    intent.setPriority(0);
7794                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7795                            + a.className + " with priority > 0, forcing to 0");
7796                }
7797                if (DEBUG_SHOW_INFO) {
7798                    Log.v(TAG, "    IntentFilter:");
7799                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7800                }
7801                if (!intent.debugCheck()) {
7802                    Log.w(TAG, "==> For Activity " + a.info.name);
7803                }
7804                addFilter(intent);
7805            }
7806        }
7807
7808        public final void removeActivity(PackageParser.Activity a, String type) {
7809            mActivities.remove(a.getComponentName());
7810            if (DEBUG_SHOW_INFO) {
7811                Log.v(TAG, "  " + type + " "
7812                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7813                                : a.info.name) + ":");
7814                Log.v(TAG, "    Class=" + a.info.name);
7815            }
7816            final int NI = a.intents.size();
7817            for (int j=0; j<NI; j++) {
7818                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7819                if (DEBUG_SHOW_INFO) {
7820                    Log.v(TAG, "    IntentFilter:");
7821                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7822                }
7823                removeFilter(intent);
7824            }
7825        }
7826
7827        @Override
7828        protected boolean allowFilterResult(
7829                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7830            ActivityInfo filterAi = filter.activity.info;
7831            for (int i=dest.size()-1; i>=0; i--) {
7832                ActivityInfo destAi = dest.get(i).activityInfo;
7833                if (destAi.name == filterAi.name
7834                        && destAi.packageName == filterAi.packageName) {
7835                    return false;
7836                }
7837            }
7838            return true;
7839        }
7840
7841        @Override
7842        protected ActivityIntentInfo[] newArray(int size) {
7843            return new ActivityIntentInfo[size];
7844        }
7845
7846        @Override
7847        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7848            if (!sUserManager.exists(userId)) return true;
7849            PackageParser.Package p = filter.activity.owner;
7850            if (p != null) {
7851                PackageSetting ps = (PackageSetting)p.mExtras;
7852                if (ps != null) {
7853                    // System apps are never considered stopped for purposes of
7854                    // filtering, because there may be no way for the user to
7855                    // actually re-launch them.
7856                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7857                            && ps.getStopped(userId);
7858                }
7859            }
7860            return false;
7861        }
7862
7863        @Override
7864        protected boolean isPackageForFilter(String packageName,
7865                PackageParser.ActivityIntentInfo info) {
7866            return packageName.equals(info.activity.owner.packageName);
7867        }
7868
7869        @Override
7870        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7871                int match, int userId) {
7872            if (!sUserManager.exists(userId)) return null;
7873            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7874                return null;
7875            }
7876            final PackageParser.Activity activity = info.activity;
7877            if (mSafeMode && (activity.info.applicationInfo.flags
7878                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7879                return null;
7880            }
7881            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7882            if (ps == null) {
7883                return null;
7884            }
7885            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7886                    ps.readUserState(userId), userId);
7887            if (ai == null) {
7888                return null;
7889            }
7890            final ResolveInfo res = new ResolveInfo();
7891            res.activityInfo = ai;
7892            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7893                res.filter = info;
7894            }
7895            if (info != null) {
7896                res.handleAllWebDataURI = info.handleAllWebDataURI();
7897            }
7898            res.priority = info.getPriority();
7899            res.preferredOrder = activity.owner.mPreferredOrder;
7900            //System.out.println("Result: " + res.activityInfo.className +
7901            //                   " = " + res.priority);
7902            res.match = match;
7903            res.isDefault = info.hasDefault;
7904            res.labelRes = info.labelRes;
7905            res.nonLocalizedLabel = info.nonLocalizedLabel;
7906            if (userNeedsBadging(userId)) {
7907                res.noResourceId = true;
7908            } else {
7909                res.icon = info.icon;
7910            }
7911            res.system = res.activityInfo.applicationInfo.isSystemApp();
7912            return res;
7913        }
7914
7915        @Override
7916        protected void sortResults(List<ResolveInfo> results) {
7917            Collections.sort(results, mResolvePrioritySorter);
7918        }
7919
7920        @Override
7921        protected void dumpFilter(PrintWriter out, String prefix,
7922                PackageParser.ActivityIntentInfo filter) {
7923            out.print(prefix); out.print(
7924                    Integer.toHexString(System.identityHashCode(filter.activity)));
7925                    out.print(' ');
7926                    filter.activity.printComponentShortName(out);
7927                    out.print(" filter ");
7928                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7929        }
7930
7931        @Override
7932        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
7933            return filter.activity;
7934        }
7935
7936        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7937            PackageParser.Activity activity = (PackageParser.Activity)label;
7938            out.print(prefix); out.print(
7939                    Integer.toHexString(System.identityHashCode(activity)));
7940                    out.print(' ');
7941                    activity.printComponentShortName(out);
7942            if (count > 1) {
7943                out.print(" ("); out.print(count); out.print(" filters)");
7944            }
7945            out.println();
7946        }
7947
7948//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7949//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7950//            final List<ResolveInfo> retList = Lists.newArrayList();
7951//            while (i.hasNext()) {
7952//                final ResolveInfo resolveInfo = i.next();
7953//                if (isEnabledLP(resolveInfo.activityInfo)) {
7954//                    retList.add(resolveInfo);
7955//                }
7956//            }
7957//            return retList;
7958//        }
7959
7960        // Keys are String (activity class name), values are Activity.
7961        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
7962                = new ArrayMap<ComponentName, PackageParser.Activity>();
7963        private int mFlags;
7964    }
7965
7966    private final class ServiceIntentResolver
7967            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7968        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7969                boolean defaultOnly, int userId) {
7970            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7971            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7972        }
7973
7974        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7975                int userId) {
7976            if (!sUserManager.exists(userId)) return null;
7977            mFlags = flags;
7978            return super.queryIntent(intent, resolvedType,
7979                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7980        }
7981
7982        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7983                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7984            if (!sUserManager.exists(userId)) return null;
7985            if (packageServices == null) {
7986                return null;
7987            }
7988            mFlags = flags;
7989            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7990            final int N = packageServices.size();
7991            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7992                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7993
7994            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7995            for (int i = 0; i < N; ++i) {
7996                intentFilters = packageServices.get(i).intents;
7997                if (intentFilters != null && intentFilters.size() > 0) {
7998                    PackageParser.ServiceIntentInfo[] array =
7999                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8000                    intentFilters.toArray(array);
8001                    listCut.add(array);
8002                }
8003            }
8004            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8005        }
8006
8007        public final void addService(PackageParser.Service s) {
8008            mServices.put(s.getComponentName(), s);
8009            if (DEBUG_SHOW_INFO) {
8010                Log.v(TAG, "  "
8011                        + (s.info.nonLocalizedLabel != null
8012                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8013                Log.v(TAG, "    Class=" + s.info.name);
8014            }
8015            final int NI = s.intents.size();
8016            int j;
8017            for (j=0; j<NI; j++) {
8018                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8019                if (DEBUG_SHOW_INFO) {
8020                    Log.v(TAG, "    IntentFilter:");
8021                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8022                }
8023                if (!intent.debugCheck()) {
8024                    Log.w(TAG, "==> For Service " + s.info.name);
8025                }
8026                addFilter(intent);
8027            }
8028        }
8029
8030        public final void removeService(PackageParser.Service s) {
8031            mServices.remove(s.getComponentName());
8032            if (DEBUG_SHOW_INFO) {
8033                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8034                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8035                Log.v(TAG, "    Class=" + s.info.name);
8036            }
8037            final int NI = s.intents.size();
8038            int j;
8039            for (j=0; j<NI; j++) {
8040                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8041                if (DEBUG_SHOW_INFO) {
8042                    Log.v(TAG, "    IntentFilter:");
8043                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8044                }
8045                removeFilter(intent);
8046            }
8047        }
8048
8049        @Override
8050        protected boolean allowFilterResult(
8051                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8052            ServiceInfo filterSi = filter.service.info;
8053            for (int i=dest.size()-1; i>=0; i--) {
8054                ServiceInfo destAi = dest.get(i).serviceInfo;
8055                if (destAi.name == filterSi.name
8056                        && destAi.packageName == filterSi.packageName) {
8057                    return false;
8058                }
8059            }
8060            return true;
8061        }
8062
8063        @Override
8064        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8065            return new PackageParser.ServiceIntentInfo[size];
8066        }
8067
8068        @Override
8069        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8070            if (!sUserManager.exists(userId)) return true;
8071            PackageParser.Package p = filter.service.owner;
8072            if (p != null) {
8073                PackageSetting ps = (PackageSetting)p.mExtras;
8074                if (ps != null) {
8075                    // System apps are never considered stopped for purposes of
8076                    // filtering, because there may be no way for the user to
8077                    // actually re-launch them.
8078                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8079                            && ps.getStopped(userId);
8080                }
8081            }
8082            return false;
8083        }
8084
8085        @Override
8086        protected boolean isPackageForFilter(String packageName,
8087                PackageParser.ServiceIntentInfo info) {
8088            return packageName.equals(info.service.owner.packageName);
8089        }
8090
8091        @Override
8092        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8093                int match, int userId) {
8094            if (!sUserManager.exists(userId)) return null;
8095            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8096            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8097                return null;
8098            }
8099            final PackageParser.Service service = info.service;
8100            if (mSafeMode && (service.info.applicationInfo.flags
8101                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8102                return null;
8103            }
8104            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8105            if (ps == null) {
8106                return null;
8107            }
8108            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8109                    ps.readUserState(userId), userId);
8110            if (si == null) {
8111                return null;
8112            }
8113            final ResolveInfo res = new ResolveInfo();
8114            res.serviceInfo = si;
8115            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8116                res.filter = filter;
8117            }
8118            res.priority = info.getPriority();
8119            res.preferredOrder = service.owner.mPreferredOrder;
8120            res.match = match;
8121            res.isDefault = info.hasDefault;
8122            res.labelRes = info.labelRes;
8123            res.nonLocalizedLabel = info.nonLocalizedLabel;
8124            res.icon = info.icon;
8125            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8126            return res;
8127        }
8128
8129        @Override
8130        protected void sortResults(List<ResolveInfo> results) {
8131            Collections.sort(results, mResolvePrioritySorter);
8132        }
8133
8134        @Override
8135        protected void dumpFilter(PrintWriter out, String prefix,
8136                PackageParser.ServiceIntentInfo filter) {
8137            out.print(prefix); out.print(
8138                    Integer.toHexString(System.identityHashCode(filter.service)));
8139                    out.print(' ');
8140                    filter.service.printComponentShortName(out);
8141                    out.print(" filter ");
8142                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8143        }
8144
8145        @Override
8146        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8147            return filter.service;
8148        }
8149
8150        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8151            PackageParser.Service service = (PackageParser.Service)label;
8152            out.print(prefix); out.print(
8153                    Integer.toHexString(System.identityHashCode(service)));
8154                    out.print(' ');
8155                    service.printComponentShortName(out);
8156            if (count > 1) {
8157                out.print(" ("); out.print(count); out.print(" filters)");
8158            }
8159            out.println();
8160        }
8161
8162//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8163//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8164//            final List<ResolveInfo> retList = Lists.newArrayList();
8165//            while (i.hasNext()) {
8166//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8167//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8168//                    retList.add(resolveInfo);
8169//                }
8170//            }
8171//            return retList;
8172//        }
8173
8174        // Keys are String (activity class name), values are Activity.
8175        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8176                = new ArrayMap<ComponentName, PackageParser.Service>();
8177        private int mFlags;
8178    };
8179
8180    private final class ProviderIntentResolver
8181            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8182        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8183                boolean defaultOnly, int userId) {
8184            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8185            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8186        }
8187
8188        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8189                int userId) {
8190            if (!sUserManager.exists(userId))
8191                return null;
8192            mFlags = flags;
8193            return super.queryIntent(intent, resolvedType,
8194                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8195        }
8196
8197        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8198                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8199            if (!sUserManager.exists(userId))
8200                return null;
8201            if (packageProviders == null) {
8202                return null;
8203            }
8204            mFlags = flags;
8205            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8206            final int N = packageProviders.size();
8207            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8208                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8209
8210            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8211            for (int i = 0; i < N; ++i) {
8212                intentFilters = packageProviders.get(i).intents;
8213                if (intentFilters != null && intentFilters.size() > 0) {
8214                    PackageParser.ProviderIntentInfo[] array =
8215                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8216                    intentFilters.toArray(array);
8217                    listCut.add(array);
8218                }
8219            }
8220            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8221        }
8222
8223        public final void addProvider(PackageParser.Provider p) {
8224            if (mProviders.containsKey(p.getComponentName())) {
8225                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8226                return;
8227            }
8228
8229            mProviders.put(p.getComponentName(), p);
8230            if (DEBUG_SHOW_INFO) {
8231                Log.v(TAG, "  "
8232                        + (p.info.nonLocalizedLabel != null
8233                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8234                Log.v(TAG, "    Class=" + p.info.name);
8235            }
8236            final int NI = p.intents.size();
8237            int j;
8238            for (j = 0; j < NI; j++) {
8239                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8240                if (DEBUG_SHOW_INFO) {
8241                    Log.v(TAG, "    IntentFilter:");
8242                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8243                }
8244                if (!intent.debugCheck()) {
8245                    Log.w(TAG, "==> For Provider " + p.info.name);
8246                }
8247                addFilter(intent);
8248            }
8249        }
8250
8251        public final void removeProvider(PackageParser.Provider p) {
8252            mProviders.remove(p.getComponentName());
8253            if (DEBUG_SHOW_INFO) {
8254                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8255                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8256                Log.v(TAG, "    Class=" + p.info.name);
8257            }
8258            final int NI = p.intents.size();
8259            int j;
8260            for (j = 0; j < NI; j++) {
8261                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8262                if (DEBUG_SHOW_INFO) {
8263                    Log.v(TAG, "    IntentFilter:");
8264                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8265                }
8266                removeFilter(intent);
8267            }
8268        }
8269
8270        @Override
8271        protected boolean allowFilterResult(
8272                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8273            ProviderInfo filterPi = filter.provider.info;
8274            for (int i = dest.size() - 1; i >= 0; i--) {
8275                ProviderInfo destPi = dest.get(i).providerInfo;
8276                if (destPi.name == filterPi.name
8277                        && destPi.packageName == filterPi.packageName) {
8278                    return false;
8279                }
8280            }
8281            return true;
8282        }
8283
8284        @Override
8285        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8286            return new PackageParser.ProviderIntentInfo[size];
8287        }
8288
8289        @Override
8290        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8291            if (!sUserManager.exists(userId))
8292                return true;
8293            PackageParser.Package p = filter.provider.owner;
8294            if (p != null) {
8295                PackageSetting ps = (PackageSetting) p.mExtras;
8296                if (ps != null) {
8297                    // System apps are never considered stopped for purposes of
8298                    // filtering, because there may be no way for the user to
8299                    // actually re-launch them.
8300                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8301                            && ps.getStopped(userId);
8302                }
8303            }
8304            return false;
8305        }
8306
8307        @Override
8308        protected boolean isPackageForFilter(String packageName,
8309                PackageParser.ProviderIntentInfo info) {
8310            return packageName.equals(info.provider.owner.packageName);
8311        }
8312
8313        @Override
8314        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8315                int match, int userId) {
8316            if (!sUserManager.exists(userId))
8317                return null;
8318            final PackageParser.ProviderIntentInfo info = filter;
8319            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8320                return null;
8321            }
8322            final PackageParser.Provider provider = info.provider;
8323            if (mSafeMode && (provider.info.applicationInfo.flags
8324                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8325                return null;
8326            }
8327            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8328            if (ps == null) {
8329                return null;
8330            }
8331            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8332                    ps.readUserState(userId), userId);
8333            if (pi == null) {
8334                return null;
8335            }
8336            final ResolveInfo res = new ResolveInfo();
8337            res.providerInfo = pi;
8338            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8339                res.filter = filter;
8340            }
8341            res.priority = info.getPriority();
8342            res.preferredOrder = provider.owner.mPreferredOrder;
8343            res.match = match;
8344            res.isDefault = info.hasDefault;
8345            res.labelRes = info.labelRes;
8346            res.nonLocalizedLabel = info.nonLocalizedLabel;
8347            res.icon = info.icon;
8348            res.system = res.providerInfo.applicationInfo.isSystemApp();
8349            return res;
8350        }
8351
8352        @Override
8353        protected void sortResults(List<ResolveInfo> results) {
8354            Collections.sort(results, mResolvePrioritySorter);
8355        }
8356
8357        @Override
8358        protected void dumpFilter(PrintWriter out, String prefix,
8359                PackageParser.ProviderIntentInfo filter) {
8360            out.print(prefix);
8361            out.print(
8362                    Integer.toHexString(System.identityHashCode(filter.provider)));
8363            out.print(' ');
8364            filter.provider.printComponentShortName(out);
8365            out.print(" filter ");
8366            out.println(Integer.toHexString(System.identityHashCode(filter)));
8367        }
8368
8369        @Override
8370        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8371            return filter.provider;
8372        }
8373
8374        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8375            PackageParser.Provider provider = (PackageParser.Provider)label;
8376            out.print(prefix); out.print(
8377                    Integer.toHexString(System.identityHashCode(provider)));
8378                    out.print(' ');
8379                    provider.printComponentShortName(out);
8380            if (count > 1) {
8381                out.print(" ("); out.print(count); out.print(" filters)");
8382            }
8383            out.println();
8384        }
8385
8386        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8387                = new ArrayMap<ComponentName, PackageParser.Provider>();
8388        private int mFlags;
8389    };
8390
8391    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8392            new Comparator<ResolveInfo>() {
8393        public int compare(ResolveInfo r1, ResolveInfo r2) {
8394            int v1 = r1.priority;
8395            int v2 = r2.priority;
8396            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8397            if (v1 != v2) {
8398                return (v1 > v2) ? -1 : 1;
8399            }
8400            v1 = r1.preferredOrder;
8401            v2 = r2.preferredOrder;
8402            if (v1 != v2) {
8403                return (v1 > v2) ? -1 : 1;
8404            }
8405            if (r1.isDefault != r2.isDefault) {
8406                return r1.isDefault ? -1 : 1;
8407            }
8408            v1 = r1.match;
8409            v2 = r2.match;
8410            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8411            if (v1 != v2) {
8412                return (v1 > v2) ? -1 : 1;
8413            }
8414            if (r1.system != r2.system) {
8415                return r1.system ? -1 : 1;
8416            }
8417            return 0;
8418        }
8419    };
8420
8421    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8422            new Comparator<ProviderInfo>() {
8423        public int compare(ProviderInfo p1, ProviderInfo p2) {
8424            final int v1 = p1.initOrder;
8425            final int v2 = p2.initOrder;
8426            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8427        }
8428    };
8429
8430    static final void sendPackageBroadcast(String action, String pkg,
8431            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
8432            int[] userIds) {
8433        IActivityManager am = ActivityManagerNative.getDefault();
8434        if (am != null) {
8435            try {
8436                if (userIds == null) {
8437                    userIds = am.getRunningUserIds();
8438                }
8439                for (int id : userIds) {
8440                    final Intent intent = new Intent(action,
8441                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
8442                    if (extras != null) {
8443                        intent.putExtras(extras);
8444                    }
8445                    if (targetPkg != null) {
8446                        intent.setPackage(targetPkg);
8447                    }
8448                    // Modify the UID when posting to other users
8449                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8450                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
8451                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8452                        intent.putExtra(Intent.EXTRA_UID, uid);
8453                    }
8454                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8455                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8456                    if (DEBUG_BROADCASTS) {
8457                        RuntimeException here = new RuntimeException("here");
8458                        here.fillInStackTrace();
8459                        Slog.d(TAG, "Sending to user " + id + ": "
8460                                + intent.toShortString(false, true, false, false)
8461                                + " " + intent.getExtras(), here);
8462                    }
8463                    am.broadcastIntent(null, intent, null, finishedReceiver,
8464                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
8465                            finishedReceiver != null, false, id);
8466                }
8467            } catch (RemoteException ex) {
8468            }
8469        }
8470    }
8471
8472    /**
8473     * Check if the external storage media is available. This is true if there
8474     * is a mounted external storage medium or if the external storage is
8475     * emulated.
8476     */
8477    private boolean isExternalMediaAvailable() {
8478        return mMediaMounted || Environment.isExternalStorageEmulated();
8479    }
8480
8481    @Override
8482    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8483        // writer
8484        synchronized (mPackages) {
8485            if (!isExternalMediaAvailable()) {
8486                // If the external storage is no longer mounted at this point,
8487                // the caller may not have been able to delete all of this
8488                // packages files and can not delete any more.  Bail.
8489                return null;
8490            }
8491            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8492            if (lastPackage != null) {
8493                pkgs.remove(lastPackage);
8494            }
8495            if (pkgs.size() > 0) {
8496                return pkgs.get(0);
8497            }
8498        }
8499        return null;
8500    }
8501
8502    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8503        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8504                userId, andCode ? 1 : 0, packageName);
8505        if (mSystemReady) {
8506            msg.sendToTarget();
8507        } else {
8508            if (mPostSystemReadyMessages == null) {
8509                mPostSystemReadyMessages = new ArrayList<>();
8510            }
8511            mPostSystemReadyMessages.add(msg);
8512        }
8513    }
8514
8515    void startCleaningPackages() {
8516        // reader
8517        synchronized (mPackages) {
8518            if (!isExternalMediaAvailable()) {
8519                return;
8520            }
8521            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8522                return;
8523            }
8524        }
8525        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8526        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8527        IActivityManager am = ActivityManagerNative.getDefault();
8528        if (am != null) {
8529            try {
8530                am.startService(null, intent, null, UserHandle.USER_OWNER);
8531            } catch (RemoteException e) {
8532            }
8533        }
8534    }
8535
8536    @Override
8537    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8538            int installFlags, String installerPackageName, VerificationParams verificationParams,
8539            String packageAbiOverride) {
8540        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8541                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8542    }
8543
8544    @Override
8545    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8546            int installFlags, String installerPackageName, VerificationParams verificationParams,
8547            String packageAbiOverride, int userId) {
8548        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8549
8550        final int callingUid = Binder.getCallingUid();
8551        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8552
8553        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8554            try {
8555                if (observer != null) {
8556                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8557                }
8558            } catch (RemoteException re) {
8559            }
8560            return;
8561        }
8562
8563        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8564            installFlags |= PackageManager.INSTALL_FROM_ADB;
8565
8566        } else {
8567            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8568            // about installerPackageName.
8569
8570            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8571            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8572        }
8573
8574        UserHandle user;
8575        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8576            user = UserHandle.ALL;
8577        } else {
8578            user = new UserHandle(userId);
8579        }
8580
8581        // Only system components can circumvent runtime permissions when installing.
8582        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
8583                && mContext.checkCallingOrSelfPermission(Manifest.permission
8584                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
8585            throw new SecurityException("You need the "
8586                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
8587                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
8588        }
8589
8590        verificationParams.setInstallerUid(callingUid);
8591
8592        final File originFile = new File(originPath);
8593        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8594
8595        final Message msg = mHandler.obtainMessage(INIT_COPY);
8596        msg.obj = new InstallParams(origin, observer, installFlags,
8597                installerPackageName, null, verificationParams, user, packageAbiOverride);
8598        mHandler.sendMessage(msg);
8599    }
8600
8601    void installStage(String packageName, File stagedDir, String stagedCid,
8602            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8603            String installerPackageName, int installerUid, UserHandle user) {
8604        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8605                params.referrerUri, installerUid, null);
8606
8607        final OriginInfo origin;
8608        if (stagedDir != null) {
8609            origin = OriginInfo.fromStagedFile(stagedDir);
8610        } else {
8611            origin = OriginInfo.fromStagedContainer(stagedCid);
8612        }
8613
8614        final Message msg = mHandler.obtainMessage(INIT_COPY);
8615        msg.obj = new InstallParams(origin, observer, params.installFlags,
8616                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8617        mHandler.sendMessage(msg);
8618    }
8619
8620    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8621        Bundle extras = new Bundle(1);
8622        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8623
8624        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8625                packageName, extras, null, null, new int[] {userId});
8626        try {
8627            IActivityManager am = ActivityManagerNative.getDefault();
8628            final boolean isSystem =
8629                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8630            if (isSystem && am.isUserRunning(userId, false)) {
8631                // The just-installed/enabled app is bundled on the system, so presumed
8632                // to be able to run automatically without needing an explicit launch.
8633                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8634                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8635                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8636                        .setPackage(packageName);
8637                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8638                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8639            }
8640        } catch (RemoteException e) {
8641            // shouldn't happen
8642            Slog.w(TAG, "Unable to bootstrap installed package", e);
8643        }
8644    }
8645
8646    @Override
8647    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8648            int userId) {
8649        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8650        PackageSetting pkgSetting;
8651        final int uid = Binder.getCallingUid();
8652        enforceCrossUserPermission(uid, userId, true, true,
8653                "setApplicationHiddenSetting for user " + userId);
8654
8655        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8656            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8657            return false;
8658        }
8659
8660        long callingId = Binder.clearCallingIdentity();
8661        try {
8662            boolean sendAdded = false;
8663            boolean sendRemoved = false;
8664            // writer
8665            synchronized (mPackages) {
8666                pkgSetting = mSettings.mPackages.get(packageName);
8667                if (pkgSetting == null) {
8668                    return false;
8669                }
8670                if (pkgSetting.getHidden(userId) != hidden) {
8671                    pkgSetting.setHidden(hidden, userId);
8672                    mSettings.writePackageRestrictionsLPr(userId);
8673                    if (hidden) {
8674                        sendRemoved = true;
8675                    } else {
8676                        sendAdded = true;
8677                    }
8678                }
8679            }
8680            if (sendAdded) {
8681                sendPackageAddedForUser(packageName, pkgSetting, userId);
8682                return true;
8683            }
8684            if (sendRemoved) {
8685                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8686                        "hiding pkg");
8687                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8688            }
8689        } finally {
8690            Binder.restoreCallingIdentity(callingId);
8691        }
8692        return false;
8693    }
8694
8695    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8696            int userId) {
8697        final PackageRemovedInfo info = new PackageRemovedInfo();
8698        info.removedPackage = packageName;
8699        info.removedUsers = new int[] {userId};
8700        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8701        info.sendBroadcast(false, false, false);
8702    }
8703
8704    /**
8705     * Returns true if application is not found or there was an error. Otherwise it returns
8706     * the hidden state of the package for the given user.
8707     */
8708    @Override
8709    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8710        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8711        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8712                false, "getApplicationHidden for user " + userId);
8713        PackageSetting pkgSetting;
8714        long callingId = Binder.clearCallingIdentity();
8715        try {
8716            // writer
8717            synchronized (mPackages) {
8718                pkgSetting = mSettings.mPackages.get(packageName);
8719                if (pkgSetting == null) {
8720                    return true;
8721                }
8722                return pkgSetting.getHidden(userId);
8723            }
8724        } finally {
8725            Binder.restoreCallingIdentity(callingId);
8726        }
8727    }
8728
8729    /**
8730     * @hide
8731     */
8732    @Override
8733    public int installExistingPackageAsUser(String packageName, int userId) {
8734        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8735                null);
8736        PackageSetting pkgSetting;
8737        final int uid = Binder.getCallingUid();
8738        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8739                + userId);
8740        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8741            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8742        }
8743
8744        long callingId = Binder.clearCallingIdentity();
8745        try {
8746            boolean sendAdded = false;
8747
8748            // writer
8749            synchronized (mPackages) {
8750                pkgSetting = mSettings.mPackages.get(packageName);
8751                if (pkgSetting == null) {
8752                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8753                }
8754                if (!pkgSetting.getInstalled(userId)) {
8755                    pkgSetting.setInstalled(true, userId);
8756                    pkgSetting.setHidden(false, userId);
8757                    mSettings.writePackageRestrictionsLPr(userId);
8758                    sendAdded = true;
8759                }
8760            }
8761
8762            if (sendAdded) {
8763                sendPackageAddedForUser(packageName, pkgSetting, userId);
8764            }
8765        } finally {
8766            Binder.restoreCallingIdentity(callingId);
8767        }
8768
8769        return PackageManager.INSTALL_SUCCEEDED;
8770    }
8771
8772    boolean isUserRestricted(int userId, String restrictionKey) {
8773        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8774        if (restrictions.getBoolean(restrictionKey, false)) {
8775            Log.w(TAG, "User is restricted: " + restrictionKey);
8776            return true;
8777        }
8778        return false;
8779    }
8780
8781    @Override
8782    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8783        mContext.enforceCallingOrSelfPermission(
8784                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8785                "Only package verification agents can verify applications");
8786
8787        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8788        final PackageVerificationResponse response = new PackageVerificationResponse(
8789                verificationCode, Binder.getCallingUid());
8790        msg.arg1 = id;
8791        msg.obj = response;
8792        mHandler.sendMessage(msg);
8793    }
8794
8795    @Override
8796    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8797            long millisecondsToDelay) {
8798        mContext.enforceCallingOrSelfPermission(
8799                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8800                "Only package verification agents can extend verification timeouts");
8801
8802        final PackageVerificationState state = mPendingVerification.get(id);
8803        final PackageVerificationResponse response = new PackageVerificationResponse(
8804                verificationCodeAtTimeout, Binder.getCallingUid());
8805
8806        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8807            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8808        }
8809        if (millisecondsToDelay < 0) {
8810            millisecondsToDelay = 0;
8811        }
8812        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8813                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8814            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8815        }
8816
8817        if ((state != null) && !state.timeoutExtended()) {
8818            state.extendTimeout();
8819
8820            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8821            msg.arg1 = id;
8822            msg.obj = response;
8823            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8824        }
8825    }
8826
8827    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8828            int verificationCode, UserHandle user) {
8829        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8830        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8831        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8832        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8833        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8834
8835        mContext.sendBroadcastAsUser(intent, user,
8836                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8837    }
8838
8839    private ComponentName matchComponentForVerifier(String packageName,
8840            List<ResolveInfo> receivers) {
8841        ActivityInfo targetReceiver = null;
8842
8843        final int NR = receivers.size();
8844        for (int i = 0; i < NR; i++) {
8845            final ResolveInfo info = receivers.get(i);
8846            if (info.activityInfo == null) {
8847                continue;
8848            }
8849
8850            if (packageName.equals(info.activityInfo.packageName)) {
8851                targetReceiver = info.activityInfo;
8852                break;
8853            }
8854        }
8855
8856        if (targetReceiver == null) {
8857            return null;
8858        }
8859
8860        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8861    }
8862
8863    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8864            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8865        if (pkgInfo.verifiers.length == 0) {
8866            return null;
8867        }
8868
8869        final int N = pkgInfo.verifiers.length;
8870        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8871        for (int i = 0; i < N; i++) {
8872            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8873
8874            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8875                    receivers);
8876            if (comp == null) {
8877                continue;
8878            }
8879
8880            final int verifierUid = getUidForVerifier(verifierInfo);
8881            if (verifierUid == -1) {
8882                continue;
8883            }
8884
8885            if (DEBUG_VERIFY) {
8886                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8887                        + " with the correct signature");
8888            }
8889            sufficientVerifiers.add(comp);
8890            verificationState.addSufficientVerifier(verifierUid);
8891        }
8892
8893        return sufficientVerifiers;
8894    }
8895
8896    private int getUidForVerifier(VerifierInfo verifierInfo) {
8897        synchronized (mPackages) {
8898            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8899            if (pkg == null) {
8900                return -1;
8901            } else if (pkg.mSignatures.length != 1) {
8902                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8903                        + " has more than one signature; ignoring");
8904                return -1;
8905            }
8906
8907            /*
8908             * If the public key of the package's signature does not match
8909             * our expected public key, then this is a different package and
8910             * we should skip.
8911             */
8912
8913            final byte[] expectedPublicKey;
8914            try {
8915                final Signature verifierSig = pkg.mSignatures[0];
8916                final PublicKey publicKey = verifierSig.getPublicKey();
8917                expectedPublicKey = publicKey.getEncoded();
8918            } catch (CertificateException e) {
8919                return -1;
8920            }
8921
8922            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8923
8924            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8925                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8926                        + " does not have the expected public key; ignoring");
8927                return -1;
8928            }
8929
8930            return pkg.applicationInfo.uid;
8931        }
8932    }
8933
8934    @Override
8935    public void finishPackageInstall(int token) {
8936        enforceSystemOrRoot("Only the system is allowed to finish installs");
8937
8938        if (DEBUG_INSTALL) {
8939            Slog.v(TAG, "BM finishing package install for " + token);
8940        }
8941
8942        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8943        mHandler.sendMessage(msg);
8944    }
8945
8946    /**
8947     * Get the verification agent timeout.
8948     *
8949     * @return verification timeout in milliseconds
8950     */
8951    private long getVerificationTimeout() {
8952        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8953                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8954                DEFAULT_VERIFICATION_TIMEOUT);
8955    }
8956
8957    /**
8958     * Get the default verification agent response code.
8959     *
8960     * @return default verification response code
8961     */
8962    private int getDefaultVerificationResponse() {
8963        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8964                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8965                DEFAULT_VERIFICATION_RESPONSE);
8966    }
8967
8968    /**
8969     * Check whether or not package verification has been enabled.
8970     *
8971     * @return true if verification should be performed
8972     */
8973    private boolean isVerificationEnabled(int userId, int installFlags) {
8974        if (!DEFAULT_VERIFY_ENABLE) {
8975            return false;
8976        }
8977
8978        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8979
8980        // Check if installing from ADB
8981        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8982            // Do not run verification in a test harness environment
8983            if (ActivityManager.isRunningInTestHarness()) {
8984                return false;
8985            }
8986            if (ensureVerifyAppsEnabled) {
8987                return true;
8988            }
8989            // Check if the developer does not want package verification for ADB installs
8990            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8991                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8992                return false;
8993            }
8994        }
8995
8996        if (ensureVerifyAppsEnabled) {
8997            return true;
8998        }
8999
9000        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9001                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9002    }
9003
9004    @Override
9005    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9006            throws RemoteException {
9007        mContext.enforceCallingOrSelfPermission(
9008                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9009                "Only intentfilter verification agents can verify applications");
9010
9011        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9012        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9013                Binder.getCallingUid(), verificationCode, failedDomains);
9014        msg.arg1 = id;
9015        msg.obj = response;
9016        mHandler.sendMessage(msg);
9017    }
9018
9019    @Override
9020    public int getIntentVerificationStatus(String packageName, int userId) {
9021        synchronized (mPackages) {
9022            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9023        }
9024    }
9025
9026    @Override
9027    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9028        boolean result = false;
9029        synchronized (mPackages) {
9030            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9031        }
9032        scheduleWritePackageRestrictionsLocked(userId);
9033        return result;
9034    }
9035
9036    @Override
9037    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9038        synchronized (mPackages) {
9039            return mSettings.getIntentFilterVerificationsLPr(packageName);
9040        }
9041    }
9042
9043    @Override
9044    public List<IntentFilter> getAllIntentFilters(String packageName) {
9045        if (TextUtils.isEmpty(packageName)) {
9046            return Collections.<IntentFilter>emptyList();
9047        }
9048        synchronized (mPackages) {
9049            PackageParser.Package pkg = mPackages.get(packageName);
9050            if (pkg == null || pkg.activities == null) {
9051                return Collections.<IntentFilter>emptyList();
9052            }
9053            final int count = pkg.activities.size();
9054            ArrayList<IntentFilter> result = new ArrayList<>();
9055            for (int n=0; n<count; n++) {
9056                PackageParser.Activity activity = pkg.activities.get(n);
9057                if (activity.intents != null || activity.intents.size() > 0) {
9058                    result.addAll(activity.intents);
9059                }
9060            }
9061            return result;
9062        }
9063    }
9064
9065    @Override
9066    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9067        synchronized (mPackages) {
9068            return mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9069        }
9070    }
9071
9072    @Override
9073    public String getDefaultBrowserPackageName(int userId) {
9074        synchronized (mPackages) {
9075            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9076        }
9077    }
9078
9079    /**
9080     * Get the "allow unknown sources" setting.
9081     *
9082     * @return the current "allow unknown sources" setting
9083     */
9084    private int getUnknownSourcesSettings() {
9085        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9086                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9087                -1);
9088    }
9089
9090    @Override
9091    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9092        final int uid = Binder.getCallingUid();
9093        // writer
9094        synchronized (mPackages) {
9095            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9096            if (targetPackageSetting == null) {
9097                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9098            }
9099
9100            PackageSetting installerPackageSetting;
9101            if (installerPackageName != null) {
9102                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9103                if (installerPackageSetting == null) {
9104                    throw new IllegalArgumentException("Unknown installer package: "
9105                            + installerPackageName);
9106                }
9107            } else {
9108                installerPackageSetting = null;
9109            }
9110
9111            Signature[] callerSignature;
9112            Object obj = mSettings.getUserIdLPr(uid);
9113            if (obj != null) {
9114                if (obj instanceof SharedUserSetting) {
9115                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9116                } else if (obj instanceof PackageSetting) {
9117                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9118                } else {
9119                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9120                }
9121            } else {
9122                throw new SecurityException("Unknown calling uid " + uid);
9123            }
9124
9125            // Verify: can't set installerPackageName to a package that is
9126            // not signed with the same cert as the caller.
9127            if (installerPackageSetting != null) {
9128                if (compareSignatures(callerSignature,
9129                        installerPackageSetting.signatures.mSignatures)
9130                        != PackageManager.SIGNATURE_MATCH) {
9131                    throw new SecurityException(
9132                            "Caller does not have same cert as new installer package "
9133                            + installerPackageName);
9134                }
9135            }
9136
9137            // Verify: if target already has an installer package, it must
9138            // be signed with the same cert as the caller.
9139            if (targetPackageSetting.installerPackageName != null) {
9140                PackageSetting setting = mSettings.mPackages.get(
9141                        targetPackageSetting.installerPackageName);
9142                // If the currently set package isn't valid, then it's always
9143                // okay to change it.
9144                if (setting != null) {
9145                    if (compareSignatures(callerSignature,
9146                            setting.signatures.mSignatures)
9147                            != PackageManager.SIGNATURE_MATCH) {
9148                        throw new SecurityException(
9149                                "Caller does not have same cert as old installer package "
9150                                + targetPackageSetting.installerPackageName);
9151                    }
9152                }
9153            }
9154
9155            // Okay!
9156            targetPackageSetting.installerPackageName = installerPackageName;
9157            scheduleWriteSettingsLocked();
9158        }
9159    }
9160
9161    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9162        // Queue up an async operation since the package installation may take a little while.
9163        mHandler.post(new Runnable() {
9164            public void run() {
9165                mHandler.removeCallbacks(this);
9166                 // Result object to be returned
9167                PackageInstalledInfo res = new PackageInstalledInfo();
9168                res.returnCode = currentStatus;
9169                res.uid = -1;
9170                res.pkg = null;
9171                res.removedInfo = new PackageRemovedInfo();
9172                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9173                    args.doPreInstall(res.returnCode);
9174                    synchronized (mInstallLock) {
9175                        installPackageLI(args, res);
9176                    }
9177                    args.doPostInstall(res.returnCode, res.uid);
9178                }
9179
9180                // A restore should be performed at this point if (a) the install
9181                // succeeded, (b) the operation is not an update, and (c) the new
9182                // package has not opted out of backup participation.
9183                final boolean update = res.removedInfo.removedPackage != null;
9184                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9185                boolean doRestore = !update
9186                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9187
9188                // Set up the post-install work request bookkeeping.  This will be used
9189                // and cleaned up by the post-install event handling regardless of whether
9190                // there's a restore pass performed.  Token values are >= 1.
9191                int token;
9192                if (mNextInstallToken < 0) mNextInstallToken = 1;
9193                token = mNextInstallToken++;
9194
9195                PostInstallData data = new PostInstallData(args, res);
9196                mRunningInstalls.put(token, data);
9197                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9198
9199                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9200                    // Pass responsibility to the Backup Manager.  It will perform a
9201                    // restore if appropriate, then pass responsibility back to the
9202                    // Package Manager to run the post-install observer callbacks
9203                    // and broadcasts.
9204                    IBackupManager bm = IBackupManager.Stub.asInterface(
9205                            ServiceManager.getService(Context.BACKUP_SERVICE));
9206                    if (bm != null) {
9207                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9208                                + " to BM for possible restore");
9209                        try {
9210                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9211                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9212                            } else {
9213                                doRestore = false;
9214                            }
9215                        } catch (RemoteException e) {
9216                            // can't happen; the backup manager is local
9217                        } catch (Exception e) {
9218                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9219                            doRestore = false;
9220                        }
9221                    } else {
9222                        Slog.e(TAG, "Backup Manager not found!");
9223                        doRestore = false;
9224                    }
9225                }
9226
9227                if (!doRestore) {
9228                    // No restore possible, or the Backup Manager was mysteriously not
9229                    // available -- just fire the post-install work request directly.
9230                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9231                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9232                    mHandler.sendMessage(msg);
9233                }
9234            }
9235        });
9236    }
9237
9238    private abstract class HandlerParams {
9239        private static final int MAX_RETRIES = 4;
9240
9241        /**
9242         * Number of times startCopy() has been attempted and had a non-fatal
9243         * error.
9244         */
9245        private int mRetries = 0;
9246
9247        /** User handle for the user requesting the information or installation. */
9248        private final UserHandle mUser;
9249
9250        HandlerParams(UserHandle user) {
9251            mUser = user;
9252        }
9253
9254        UserHandle getUser() {
9255            return mUser;
9256        }
9257
9258        final boolean startCopy() {
9259            boolean res;
9260            try {
9261                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9262
9263                if (++mRetries > MAX_RETRIES) {
9264                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9265                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9266                    handleServiceError();
9267                    return false;
9268                } else {
9269                    handleStartCopy();
9270                    res = true;
9271                }
9272            } catch (RemoteException e) {
9273                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9274                mHandler.sendEmptyMessage(MCS_RECONNECT);
9275                res = false;
9276            }
9277            handleReturnCode();
9278            return res;
9279        }
9280
9281        final void serviceError() {
9282            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9283            handleServiceError();
9284            handleReturnCode();
9285        }
9286
9287        abstract void handleStartCopy() throws RemoteException;
9288        abstract void handleServiceError();
9289        abstract void handleReturnCode();
9290    }
9291
9292    class MeasureParams extends HandlerParams {
9293        private final PackageStats mStats;
9294        private boolean mSuccess;
9295
9296        private final IPackageStatsObserver mObserver;
9297
9298        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9299            super(new UserHandle(stats.userHandle));
9300            mObserver = observer;
9301            mStats = stats;
9302        }
9303
9304        @Override
9305        public String toString() {
9306            return "MeasureParams{"
9307                + Integer.toHexString(System.identityHashCode(this))
9308                + " " + mStats.packageName + "}";
9309        }
9310
9311        @Override
9312        void handleStartCopy() throws RemoteException {
9313            synchronized (mInstallLock) {
9314                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9315            }
9316
9317            if (mSuccess) {
9318                final boolean mounted;
9319                if (Environment.isExternalStorageEmulated()) {
9320                    mounted = true;
9321                } else {
9322                    final String status = Environment.getExternalStorageState();
9323                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9324                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9325                }
9326
9327                if (mounted) {
9328                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9329
9330                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9331                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9332
9333                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9334                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9335
9336                    // Always subtract cache size, since it's a subdirectory
9337                    mStats.externalDataSize -= mStats.externalCacheSize;
9338
9339                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9340                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9341
9342                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9343                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9344                }
9345            }
9346        }
9347
9348        @Override
9349        void handleReturnCode() {
9350            if (mObserver != null) {
9351                try {
9352                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9353                } catch (RemoteException e) {
9354                    Slog.i(TAG, "Observer no longer exists.");
9355                }
9356            }
9357        }
9358
9359        @Override
9360        void handleServiceError() {
9361            Slog.e(TAG, "Could not measure application " + mStats.packageName
9362                            + " external storage");
9363        }
9364    }
9365
9366    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9367            throws RemoteException {
9368        long result = 0;
9369        for (File path : paths) {
9370            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9371        }
9372        return result;
9373    }
9374
9375    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9376        for (File path : paths) {
9377            try {
9378                mcs.clearDirectory(path.getAbsolutePath());
9379            } catch (RemoteException e) {
9380            }
9381        }
9382    }
9383
9384    static class OriginInfo {
9385        /**
9386         * Location where install is coming from, before it has been
9387         * copied/renamed into place. This could be a single monolithic APK
9388         * file, or a cluster directory. This location may be untrusted.
9389         */
9390        final File file;
9391        final String cid;
9392
9393        /**
9394         * Flag indicating that {@link #file} or {@link #cid} has already been
9395         * staged, meaning downstream users don't need to defensively copy the
9396         * contents.
9397         */
9398        final boolean staged;
9399
9400        /**
9401         * Flag indicating that {@link #file} or {@link #cid} is an already
9402         * installed app that is being moved.
9403         */
9404        final boolean existing;
9405
9406        final String resolvedPath;
9407        final File resolvedFile;
9408
9409        static OriginInfo fromNothing() {
9410            return new OriginInfo(null, null, false, false);
9411        }
9412
9413        static OriginInfo fromUntrustedFile(File file) {
9414            return new OriginInfo(file, null, false, false);
9415        }
9416
9417        static OriginInfo fromExistingFile(File file) {
9418            return new OriginInfo(file, null, false, true);
9419        }
9420
9421        static OriginInfo fromStagedFile(File file) {
9422            return new OriginInfo(file, null, true, false);
9423        }
9424
9425        static OriginInfo fromStagedContainer(String cid) {
9426            return new OriginInfo(null, cid, true, false);
9427        }
9428
9429        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9430            this.file = file;
9431            this.cid = cid;
9432            this.staged = staged;
9433            this.existing = existing;
9434
9435            if (cid != null) {
9436                resolvedPath = PackageHelper.getSdDir(cid);
9437                resolvedFile = new File(resolvedPath);
9438            } else if (file != null) {
9439                resolvedPath = file.getAbsolutePath();
9440                resolvedFile = file;
9441            } else {
9442                resolvedPath = null;
9443                resolvedFile = null;
9444            }
9445        }
9446    }
9447
9448    class InstallParams extends HandlerParams {
9449        final OriginInfo origin;
9450        final IPackageInstallObserver2 observer;
9451        int installFlags;
9452        final String installerPackageName;
9453        final String volumeUuid;
9454        final VerificationParams verificationParams;
9455        private InstallArgs mArgs;
9456        private int mRet;
9457        final String packageAbiOverride;
9458
9459        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9460                String installerPackageName, String volumeUuid,
9461                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9462            super(user);
9463            this.origin = origin;
9464            this.observer = observer;
9465            this.installFlags = installFlags;
9466            this.installerPackageName = installerPackageName;
9467            this.volumeUuid = volumeUuid;
9468            this.verificationParams = verificationParams;
9469            this.packageAbiOverride = packageAbiOverride;
9470        }
9471
9472        @Override
9473        public String toString() {
9474            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9475                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9476        }
9477
9478        public ManifestDigest getManifestDigest() {
9479            if (verificationParams == null) {
9480                return null;
9481            }
9482            return verificationParams.getManifestDigest();
9483        }
9484
9485        private int installLocationPolicy(PackageInfoLite pkgLite) {
9486            String packageName = pkgLite.packageName;
9487            int installLocation = pkgLite.installLocation;
9488            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9489            // reader
9490            synchronized (mPackages) {
9491                PackageParser.Package pkg = mPackages.get(packageName);
9492                if (pkg != null) {
9493                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9494                        // Check for downgrading.
9495                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9496                            try {
9497                                checkDowngrade(pkg, pkgLite);
9498                            } catch (PackageManagerException e) {
9499                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9500                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9501                            }
9502                        }
9503                        // Check for updated system application.
9504                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9505                            if (onSd) {
9506                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9507                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9508                            }
9509                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9510                        } else {
9511                            if (onSd) {
9512                                // Install flag overrides everything.
9513                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9514                            }
9515                            // If current upgrade specifies particular preference
9516                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9517                                // Application explicitly specified internal.
9518                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9519                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9520                                // App explictly prefers external. Let policy decide
9521                            } else {
9522                                // Prefer previous location
9523                                if (isExternal(pkg)) {
9524                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9525                                }
9526                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9527                            }
9528                        }
9529                    } else {
9530                        // Invalid install. Return error code
9531                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9532                    }
9533                }
9534            }
9535            // All the special cases have been taken care of.
9536            // Return result based on recommended install location.
9537            if (onSd) {
9538                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9539            }
9540            return pkgLite.recommendedInstallLocation;
9541        }
9542
9543        /*
9544         * Invoke remote method to get package information and install
9545         * location values. Override install location based on default
9546         * policy if needed and then create install arguments based
9547         * on the install location.
9548         */
9549        public void handleStartCopy() throws RemoteException {
9550            int ret = PackageManager.INSTALL_SUCCEEDED;
9551
9552            // If we're already staged, we've firmly committed to an install location
9553            if (origin.staged) {
9554                if (origin.file != null) {
9555                    installFlags |= PackageManager.INSTALL_INTERNAL;
9556                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9557                } else if (origin.cid != null) {
9558                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9559                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9560                } else {
9561                    throw new IllegalStateException("Invalid stage location");
9562                }
9563            }
9564
9565            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9566            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9567
9568            PackageInfoLite pkgLite = null;
9569
9570            if (onInt && onSd) {
9571                // Check if both bits are set.
9572                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9573                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9574            } else {
9575                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9576                        packageAbiOverride);
9577
9578                /*
9579                 * If we have too little free space, try to free cache
9580                 * before giving up.
9581                 */
9582                if (!origin.staged && pkgLite.recommendedInstallLocation
9583                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9584                    // TODO: focus freeing disk space on the target device
9585                    final StorageManager storage = StorageManager.from(mContext);
9586                    final long lowThreshold = storage.getStorageLowBytes(
9587                            Environment.getDataDirectory());
9588
9589                    final long sizeBytes = mContainerService.calculateInstalledSize(
9590                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9591
9592                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
9593                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9594                                installFlags, packageAbiOverride);
9595                    }
9596
9597                    /*
9598                     * The cache free must have deleted the file we
9599                     * downloaded to install.
9600                     *
9601                     * TODO: fix the "freeCache" call to not delete
9602                     *       the file we care about.
9603                     */
9604                    if (pkgLite.recommendedInstallLocation
9605                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9606                        pkgLite.recommendedInstallLocation
9607                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9608                    }
9609                }
9610            }
9611
9612            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9613                int loc = pkgLite.recommendedInstallLocation;
9614                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9615                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9616                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9617                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9618                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9619                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9620                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9621                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9622                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9623                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9624                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9625                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9626                } else {
9627                    // Override with defaults if needed.
9628                    loc = installLocationPolicy(pkgLite);
9629                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9630                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9631                    } else if (!onSd && !onInt) {
9632                        // Override install location with flags
9633                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9634                            // Set the flag to install on external media.
9635                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9636                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9637                        } else {
9638                            // Make sure the flag for installing on external
9639                            // media is unset
9640                            installFlags |= PackageManager.INSTALL_INTERNAL;
9641                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9642                        }
9643                    }
9644                }
9645            }
9646
9647            final InstallArgs args = createInstallArgs(this);
9648            mArgs = args;
9649
9650            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9651                 /*
9652                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9653                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9654                 */
9655                int userIdentifier = getUser().getIdentifier();
9656                if (userIdentifier == UserHandle.USER_ALL
9657                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9658                    userIdentifier = UserHandle.USER_OWNER;
9659                }
9660
9661                /*
9662                 * Determine if we have any installed package verifiers. If we
9663                 * do, then we'll defer to them to verify the packages.
9664                 */
9665                final int requiredUid = mRequiredVerifierPackage == null ? -1
9666                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9667                if (!origin.existing && requiredUid != -1
9668                        && isVerificationEnabled(userIdentifier, installFlags)) {
9669                    final Intent verification = new Intent(
9670                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9671                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9672                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9673                            PACKAGE_MIME_TYPE);
9674                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9675
9676                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9677                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9678                            0 /* TODO: Which userId? */);
9679
9680                    if (DEBUG_VERIFY) {
9681                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9682                                + verification.toString() + " with " + pkgLite.verifiers.length
9683                                + " optional verifiers");
9684                    }
9685
9686                    final int verificationId = mPendingVerificationToken++;
9687
9688                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9689
9690                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9691                            installerPackageName);
9692
9693                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9694                            installFlags);
9695
9696                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9697                            pkgLite.packageName);
9698
9699                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9700                            pkgLite.versionCode);
9701
9702                    if (verificationParams != null) {
9703                        if (verificationParams.getVerificationURI() != null) {
9704                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9705                                 verificationParams.getVerificationURI());
9706                        }
9707                        if (verificationParams.getOriginatingURI() != null) {
9708                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9709                                  verificationParams.getOriginatingURI());
9710                        }
9711                        if (verificationParams.getReferrer() != null) {
9712                            verification.putExtra(Intent.EXTRA_REFERRER,
9713                                  verificationParams.getReferrer());
9714                        }
9715                        if (verificationParams.getOriginatingUid() >= 0) {
9716                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9717                                  verificationParams.getOriginatingUid());
9718                        }
9719                        if (verificationParams.getInstallerUid() >= 0) {
9720                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9721                                  verificationParams.getInstallerUid());
9722                        }
9723                    }
9724
9725                    final PackageVerificationState verificationState = new PackageVerificationState(
9726                            requiredUid, args);
9727
9728                    mPendingVerification.append(verificationId, verificationState);
9729
9730                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9731                            receivers, verificationState);
9732
9733                    /*
9734                     * If any sufficient verifiers were listed in the package
9735                     * manifest, attempt to ask them.
9736                     */
9737                    if (sufficientVerifiers != null) {
9738                        final int N = sufficientVerifiers.size();
9739                        if (N == 0) {
9740                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9741                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9742                        } else {
9743                            for (int i = 0; i < N; i++) {
9744                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9745
9746                                final Intent sufficientIntent = new Intent(verification);
9747                                sufficientIntent.setComponent(verifierComponent);
9748
9749                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9750                            }
9751                        }
9752                    }
9753
9754                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9755                            mRequiredVerifierPackage, receivers);
9756                    if (ret == PackageManager.INSTALL_SUCCEEDED
9757                            && mRequiredVerifierPackage != null) {
9758                        /*
9759                         * Send the intent to the required verification agent,
9760                         * but only start the verification timeout after the
9761                         * target BroadcastReceivers have run.
9762                         */
9763                        verification.setComponent(requiredVerifierComponent);
9764                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9765                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9766                                new BroadcastReceiver() {
9767                                    @Override
9768                                    public void onReceive(Context context, Intent intent) {
9769                                        final Message msg = mHandler
9770                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9771                                        msg.arg1 = verificationId;
9772                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9773                                    }
9774                                }, null, 0, null, null);
9775
9776                        /*
9777                         * We don't want the copy to proceed until verification
9778                         * succeeds, so null out this field.
9779                         */
9780                        mArgs = null;
9781                    }
9782                } else {
9783                    /*
9784                     * No package verification is enabled, so immediately start
9785                     * the remote call to initiate copy using temporary file.
9786                     */
9787                    ret = args.copyApk(mContainerService, true);
9788                }
9789            }
9790
9791            mRet = ret;
9792        }
9793
9794        @Override
9795        void handleReturnCode() {
9796            // If mArgs is null, then MCS couldn't be reached. When it
9797            // reconnects, it will try again to install. At that point, this
9798            // will succeed.
9799            if (mArgs != null) {
9800                processPendingInstall(mArgs, mRet);
9801            }
9802        }
9803
9804        @Override
9805        void handleServiceError() {
9806            mArgs = createInstallArgs(this);
9807            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9808        }
9809
9810        public boolean isForwardLocked() {
9811            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9812        }
9813    }
9814
9815    /**
9816     * Used during creation of InstallArgs
9817     *
9818     * @param installFlags package installation flags
9819     * @return true if should be installed on external storage
9820     */
9821    private static boolean installOnExternalAsec(int installFlags) {
9822        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9823            return false;
9824        }
9825        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9826            return true;
9827        }
9828        return false;
9829    }
9830
9831    /**
9832     * Used during creation of InstallArgs
9833     *
9834     * @param installFlags package installation flags
9835     * @return true if should be installed as forward locked
9836     */
9837    private static boolean installForwardLocked(int installFlags) {
9838        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9839    }
9840
9841    private InstallArgs createInstallArgs(InstallParams params) {
9842        if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
9843            return new AsecInstallArgs(params);
9844        } else {
9845            return new FileInstallArgs(params);
9846        }
9847    }
9848
9849    /**
9850     * Create args that describe an existing installed package. Typically used
9851     * when cleaning up old installs, or used as a move source.
9852     */
9853    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9854            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9855        final boolean isInAsec;
9856        if (installOnExternalAsec(installFlags)) {
9857            /* Apps on SD card are always in ASEC containers. */
9858            isInAsec = true;
9859        } else if (installForwardLocked(installFlags)
9860                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9861            /*
9862             * Forward-locked apps are only in ASEC containers if they're the
9863             * new style
9864             */
9865            isInAsec = true;
9866        } else {
9867            isInAsec = false;
9868        }
9869
9870        if (isInAsec) {
9871            return new AsecInstallArgs(codePath, instructionSets,
9872                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
9873        } else {
9874            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9875                    instructionSets);
9876        }
9877    }
9878
9879    static abstract class InstallArgs {
9880        /** @see InstallParams#origin */
9881        final OriginInfo origin;
9882
9883        final IPackageInstallObserver2 observer;
9884        // Always refers to PackageManager flags only
9885        final int installFlags;
9886        final String installerPackageName;
9887        final String volumeUuid;
9888        final ManifestDigest manifestDigest;
9889        final UserHandle user;
9890        final String abiOverride;
9891
9892        // The list of instruction sets supported by this app. This is currently
9893        // only used during the rmdex() phase to clean up resources. We can get rid of this
9894        // if we move dex files under the common app path.
9895        /* nullable */ String[] instructionSets;
9896
9897        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9898                String installerPackageName, String volumeUuid, ManifestDigest manifestDigest,
9899                UserHandle user, String[] instructionSets, String abiOverride) {
9900            this.origin = origin;
9901            this.installFlags = installFlags;
9902            this.observer = observer;
9903            this.installerPackageName = installerPackageName;
9904            this.volumeUuid = volumeUuid;
9905            this.manifestDigest = manifestDigest;
9906            this.user = user;
9907            this.instructionSets = instructionSets;
9908            this.abiOverride = abiOverride;
9909        }
9910
9911        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9912        abstract int doPreInstall(int status);
9913
9914        /**
9915         * Rename package into final resting place. All paths on the given
9916         * scanned package should be updated to reflect the rename.
9917         */
9918        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9919        abstract int doPostInstall(int status, int uid);
9920
9921        /** @see PackageSettingBase#codePathString */
9922        abstract String getCodePath();
9923        /** @see PackageSettingBase#resourcePathString */
9924        abstract String getResourcePath();
9925        abstract String getLegacyNativeLibraryPath();
9926
9927        // Need installer lock especially for dex file removal.
9928        abstract void cleanUpResourcesLI();
9929        abstract boolean doPostDeleteLI(boolean delete);
9930        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9931
9932        /**
9933         * Called before the source arguments are copied. This is used mostly
9934         * for MoveParams when it needs to read the source file to put it in the
9935         * destination.
9936         */
9937        int doPreCopy() {
9938            return PackageManager.INSTALL_SUCCEEDED;
9939        }
9940
9941        /**
9942         * Called after the source arguments are copied. This is used mostly for
9943         * MoveParams when it needs to read the source file to put it in the
9944         * destination.
9945         *
9946         * @return
9947         */
9948        int doPostCopy(int uid) {
9949            return PackageManager.INSTALL_SUCCEEDED;
9950        }
9951
9952        protected boolean isFwdLocked() {
9953            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9954        }
9955
9956        protected boolean isExternalAsec() {
9957            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9958        }
9959
9960        UserHandle getUser() {
9961            return user;
9962        }
9963    }
9964
9965    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
9966        if (!allCodePaths.isEmpty()) {
9967            if (instructionSets == null) {
9968                throw new IllegalStateException("instructionSet == null");
9969            }
9970            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9971            for (String codePath : allCodePaths) {
9972                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9973                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9974                    if (retCode < 0) {
9975                        Slog.w(TAG, "Couldn't remove dex file for package: "
9976                                + " at location " + codePath + ", retcode=" + retCode);
9977                        // we don't consider this to be a failure of the core package deletion
9978                    }
9979                }
9980            }
9981        }
9982    }
9983
9984    /**
9985     * Logic to handle installation of non-ASEC applications, including copying
9986     * and renaming logic.
9987     */
9988    class FileInstallArgs extends InstallArgs {
9989        private File codeFile;
9990        private File resourceFile;
9991        private File legacyNativeLibraryPath;
9992
9993        // Example topology:
9994        // /data/app/com.example/base.apk
9995        // /data/app/com.example/split_foo.apk
9996        // /data/app/com.example/lib/arm/libfoo.so
9997        // /data/app/com.example/lib/arm64/libfoo.so
9998        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9999
10000        /** New install */
10001        FileInstallArgs(InstallParams params) {
10002            super(params.origin, params.observer, params.installFlags,
10003                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10004                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10005            if (isFwdLocked()) {
10006                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10007            }
10008        }
10009
10010        /** Existing install */
10011        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
10012                String[] instructionSets) {
10013            super(OriginInfo.fromNothing(), null, 0, null, null, null, null, instructionSets, null);
10014            this.codeFile = (codePath != null) ? new File(codePath) : null;
10015            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10016            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
10017                    new File(legacyNativeLibraryPath) : null;
10018        }
10019
10020        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
10021            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
10022                    isFwdLocked(), abiOverride);
10023
10024            final StorageManager storage = StorageManager.from(mContext);
10025            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
10026        }
10027
10028        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10029            if (origin.staged) {
10030                Slog.d(TAG, origin.file + " already staged; skipping copy");
10031                codeFile = origin.file;
10032                resourceFile = origin.file;
10033                return PackageManager.INSTALL_SUCCEEDED;
10034            }
10035
10036            try {
10037                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10038                codeFile = tempDir;
10039                resourceFile = tempDir;
10040            } catch (IOException e) {
10041                Slog.w(TAG, "Failed to create copy file: " + e);
10042                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10043            }
10044
10045            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10046                @Override
10047                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10048                    if (!FileUtils.isValidExtFilename(name)) {
10049                        throw new IllegalArgumentException("Invalid filename: " + name);
10050                    }
10051                    try {
10052                        final File file = new File(codeFile, name);
10053                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10054                                O_RDWR | O_CREAT, 0644);
10055                        Os.chmod(file.getAbsolutePath(), 0644);
10056                        return new ParcelFileDescriptor(fd);
10057                    } catch (ErrnoException e) {
10058                        throw new RemoteException("Failed to open: " + e.getMessage());
10059                    }
10060                }
10061            };
10062
10063            int ret = PackageManager.INSTALL_SUCCEEDED;
10064            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10065            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10066                Slog.e(TAG, "Failed to copy package");
10067                return ret;
10068            }
10069
10070            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10071            NativeLibraryHelper.Handle handle = null;
10072            try {
10073                handle = NativeLibraryHelper.Handle.create(codeFile);
10074                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10075                        abiOverride);
10076            } catch (IOException e) {
10077                Slog.e(TAG, "Copying native libraries failed", e);
10078                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10079            } finally {
10080                IoUtils.closeQuietly(handle);
10081            }
10082
10083            return ret;
10084        }
10085
10086        int doPreInstall(int status) {
10087            if (status != PackageManager.INSTALL_SUCCEEDED) {
10088                cleanUp();
10089            }
10090            return status;
10091        }
10092
10093        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10094            if (status != PackageManager.INSTALL_SUCCEEDED) {
10095                cleanUp();
10096                return false;
10097            } else {
10098                final File targetDir = codeFile.getParentFile();
10099                final File beforeCodeFile = codeFile;
10100                final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10101
10102                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10103                try {
10104                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10105                } catch (ErrnoException e) {
10106                    Slog.d(TAG, "Failed to rename", e);
10107                    return false;
10108                }
10109
10110                if (!SELinux.restoreconRecursive(afterCodeFile)) {
10111                    Slog.d(TAG, "Failed to restorecon");
10112                    return false;
10113                }
10114
10115                // Reflect the rename internally
10116                codeFile = afterCodeFile;
10117                resourceFile = afterCodeFile;
10118
10119                // Reflect the rename in scanned details
10120                pkg.codePath = afterCodeFile.getAbsolutePath();
10121                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10122                        pkg.baseCodePath);
10123                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10124                        pkg.splitCodePaths);
10125
10126                // Reflect the rename in app info
10127                pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10128                pkg.applicationInfo.setCodePath(pkg.codePath);
10129                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10130                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10131                pkg.applicationInfo.setResourcePath(pkg.codePath);
10132                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10133                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10134
10135                return true;
10136            }
10137        }
10138
10139        int doPostInstall(int status, int uid) {
10140            if (status != PackageManager.INSTALL_SUCCEEDED) {
10141                cleanUp();
10142            }
10143            return status;
10144        }
10145
10146        @Override
10147        String getCodePath() {
10148            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10149        }
10150
10151        @Override
10152        String getResourcePath() {
10153            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10154        }
10155
10156        @Override
10157        String getLegacyNativeLibraryPath() {
10158            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
10159        }
10160
10161        private boolean cleanUp() {
10162            if (codeFile == null || !codeFile.exists()) {
10163                return false;
10164            }
10165
10166            if (codeFile.isDirectory()) {
10167                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10168            } else {
10169                codeFile.delete();
10170            }
10171
10172            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10173                resourceFile.delete();
10174            }
10175
10176            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
10177                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
10178                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
10179                }
10180                legacyNativeLibraryPath.delete();
10181            }
10182
10183            return true;
10184        }
10185
10186        void cleanUpResourcesLI() {
10187            // Try enumerating all code paths before deleting
10188            List<String> allCodePaths = Collections.EMPTY_LIST;
10189            if (codeFile != null && codeFile.exists()) {
10190                try {
10191                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10192                    allCodePaths = pkg.getAllCodePaths();
10193                } catch (PackageParserException e) {
10194                    // Ignored; we tried our best
10195                }
10196            }
10197
10198            cleanUp();
10199            removeDexFiles(allCodePaths, instructionSets);
10200        }
10201
10202        boolean doPostDeleteLI(boolean delete) {
10203            // XXX err, shouldn't we respect the delete flag?
10204            cleanUpResourcesLI();
10205            return true;
10206        }
10207    }
10208
10209    private boolean isAsecExternal(String cid) {
10210        final String asecPath = PackageHelper.getSdFilesystem(cid);
10211        return !asecPath.startsWith(mAsecInternalPath);
10212    }
10213
10214    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10215            PackageManagerException {
10216        if (copyRet < 0) {
10217            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10218                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10219                throw new PackageManagerException(copyRet, message);
10220            }
10221        }
10222    }
10223
10224    /**
10225     * Extract the MountService "container ID" from the full code path of an
10226     * .apk.
10227     */
10228    static String cidFromCodePath(String fullCodePath) {
10229        int eidx = fullCodePath.lastIndexOf("/");
10230        String subStr1 = fullCodePath.substring(0, eidx);
10231        int sidx = subStr1.lastIndexOf("/");
10232        return subStr1.substring(sidx+1, eidx);
10233    }
10234
10235    /**
10236     * Logic to handle installation of ASEC applications, including copying and
10237     * renaming logic.
10238     */
10239    class AsecInstallArgs extends InstallArgs {
10240        static final String RES_FILE_NAME = "pkg.apk";
10241        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10242
10243        String cid;
10244        String packagePath;
10245        String resourcePath;
10246        String legacyNativeLibraryDir;
10247
10248        /** New install */
10249        AsecInstallArgs(InstallParams params) {
10250            super(params.origin, params.observer, params.installFlags,
10251                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10252                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10253        }
10254
10255        /** Existing install */
10256        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10257                        boolean isExternal, boolean isForwardLocked) {
10258            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
10259                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10260                    instructionSets, null);
10261            // Hackily pretend we're still looking at a full code path
10262            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10263                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10264            }
10265
10266            // Extract cid from fullCodePath
10267            int eidx = fullCodePath.lastIndexOf("/");
10268            String subStr1 = fullCodePath.substring(0, eidx);
10269            int sidx = subStr1.lastIndexOf("/");
10270            cid = subStr1.substring(sidx+1, eidx);
10271            setMountPath(subStr1);
10272        }
10273
10274        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10275            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10276                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10277                    instructionSets, null);
10278            this.cid = cid;
10279            setMountPath(PackageHelper.getSdDir(cid));
10280        }
10281
10282        void createCopyFile() {
10283            cid = mInstallerService.allocateExternalStageCidLegacy();
10284        }
10285
10286        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
10287            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
10288                    abiOverride);
10289
10290            final File target;
10291            if (isExternalAsec()) {
10292                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
10293            } else {
10294                target = Environment.getDataDirectory();
10295            }
10296
10297            final StorageManager storage = StorageManager.from(mContext);
10298            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
10299        }
10300
10301        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10302            if (origin.staged) {
10303                Slog.d(TAG, origin.cid + " already staged; skipping copy");
10304                cid = origin.cid;
10305                setMountPath(PackageHelper.getSdDir(cid));
10306                return PackageManager.INSTALL_SUCCEEDED;
10307            }
10308
10309            if (temp) {
10310                createCopyFile();
10311            } else {
10312                /*
10313                 * Pre-emptively destroy the container since it's destroyed if
10314                 * copying fails due to it existing anyway.
10315                 */
10316                PackageHelper.destroySdDir(cid);
10317            }
10318
10319            final String newMountPath = imcs.copyPackageToContainer(
10320                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10321                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10322
10323            if (newMountPath != null) {
10324                setMountPath(newMountPath);
10325                return PackageManager.INSTALL_SUCCEEDED;
10326            } else {
10327                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10328            }
10329        }
10330
10331        @Override
10332        String getCodePath() {
10333            return packagePath;
10334        }
10335
10336        @Override
10337        String getResourcePath() {
10338            return resourcePath;
10339        }
10340
10341        @Override
10342        String getLegacyNativeLibraryPath() {
10343            return legacyNativeLibraryDir;
10344        }
10345
10346        int doPreInstall(int status) {
10347            if (status != PackageManager.INSTALL_SUCCEEDED) {
10348                // Destroy container
10349                PackageHelper.destroySdDir(cid);
10350            } else {
10351                boolean mounted = PackageHelper.isContainerMounted(cid);
10352                if (!mounted) {
10353                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10354                            Process.SYSTEM_UID);
10355                    if (newMountPath != null) {
10356                        setMountPath(newMountPath);
10357                    } else {
10358                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10359                    }
10360                }
10361            }
10362            return status;
10363        }
10364
10365        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10366            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10367            String newMountPath = null;
10368            if (PackageHelper.isContainerMounted(cid)) {
10369                // Unmount the container
10370                if (!PackageHelper.unMountSdDir(cid)) {
10371                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10372                    return false;
10373                }
10374            }
10375            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10376                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10377                        " which might be stale. Will try to clean up.");
10378                // Clean up the stale container and proceed to recreate.
10379                if (!PackageHelper.destroySdDir(newCacheId)) {
10380                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10381                    return false;
10382                }
10383                // Successfully cleaned up stale container. Try to rename again.
10384                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10385                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10386                            + " inspite of cleaning it up.");
10387                    return false;
10388                }
10389            }
10390            if (!PackageHelper.isContainerMounted(newCacheId)) {
10391                Slog.w(TAG, "Mounting container " + newCacheId);
10392                newMountPath = PackageHelper.mountSdDir(newCacheId,
10393                        getEncryptKey(), Process.SYSTEM_UID);
10394            } else {
10395                newMountPath = PackageHelper.getSdDir(newCacheId);
10396            }
10397            if (newMountPath == null) {
10398                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10399                return false;
10400            }
10401            Log.i(TAG, "Succesfully renamed " + cid +
10402                    " to " + newCacheId +
10403                    " at new path: " + newMountPath);
10404            cid = newCacheId;
10405
10406            final File beforeCodeFile = new File(packagePath);
10407            setMountPath(newMountPath);
10408            final File afterCodeFile = new File(packagePath);
10409
10410            // Reflect the rename in scanned details
10411            pkg.codePath = afterCodeFile.getAbsolutePath();
10412            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10413                    pkg.baseCodePath);
10414            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10415                    pkg.splitCodePaths);
10416
10417            // Reflect the rename in app info
10418            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10419            pkg.applicationInfo.setCodePath(pkg.codePath);
10420            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10421            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10422            pkg.applicationInfo.setResourcePath(pkg.codePath);
10423            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10424            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10425
10426            return true;
10427        }
10428
10429        private void setMountPath(String mountPath) {
10430            final File mountFile = new File(mountPath);
10431
10432            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10433            if (monolithicFile.exists()) {
10434                packagePath = monolithicFile.getAbsolutePath();
10435                if (isFwdLocked()) {
10436                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10437                } else {
10438                    resourcePath = packagePath;
10439                }
10440            } else {
10441                packagePath = mountFile.getAbsolutePath();
10442                resourcePath = packagePath;
10443            }
10444
10445            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
10446        }
10447
10448        int doPostInstall(int status, int uid) {
10449            if (status != PackageManager.INSTALL_SUCCEEDED) {
10450                cleanUp();
10451            } else {
10452                final int groupOwner;
10453                final String protectedFile;
10454                if (isFwdLocked()) {
10455                    groupOwner = UserHandle.getSharedAppGid(uid);
10456                    protectedFile = RES_FILE_NAME;
10457                } else {
10458                    groupOwner = -1;
10459                    protectedFile = null;
10460                }
10461
10462                if (uid < Process.FIRST_APPLICATION_UID
10463                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10464                    Slog.e(TAG, "Failed to finalize " + cid);
10465                    PackageHelper.destroySdDir(cid);
10466                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10467                }
10468
10469                boolean mounted = PackageHelper.isContainerMounted(cid);
10470                if (!mounted) {
10471                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10472                }
10473            }
10474            return status;
10475        }
10476
10477        private void cleanUp() {
10478            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10479
10480            // Destroy secure container
10481            PackageHelper.destroySdDir(cid);
10482        }
10483
10484        private List<String> getAllCodePaths() {
10485            final File codeFile = new File(getCodePath());
10486            if (codeFile != null && codeFile.exists()) {
10487                try {
10488                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10489                    return pkg.getAllCodePaths();
10490                } catch (PackageParserException e) {
10491                    // Ignored; we tried our best
10492                }
10493            }
10494            return Collections.EMPTY_LIST;
10495        }
10496
10497        void cleanUpResourcesLI() {
10498            // Enumerate all code paths before deleting
10499            cleanUpResourcesLI(getAllCodePaths());
10500        }
10501
10502        private void cleanUpResourcesLI(List<String> allCodePaths) {
10503            cleanUp();
10504            removeDexFiles(allCodePaths, instructionSets);
10505        }
10506
10507
10508
10509        String getPackageName() {
10510            return getAsecPackageName(cid);
10511        }
10512
10513        boolean doPostDeleteLI(boolean delete) {
10514            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10515            final List<String> allCodePaths = getAllCodePaths();
10516            boolean mounted = PackageHelper.isContainerMounted(cid);
10517            if (mounted) {
10518                // Unmount first
10519                if (PackageHelper.unMountSdDir(cid)) {
10520                    mounted = false;
10521                }
10522            }
10523            if (!mounted && delete) {
10524                cleanUpResourcesLI(allCodePaths);
10525            }
10526            return !mounted;
10527        }
10528
10529        @Override
10530        int doPreCopy() {
10531            if (isFwdLocked()) {
10532                if (!PackageHelper.fixSdPermissions(cid,
10533                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10534                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10535                }
10536            }
10537
10538            return PackageManager.INSTALL_SUCCEEDED;
10539        }
10540
10541        @Override
10542        int doPostCopy(int uid) {
10543            if (isFwdLocked()) {
10544                if (uid < Process.FIRST_APPLICATION_UID
10545                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10546                                RES_FILE_NAME)) {
10547                    Slog.e(TAG, "Failed to finalize " + cid);
10548                    PackageHelper.destroySdDir(cid);
10549                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10550                }
10551            }
10552
10553            return PackageManager.INSTALL_SUCCEEDED;
10554        }
10555    }
10556
10557    static String getAsecPackageName(String packageCid) {
10558        int idx = packageCid.lastIndexOf("-");
10559        if (idx == -1) {
10560            return packageCid;
10561        }
10562        return packageCid.substring(0, idx);
10563    }
10564
10565    // Utility method used to create code paths based on package name and available index.
10566    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
10567        String idxStr = "";
10568        int idx = 1;
10569        // Fall back to default value of idx=1 if prefix is not
10570        // part of oldCodePath
10571        if (oldCodePath != null) {
10572            String subStr = oldCodePath;
10573            // Drop the suffix right away
10574            if (suffix != null && subStr.endsWith(suffix)) {
10575                subStr = subStr.substring(0, subStr.length() - suffix.length());
10576            }
10577            // If oldCodePath already contains prefix find out the
10578            // ending index to either increment or decrement.
10579            int sidx = subStr.lastIndexOf(prefix);
10580            if (sidx != -1) {
10581                subStr = subStr.substring(sidx + prefix.length());
10582                if (subStr != null) {
10583                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10584                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10585                    }
10586                    try {
10587                        idx = Integer.parseInt(subStr);
10588                        if (idx <= 1) {
10589                            idx++;
10590                        } else {
10591                            idx--;
10592                        }
10593                    } catch(NumberFormatException e) {
10594                    }
10595                }
10596            }
10597        }
10598        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10599        return prefix + idxStr;
10600    }
10601
10602    private File getNextCodePath(File targetDir, String packageName) {
10603        int suffix = 1;
10604        File result;
10605        do {
10606            result = new File(targetDir, packageName + "-" + suffix);
10607            suffix++;
10608        } while (result.exists());
10609        return result;
10610    }
10611
10612    // Utility method that returns the relative package path with respect
10613    // to the installation directory. Like say for /data/data/com.test-1.apk
10614    // string com.test-1 is returned.
10615    static String deriveCodePathName(String codePath) {
10616        if (codePath == null) {
10617            return null;
10618        }
10619        final File codeFile = new File(codePath);
10620        final String name = codeFile.getName();
10621        if (codeFile.isDirectory()) {
10622            return name;
10623        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10624            final int lastDot = name.lastIndexOf('.');
10625            return name.substring(0, lastDot);
10626        } else {
10627            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10628            return null;
10629        }
10630    }
10631
10632    class PackageInstalledInfo {
10633        String name;
10634        int uid;
10635        // The set of users that originally had this package installed.
10636        int[] origUsers;
10637        // The set of users that now have this package installed.
10638        int[] newUsers;
10639        PackageParser.Package pkg;
10640        int returnCode;
10641        String returnMsg;
10642        PackageRemovedInfo removedInfo;
10643
10644        public void setError(int code, String msg) {
10645            returnCode = code;
10646            returnMsg = msg;
10647            Slog.w(TAG, msg);
10648        }
10649
10650        public void setError(String msg, PackageParserException e) {
10651            returnCode = e.error;
10652            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10653            Slog.w(TAG, msg, e);
10654        }
10655
10656        public void setError(String msg, PackageManagerException e) {
10657            returnCode = e.error;
10658            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10659            Slog.w(TAG, msg, e);
10660        }
10661
10662        // In some error cases we want to convey more info back to the observer
10663        String origPackage;
10664        String origPermission;
10665    }
10666
10667    /*
10668     * Install a non-existing package.
10669     */
10670    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
10671            UserHandle user, String installerPackageName, String volumeUuid,
10672            PackageInstalledInfo res) {
10673        // Remember this for later, in case we need to rollback this install
10674        String pkgName = pkg.packageName;
10675
10676        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10677        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
10678                UserHandle.USER_OWNER).exists();
10679        synchronized(mPackages) {
10680            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10681                // A package with the same name is already installed, though
10682                // it has been renamed to an older name.  The package we
10683                // are trying to install should be installed as an update to
10684                // the existing one, but that has not been requested, so bail.
10685                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10686                        + " without first uninstalling package running as "
10687                        + mSettings.mRenamedPackages.get(pkgName));
10688                return;
10689            }
10690            if (mPackages.containsKey(pkgName)) {
10691                // Don't allow installation over an existing package with the same name.
10692                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10693                        + " without first uninstalling.");
10694                return;
10695            }
10696        }
10697
10698        try {
10699            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10700                    System.currentTimeMillis(), user);
10701
10702            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
10703            // delete the partially installed application. the data directory will have to be
10704            // restored if it was already existing
10705            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10706                // remove package from internal structures.  Note that we want deletePackageX to
10707                // delete the package data and cache directories that it created in
10708                // scanPackageLocked, unless those directories existed before we even tried to
10709                // install.
10710                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10711                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10712                                res.removedInfo, true);
10713            }
10714
10715        } catch (PackageManagerException e) {
10716            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10717        }
10718    }
10719
10720    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10721        // Upgrade keysets are being used.  Determine if new package has a superset of the
10722        // required keys.
10723        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10724        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10725        for (int i = 0; i < upgradeKeySets.length; i++) {
10726            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10727            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10728                return true;
10729            }
10730        }
10731        return false;
10732    }
10733
10734    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
10735            UserHandle user, String installerPackageName, String volumeUuid,
10736            PackageInstalledInfo res) {
10737        PackageParser.Package oldPackage;
10738        String pkgName = pkg.packageName;
10739        int[] allUsers;
10740        boolean[] perUserInstalled;
10741
10742        // First find the old package info and check signatures
10743        synchronized(mPackages) {
10744            oldPackage = mPackages.get(pkgName);
10745            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10746            PackageSetting ps = mSettings.mPackages.get(pkgName);
10747            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10748                // default to original signature matching
10749                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10750                    != PackageManager.SIGNATURE_MATCH) {
10751                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10752                            "New package has a different signature: " + pkgName);
10753                    return;
10754                }
10755            } else {
10756                if(!checkUpgradeKeySetLP(ps, pkg)) {
10757                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10758                            "New package not signed by keys specified by upgrade-keysets: "
10759                            + pkgName);
10760                    return;
10761                }
10762            }
10763
10764            // In case of rollback, remember per-user/profile install state
10765            allUsers = sUserManager.getUserIds();
10766            perUserInstalled = new boolean[allUsers.length];
10767            for (int i = 0; i < allUsers.length; i++) {
10768                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10769            }
10770        }
10771
10772        boolean sysPkg = (isSystemApp(oldPackage));
10773        if (sysPkg) {
10774            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10775                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
10776        } else {
10777            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10778                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
10779        }
10780    }
10781
10782    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10783            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10784            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
10785            String volumeUuid, PackageInstalledInfo res) {
10786        String pkgName = deletedPackage.packageName;
10787        boolean deletedPkg = true;
10788        boolean updatedSettings = false;
10789
10790        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10791                + deletedPackage);
10792        long origUpdateTime;
10793        if (pkg.mExtras != null) {
10794            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10795        } else {
10796            origUpdateTime = 0;
10797        }
10798
10799        // First delete the existing package while retaining the data directory
10800        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10801                res.removedInfo, true)) {
10802            // If the existing package wasn't successfully deleted
10803            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10804            deletedPkg = false;
10805        } else {
10806            // Successfully deleted the old package; proceed with replace.
10807
10808            // If deleted package lived in a container, give users a chance to
10809            // relinquish resources before killing.
10810            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
10811                if (DEBUG_INSTALL) {
10812                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10813                }
10814                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10815                final ArrayList<String> pkgList = new ArrayList<String>(1);
10816                pkgList.add(deletedPackage.applicationInfo.packageName);
10817                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10818            }
10819
10820            deleteCodeCacheDirsLI(pkgName);
10821            try {
10822                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10823                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10824                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
10825                        perUserInstalled, res, user);
10826                updatedSettings = true;
10827            } catch (PackageManagerException e) {
10828                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10829            }
10830        }
10831
10832        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10833            // remove package from internal structures.  Note that we want deletePackageX to
10834            // delete the package data and cache directories that it created in
10835            // scanPackageLocked, unless those directories existed before we even tried to
10836            // install.
10837            if(updatedSettings) {
10838                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10839                deletePackageLI(
10840                        pkgName, null, true, allUsers, perUserInstalled,
10841                        PackageManager.DELETE_KEEP_DATA,
10842                                res.removedInfo, true);
10843            }
10844            // Since we failed to install the new package we need to restore the old
10845            // package that we deleted.
10846            if (deletedPkg) {
10847                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10848                File restoreFile = new File(deletedPackage.codePath);
10849                // Parse old package
10850                boolean oldExternal = isExternal(deletedPackage);
10851                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10852                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10853                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
10854                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10855                try {
10856                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10857                } catch (PackageManagerException e) {
10858                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10859                            + e.getMessage());
10860                    return;
10861                }
10862                // Restore of old package succeeded. Update permissions.
10863                // writer
10864                synchronized (mPackages) {
10865                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10866                            UPDATE_PERMISSIONS_ALL);
10867                    // can downgrade to reader
10868                    mSettings.writeLPr();
10869                }
10870                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10871            }
10872        }
10873    }
10874
10875    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10876            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10877            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
10878            String volumeUuid, PackageInstalledInfo res) {
10879        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10880                + ", old=" + deletedPackage);
10881        boolean disabledSystem = false;
10882        boolean updatedSettings = false;
10883        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10884        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
10885                != 0) {
10886            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10887        }
10888        String packageName = deletedPackage.packageName;
10889        if (packageName == null) {
10890            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10891                    "Attempt to delete null packageName.");
10892            return;
10893        }
10894        PackageParser.Package oldPkg;
10895        PackageSetting oldPkgSetting;
10896        // reader
10897        synchronized (mPackages) {
10898            oldPkg = mPackages.get(packageName);
10899            oldPkgSetting = mSettings.mPackages.get(packageName);
10900            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10901                    (oldPkgSetting == null)) {
10902                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10903                        "Couldn't find package:" + packageName + " information");
10904                return;
10905            }
10906        }
10907
10908        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10909
10910        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10911        res.removedInfo.removedPackage = packageName;
10912        // Remove existing system package
10913        removePackageLI(oldPkgSetting, true);
10914        // writer
10915        synchronized (mPackages) {
10916            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10917            if (!disabledSystem && deletedPackage != null) {
10918                // We didn't need to disable the .apk as a current system package,
10919                // which means we are replacing another update that is already
10920                // installed.  We need to make sure to delete the older one's .apk.
10921                res.removedInfo.args = createInstallArgsForExisting(0,
10922                        deletedPackage.applicationInfo.getCodePath(),
10923                        deletedPackage.applicationInfo.getResourcePath(),
10924                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10925                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10926            } else {
10927                res.removedInfo.args = null;
10928            }
10929        }
10930
10931        // Successfully disabled the old package. Now proceed with re-installation
10932        deleteCodeCacheDirsLI(packageName);
10933
10934        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10935        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10936
10937        PackageParser.Package newPackage = null;
10938        try {
10939            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10940            if (newPackage.mExtras != null) {
10941                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10942                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10943                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10944
10945                // is the update attempting to change shared user? that isn't going to work...
10946                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10947                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10948                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10949                            + " to " + newPkgSetting.sharedUser);
10950                    updatedSettings = true;
10951                }
10952            }
10953
10954            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10955                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
10956                        perUserInstalled, res, user);
10957                updatedSettings = true;
10958            }
10959
10960        } catch (PackageManagerException e) {
10961            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10962        }
10963
10964        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10965            // Re installation failed. Restore old information
10966            // Remove new pkg information
10967            if (newPackage != null) {
10968                removeInstalledPackageLI(newPackage, true);
10969            }
10970            // Add back the old system package
10971            try {
10972                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10973            } catch (PackageManagerException e) {
10974                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10975            }
10976            // Restore the old system information in Settings
10977            synchronized (mPackages) {
10978                if (disabledSystem) {
10979                    mSettings.enableSystemPackageLPw(packageName);
10980                }
10981                if (updatedSettings) {
10982                    mSettings.setInstallerPackageName(packageName,
10983                            oldPkgSetting.installerPackageName);
10984                }
10985                mSettings.writeLPr();
10986            }
10987        }
10988    }
10989
10990    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10991            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
10992            UserHandle user) {
10993        String pkgName = newPackage.packageName;
10994        synchronized (mPackages) {
10995            //write settings. the installStatus will be incomplete at this stage.
10996            //note that the new package setting would have already been
10997            //added to mPackages. It hasn't been persisted yet.
10998            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10999            mSettings.writeLPr();
11000        }
11001
11002        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11003
11004        synchronized (mPackages) {
11005            updatePermissionsLPw(newPackage.packageName, newPackage,
11006                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11007                            ? UPDATE_PERMISSIONS_ALL : 0));
11008            // For system-bundled packages, we assume that installing an upgraded version
11009            // of the package implies that the user actually wants to run that new code,
11010            // so we enable the package.
11011            PackageSetting ps = mSettings.mPackages.get(pkgName);
11012            if (ps != null) {
11013                if (isSystemApp(newPackage)) {
11014                    // NB: implicit assumption that system package upgrades apply to all users
11015                    if (DEBUG_INSTALL) {
11016                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11017                    }
11018                    if (res.origUsers != null) {
11019                        for (int userHandle : res.origUsers) {
11020                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11021                                    userHandle, installerPackageName);
11022                        }
11023                    }
11024                    // Also convey the prior install/uninstall state
11025                    if (allUsers != null && perUserInstalled != null) {
11026                        for (int i = 0; i < allUsers.length; i++) {
11027                            if (DEBUG_INSTALL) {
11028                                Slog.d(TAG, "    user " + allUsers[i]
11029                                        + " => " + perUserInstalled[i]);
11030                            }
11031                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11032                        }
11033                        // these install state changes will be persisted in the
11034                        // upcoming call to mSettings.writeLPr().
11035                    }
11036                }
11037                // It's implied that when a user requests installation, they want the app to be
11038                // installed and enabled.
11039                int userId = user.getIdentifier();
11040                if (userId != UserHandle.USER_ALL) {
11041                    ps.setInstalled(true, userId);
11042                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11043                }
11044            }
11045            res.name = pkgName;
11046            res.uid = newPackage.applicationInfo.uid;
11047            res.pkg = newPackage;
11048            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11049            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11050            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11051            //to update install status
11052            mSettings.writeLPr();
11053        }
11054    }
11055
11056    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11057        final int installFlags = args.installFlags;
11058        final String installerPackageName = args.installerPackageName;
11059        final String volumeUuid = args.volumeUuid;
11060        final File tmpPackageFile = new File(args.getCodePath());
11061        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11062        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11063                || (args.volumeUuid != null));
11064        boolean replace = false;
11065        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
11066        // Result object to be returned
11067        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11068
11069        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11070        // Retrieve PackageSettings and parse package
11071        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11072                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11073                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11074        PackageParser pp = new PackageParser();
11075        pp.setSeparateProcesses(mSeparateProcesses);
11076        pp.setDisplayMetrics(mMetrics);
11077
11078        final PackageParser.Package pkg;
11079        try {
11080            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11081        } catch (PackageParserException e) {
11082            res.setError("Failed parse during installPackageLI", e);
11083            return;
11084        }
11085
11086        // Mark that we have an install time CPU ABI override.
11087        pkg.cpuAbiOverride = args.abiOverride;
11088
11089        String pkgName = res.name = pkg.packageName;
11090        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11091            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11092                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11093                return;
11094            }
11095        }
11096
11097        try {
11098            pp.collectCertificates(pkg, parseFlags);
11099            pp.collectManifestDigest(pkg);
11100        } catch (PackageParserException e) {
11101            res.setError("Failed collect during installPackageLI", e);
11102            return;
11103        }
11104
11105        /* If the installer passed in a manifest digest, compare it now. */
11106        if (args.manifestDigest != null) {
11107            if (DEBUG_INSTALL) {
11108                final String parsedManifest = pkg.manifestDigest == null ? "null"
11109                        : pkg.manifestDigest.toString();
11110                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11111                        + parsedManifest);
11112            }
11113
11114            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11115                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11116                return;
11117            }
11118        } else if (DEBUG_INSTALL) {
11119            final String parsedManifest = pkg.manifestDigest == null
11120                    ? "null" : pkg.manifestDigest.toString();
11121            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11122        }
11123
11124        // Get rid of all references to package scan path via parser.
11125        pp = null;
11126        String oldCodePath = null;
11127        boolean systemApp = false;
11128        synchronized (mPackages) {
11129            // Check if installing already existing package
11130            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11131                String oldName = mSettings.mRenamedPackages.get(pkgName);
11132                if (pkg.mOriginalPackages != null
11133                        && pkg.mOriginalPackages.contains(oldName)
11134                        && mPackages.containsKey(oldName)) {
11135                    // This package is derived from an original package,
11136                    // and this device has been updating from that original
11137                    // name.  We must continue using the original name, so
11138                    // rename the new package here.
11139                    pkg.setPackageName(oldName);
11140                    pkgName = pkg.packageName;
11141                    replace = true;
11142                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11143                            + oldName + " pkgName=" + pkgName);
11144                } else if (mPackages.containsKey(pkgName)) {
11145                    // This package, under its official name, already exists
11146                    // on the device; we should replace it.
11147                    replace = true;
11148                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11149                }
11150            }
11151
11152            PackageSetting ps = mSettings.mPackages.get(pkgName);
11153            if (ps != null) {
11154                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11155
11156                // Quick sanity check that we're signed correctly if updating;
11157                // we'll check this again later when scanning, but we want to
11158                // bail early here before tripping over redefined permissions.
11159                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11160                    try {
11161                        verifySignaturesLP(ps, pkg);
11162                    } catch (PackageManagerException e) {
11163                        res.setError(e.error, e.getMessage());
11164                        return;
11165                    }
11166                } else {
11167                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11168                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11169                                + pkg.packageName + " upgrade keys do not match the "
11170                                + "previously installed version");
11171                        return;
11172                    }
11173                }
11174
11175                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11176                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11177                    systemApp = (ps.pkg.applicationInfo.flags &
11178                            ApplicationInfo.FLAG_SYSTEM) != 0;
11179                }
11180                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11181            }
11182
11183            // Check whether the newly-scanned package wants to define an already-defined perm
11184            int N = pkg.permissions.size();
11185            for (int i = N-1; i >= 0; i--) {
11186                PackageParser.Permission perm = pkg.permissions.get(i);
11187                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11188                if (bp != null) {
11189                    // If the defining package is signed with our cert, it's okay.  This
11190                    // also includes the "updating the same package" case, of course.
11191                    // "updating same package" could also involve key-rotation.
11192                    final boolean sigsOk;
11193                    if (!bp.sourcePackage.equals(pkg.packageName)
11194                            || !(bp.packageSetting instanceof PackageSetting)
11195                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
11196                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
11197                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11198                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11199                    } else {
11200                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11201                    }
11202                    if (!sigsOk) {
11203                        // If the owning package is the system itself, we log but allow
11204                        // install to proceed; we fail the install on all other permission
11205                        // redefinitions.
11206                        if (!bp.sourcePackage.equals("android")) {
11207                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11208                                    + pkg.packageName + " attempting to redeclare permission "
11209                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11210                            res.origPermission = perm.info.name;
11211                            res.origPackage = bp.sourcePackage;
11212                            return;
11213                        } else {
11214                            Slog.w(TAG, "Package " + pkg.packageName
11215                                    + " attempting to redeclare system permission "
11216                                    + perm.info.name + "; ignoring new declaration");
11217                            pkg.permissions.remove(i);
11218                        }
11219                    }
11220                }
11221            }
11222
11223        }
11224
11225        if (systemApp && onExternal) {
11226            // Disable updates to system apps on sdcard
11227            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11228                    "Cannot install updates to system apps on sdcard");
11229            return;
11230        }
11231
11232        // Run dexopt before old package gets removed, to minimize time when app is not available
11233        int result = mPackageDexOptimizer
11234                .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */,
11235                        false /* defer */, false /* inclDependencies */);
11236        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11237            res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11238            return;
11239        }
11240
11241        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11242            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11243            return;
11244        }
11245
11246        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11247
11248        // Call with SCAN_NO_DEX, since dexopt has already been made
11249        if (replace) {
11250            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING | SCAN_NO_DEX, args.user,
11251                    installerPackageName, volumeUuid, res);
11252        } else {
11253            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES
11254                    | SCAN_NO_DEX, args.user, installerPackageName, volumeUuid, res);
11255        }
11256        synchronized (mPackages) {
11257            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11258            if (ps != null) {
11259                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11260            }
11261        }
11262    }
11263
11264    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11265        if (mIntentFilterVerifierComponent == null) {
11266            Slog.d(TAG, "No IntentFilter verification will not be done as "
11267                    + "there is no IntentFilterVerifier available!");
11268            return;
11269        }
11270
11271        final int verifierUid = getPackageUid(
11272                mIntentFilterVerifierComponent.getPackageName(),
11273                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11274
11275        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11276        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11277        msg.obj = pkg;
11278        msg.arg1 = userId;
11279        msg.arg2 = verifierUid;
11280
11281        mHandler.sendMessage(msg);
11282    }
11283
11284    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11285            PackageParser.Package pkg) {
11286        int size = pkg.activities.size();
11287        if (size == 0) {
11288            Slog.d(TAG, "No activity, so no need to verify any IntentFilter!");
11289            return;
11290        }
11291
11292        final boolean hasDomainURLs = hasDomainURLs(pkg);
11293        if (!hasDomainURLs) {
11294            Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!");
11295            return;
11296        }
11297
11298        Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size
11299                + " Activities needs verification ...");
11300
11301        final int verificationId = mIntentFilterVerificationToken++;
11302        int count = 0;
11303        final String packageName = pkg.packageName;
11304        ArrayList<String> allHosts = new ArrayList<>();
11305
11306        synchronized (mPackages) {
11307            for (PackageParser.Activity a : pkg.activities) {
11308                for (ActivityIntentInfo filter : a.intents) {
11309                    boolean needsFilterVerification = filter.needsVerification();
11310                    if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11311                        Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString());
11312                        mIntentFilterVerifier.addOneIntentFilterVerification(
11313                                verifierUid, userId, verificationId, filter, packageName);
11314                        count++;
11315                    } else if (!needsFilterVerification) {
11316                        Slog.d(TAG, "No verification needed for IntentFilter:"
11317                                + filter.toString());
11318                        if (hasValidDomains(filter)) {
11319                            allHosts.addAll(filter.getHostsList());
11320                        }
11321                    } else {
11322                        Slog.d(TAG, "Verification already done for IntentFilter:"
11323                                + filter.toString());
11324                    }
11325                }
11326            }
11327        }
11328
11329        if (count > 0) {
11330            mIntentFilterVerifier.startVerifications(userId);
11331            Slog.d(TAG, "Started " + count + " IntentFilter verification"
11332                    + (count > 1 ? "s" : "") +  " for userId:" + userId + "!");
11333        } else {
11334            Slog.d(TAG, "No need to start any IntentFilter verification!");
11335            if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw(
11336                    packageName, allHosts) != null) {
11337                scheduleWriteSettingsLocked();
11338            }
11339        }
11340    }
11341
11342    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11343        final ComponentName cn  = filter.activity.getComponentName();
11344        final String packageName = cn.getPackageName();
11345
11346        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11347                packageName);
11348        if (ivi == null) {
11349            return true;
11350        }
11351        int status = ivi.getStatus();
11352        switch (status) {
11353            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11354            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11355                return true;
11356
11357            default:
11358                // Nothing to do
11359                return false;
11360        }
11361    }
11362
11363    private static boolean isMultiArch(PackageSetting ps) {
11364        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11365    }
11366
11367    private static boolean isMultiArch(ApplicationInfo info) {
11368        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11369    }
11370
11371    private static boolean isExternal(PackageParser.Package pkg) {
11372        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11373    }
11374
11375    private static boolean isExternal(PackageSetting ps) {
11376        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11377    }
11378
11379    private static boolean isExternal(ApplicationInfo info) {
11380        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11381    }
11382
11383    private static boolean isSystemApp(PackageParser.Package pkg) {
11384        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11385    }
11386
11387    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11388        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11389    }
11390
11391    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11392        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11393    }
11394
11395    private static boolean isSystemApp(PackageSetting ps) {
11396        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11397    }
11398
11399    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11400        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11401    }
11402
11403    private int packageFlagsToInstallFlags(PackageSetting ps) {
11404        int installFlags = 0;
11405        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11406            // This existing package was an external ASEC install when we have
11407            // the external flag without a UUID
11408            installFlags |= PackageManager.INSTALL_EXTERNAL;
11409        }
11410        if (ps.isForwardLocked()) {
11411            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11412        }
11413        return installFlags;
11414    }
11415
11416    private void deleteTempPackageFiles() {
11417        final FilenameFilter filter = new FilenameFilter() {
11418            public boolean accept(File dir, String name) {
11419                return name.startsWith("vmdl") && name.endsWith(".tmp");
11420            }
11421        };
11422        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11423            file.delete();
11424        }
11425    }
11426
11427    @Override
11428    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11429            int flags) {
11430        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11431                flags);
11432    }
11433
11434    @Override
11435    public void deletePackage(final String packageName,
11436            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11437        mContext.enforceCallingOrSelfPermission(
11438                android.Manifest.permission.DELETE_PACKAGES, null);
11439        final int uid = Binder.getCallingUid();
11440        if (UserHandle.getUserId(uid) != userId) {
11441            mContext.enforceCallingPermission(
11442                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11443                    "deletePackage for user " + userId);
11444        }
11445        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11446            try {
11447                observer.onPackageDeleted(packageName,
11448                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11449            } catch (RemoteException re) {
11450            }
11451            return;
11452        }
11453
11454        boolean uninstallBlocked = false;
11455        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11456            int[] users = sUserManager.getUserIds();
11457            for (int i = 0; i < users.length; ++i) {
11458                if (getBlockUninstallForUser(packageName, users[i])) {
11459                    uninstallBlocked = true;
11460                    break;
11461                }
11462            }
11463        } else {
11464            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11465        }
11466        if (uninstallBlocked) {
11467            try {
11468                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11469                        null);
11470            } catch (RemoteException re) {
11471            }
11472            return;
11473        }
11474
11475        if (DEBUG_REMOVE) {
11476            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
11477        }
11478        // Queue up an async operation since the package deletion may take a little while.
11479        mHandler.post(new Runnable() {
11480            public void run() {
11481                mHandler.removeCallbacks(this);
11482                final int returnCode = deletePackageX(packageName, userId, flags);
11483                if (observer != null) {
11484                    try {
11485                        observer.onPackageDeleted(packageName, returnCode, null);
11486                    } catch (RemoteException e) {
11487                        Log.i(TAG, "Observer no longer exists.");
11488                    } //end catch
11489                } //end if
11490            } //end run
11491        });
11492    }
11493
11494    private boolean isPackageDeviceAdmin(String packageName, int userId) {
11495        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
11496                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
11497        try {
11498            if (dpm != null) {
11499                if (dpm.isDeviceOwner(packageName)) {
11500                    return true;
11501                }
11502                int[] users;
11503                if (userId == UserHandle.USER_ALL) {
11504                    users = sUserManager.getUserIds();
11505                } else {
11506                    users = new int[]{userId};
11507                }
11508                for (int i = 0; i < users.length; ++i) {
11509                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
11510                        return true;
11511                    }
11512                }
11513            }
11514        } catch (RemoteException e) {
11515        }
11516        return false;
11517    }
11518
11519    /**
11520     *  This method is an internal method that could be get invoked either
11521     *  to delete an installed package or to clean up a failed installation.
11522     *  After deleting an installed package, a broadcast is sent to notify any
11523     *  listeners that the package has been installed. For cleaning up a failed
11524     *  installation, the broadcast is not necessary since the package's
11525     *  installation wouldn't have sent the initial broadcast either
11526     *  The key steps in deleting a package are
11527     *  deleting the package information in internal structures like mPackages,
11528     *  deleting the packages base directories through installd
11529     *  updating mSettings to reflect current status
11530     *  persisting settings for later use
11531     *  sending a broadcast if necessary
11532     */
11533    private int deletePackageX(String packageName, int userId, int flags) {
11534        final PackageRemovedInfo info = new PackageRemovedInfo();
11535        final boolean res;
11536
11537        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
11538                ? UserHandle.ALL : new UserHandle(userId);
11539
11540        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
11541            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
11542            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
11543        }
11544
11545        boolean removedForAllUsers = false;
11546        boolean systemUpdate = false;
11547
11548        // for the uninstall-updates case and restricted profiles, remember the per-
11549        // userhandle installed state
11550        int[] allUsers;
11551        boolean[] perUserInstalled;
11552        synchronized (mPackages) {
11553            PackageSetting ps = mSettings.mPackages.get(packageName);
11554            allUsers = sUserManager.getUserIds();
11555            perUserInstalled = new boolean[allUsers.length];
11556            for (int i = 0; i < allUsers.length; i++) {
11557                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11558            }
11559        }
11560
11561        synchronized (mInstallLock) {
11562            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
11563            res = deletePackageLI(packageName, removeForUser,
11564                    true, allUsers, perUserInstalled,
11565                    flags | REMOVE_CHATTY, info, true);
11566            systemUpdate = info.isRemovedPackageSystemUpdate;
11567            if (res && !systemUpdate && mPackages.get(packageName) == null) {
11568                removedForAllUsers = true;
11569            }
11570            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
11571                    + " removedForAllUsers=" + removedForAllUsers);
11572        }
11573
11574        if (res) {
11575            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
11576
11577            // If the removed package was a system update, the old system package
11578            // was re-enabled; we need to broadcast this information
11579            if (systemUpdate) {
11580                Bundle extras = new Bundle(1);
11581                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
11582                        ? info.removedAppId : info.uid);
11583                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11584
11585                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
11586                        extras, null, null, null);
11587                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
11588                        extras, null, null, null);
11589                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
11590                        null, packageName, null, null);
11591            }
11592        }
11593        // Force a gc here.
11594        Runtime.getRuntime().gc();
11595        // Delete the resources here after sending the broadcast to let
11596        // other processes clean up before deleting resources.
11597        if (info.args != null) {
11598            synchronized (mInstallLock) {
11599                info.args.doPostDeleteLI(true);
11600            }
11601        }
11602
11603        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
11604    }
11605
11606    static class PackageRemovedInfo {
11607        String removedPackage;
11608        int uid = -1;
11609        int removedAppId = -1;
11610        int[] removedUsers = null;
11611        boolean isRemovedPackageSystemUpdate = false;
11612        // Clean up resources deleted packages.
11613        InstallArgs args = null;
11614
11615        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
11616            Bundle extras = new Bundle(1);
11617            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
11618            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
11619            if (replacing) {
11620                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11621            }
11622            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
11623            if (removedPackage != null) {
11624                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
11625                        extras, null, null, removedUsers);
11626                if (fullRemove && !replacing) {
11627                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
11628                            extras, null, null, removedUsers);
11629                }
11630            }
11631            if (removedAppId >= 0) {
11632                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
11633                        removedUsers);
11634            }
11635        }
11636    }
11637
11638    /*
11639     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
11640     * flag is not set, the data directory is removed as well.
11641     * make sure this flag is set for partially installed apps. If not its meaningless to
11642     * delete a partially installed application.
11643     */
11644    private void removePackageDataLI(PackageSetting ps,
11645            int[] allUserHandles, boolean[] perUserInstalled,
11646            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
11647        String packageName = ps.name;
11648        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
11649        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
11650        // Retrieve object to delete permissions for shared user later on
11651        final PackageSetting deletedPs;
11652        // reader
11653        synchronized (mPackages) {
11654            deletedPs = mSettings.mPackages.get(packageName);
11655            if (outInfo != null) {
11656                outInfo.removedPackage = packageName;
11657                outInfo.removedUsers = deletedPs != null
11658                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
11659                        : null;
11660            }
11661        }
11662        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11663            removeDataDirsLI(packageName);
11664            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
11665        }
11666        // writer
11667        synchronized (mPackages) {
11668            if (deletedPs != null) {
11669                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11670                    if (outInfo != null) {
11671                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
11672                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
11673                    }
11674                    updatePermissionsLPw(deletedPs.name, null, 0);
11675                    if (deletedPs.sharedUser != null) {
11676                        // Remove permissions associated with package. Since runtime
11677                        // permissions are per user we have to kill the removed package
11678                        // or packages running under the shared user of the removed
11679                        // package if revoking the permissions requested only by the removed
11680                        // package is successful and this causes a change in gids.
11681                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11682                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
11683                                    userId);
11684                            if (userIdToKill == UserHandle.USER_ALL
11685                                    || userIdToKill >= UserHandle.USER_OWNER) {
11686                                // If gids changed for this user, kill all affected packages.
11687                                mHandler.post(new Runnable() {
11688                                    @Override
11689                                    public void run() {
11690                                        // This has to happen with no lock held.
11691                                        killSettingPackagesForUser(deletedPs, userIdToKill,
11692                                                KILL_APP_REASON_GIDS_CHANGED);
11693                                    }
11694                                });
11695                            break;
11696                            }
11697                        }
11698                    }
11699                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
11700                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
11701                }
11702                // make sure to preserve per-user disabled state if this removal was just
11703                // a downgrade of a system app to the factory package
11704                if (allUserHandles != null && perUserInstalled != null) {
11705                    if (DEBUG_REMOVE) {
11706                        Slog.d(TAG, "Propagating install state across downgrade");
11707                    }
11708                    for (int i = 0; i < allUserHandles.length; i++) {
11709                        if (DEBUG_REMOVE) {
11710                            Slog.d(TAG, "    user " + allUserHandles[i]
11711                                    + " => " + perUserInstalled[i]);
11712                        }
11713                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11714                    }
11715                }
11716            }
11717            // can downgrade to reader
11718            if (writeSettings) {
11719                // Save settings now
11720                mSettings.writeLPr();
11721            }
11722        }
11723        if (outInfo != null) {
11724            // A user ID was deleted here. Go through all users and remove it
11725            // from KeyStore.
11726            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
11727        }
11728    }
11729
11730    static boolean locationIsPrivileged(File path) {
11731        try {
11732            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
11733                    .getCanonicalPath();
11734            return path.getCanonicalPath().startsWith(privilegedAppDir);
11735        } catch (IOException e) {
11736            Slog.e(TAG, "Unable to access code path " + path);
11737        }
11738        return false;
11739    }
11740
11741    /*
11742     * Tries to delete system package.
11743     */
11744    private boolean deleteSystemPackageLI(PackageSetting newPs,
11745            int[] allUserHandles, boolean[] perUserInstalled,
11746            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
11747        final boolean applyUserRestrictions
11748                = (allUserHandles != null) && (perUserInstalled != null);
11749        PackageSetting disabledPs = null;
11750        // Confirm if the system package has been updated
11751        // An updated system app can be deleted. This will also have to restore
11752        // the system pkg from system partition
11753        // reader
11754        synchronized (mPackages) {
11755            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
11756        }
11757        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
11758                + " disabledPs=" + disabledPs);
11759        if (disabledPs == null) {
11760            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
11761            return false;
11762        } else if (DEBUG_REMOVE) {
11763            Slog.d(TAG, "Deleting system pkg from data partition");
11764        }
11765        if (DEBUG_REMOVE) {
11766            if (applyUserRestrictions) {
11767                Slog.d(TAG, "Remembering install states:");
11768                for (int i = 0; i < allUserHandles.length; i++) {
11769                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
11770                }
11771            }
11772        }
11773        // Delete the updated package
11774        outInfo.isRemovedPackageSystemUpdate = true;
11775        if (disabledPs.versionCode < newPs.versionCode) {
11776            // Delete data for downgrades
11777            flags &= ~PackageManager.DELETE_KEEP_DATA;
11778        } else {
11779            // Preserve data by setting flag
11780            flags |= PackageManager.DELETE_KEEP_DATA;
11781        }
11782        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
11783                allUserHandles, perUserInstalled, outInfo, writeSettings);
11784        if (!ret) {
11785            return false;
11786        }
11787        // writer
11788        synchronized (mPackages) {
11789            // Reinstate the old system package
11790            mSettings.enableSystemPackageLPw(newPs.name);
11791            // Remove any native libraries from the upgraded package.
11792            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
11793        }
11794        // Install the system package
11795        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
11796        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
11797        if (locationIsPrivileged(disabledPs.codePath)) {
11798            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11799        }
11800
11801        final PackageParser.Package newPkg;
11802        try {
11803            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
11804        } catch (PackageManagerException e) {
11805            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
11806            return false;
11807        }
11808
11809        // writer
11810        synchronized (mPackages) {
11811            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
11812            updatePermissionsLPw(newPkg.packageName, newPkg,
11813                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
11814            if (applyUserRestrictions) {
11815                if (DEBUG_REMOVE) {
11816                    Slog.d(TAG, "Propagating install state across reinstall");
11817                }
11818                for (int i = 0; i < allUserHandles.length; i++) {
11819                    if (DEBUG_REMOVE) {
11820                        Slog.d(TAG, "    user " + allUserHandles[i]
11821                                + " => " + perUserInstalled[i]);
11822                    }
11823                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11824                }
11825                // Regardless of writeSettings we need to ensure that this restriction
11826                // state propagation is persisted
11827                mSettings.writeAllUsersPackageRestrictionsLPr();
11828            }
11829            // can downgrade to reader here
11830            if (writeSettings) {
11831                mSettings.writeLPr();
11832            }
11833        }
11834        return true;
11835    }
11836
11837    private boolean deleteInstalledPackageLI(PackageSetting ps,
11838            boolean deleteCodeAndResources, int flags,
11839            int[] allUserHandles, boolean[] perUserInstalled,
11840            PackageRemovedInfo outInfo, boolean writeSettings) {
11841        if (outInfo != null) {
11842            outInfo.uid = ps.appId;
11843        }
11844
11845        // Delete package data from internal structures and also remove data if flag is set
11846        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
11847
11848        // Delete application code and resources
11849        if (deleteCodeAndResources && (outInfo != null)) {
11850            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
11851                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
11852                    getAppDexInstructionSets(ps));
11853            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
11854        }
11855        return true;
11856    }
11857
11858    @Override
11859    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
11860            int userId) {
11861        mContext.enforceCallingOrSelfPermission(
11862                android.Manifest.permission.DELETE_PACKAGES, null);
11863        synchronized (mPackages) {
11864            PackageSetting ps = mSettings.mPackages.get(packageName);
11865            if (ps == null) {
11866                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
11867                return false;
11868            }
11869            if (!ps.getInstalled(userId)) {
11870                // Can't block uninstall for an app that is not installed or enabled.
11871                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11872                return false;
11873            }
11874            ps.setBlockUninstall(blockUninstall, userId);
11875            mSettings.writePackageRestrictionsLPr(userId);
11876        }
11877        return true;
11878    }
11879
11880    @Override
11881    public boolean getBlockUninstallForUser(String packageName, int userId) {
11882        synchronized (mPackages) {
11883            PackageSetting ps = mSettings.mPackages.get(packageName);
11884            if (ps == null) {
11885                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11886                return false;
11887            }
11888            return ps.getBlockUninstall(userId);
11889        }
11890    }
11891
11892    /*
11893     * This method handles package deletion in general
11894     */
11895    private boolean deletePackageLI(String packageName, UserHandle user,
11896            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11897            int flags, PackageRemovedInfo outInfo,
11898            boolean writeSettings) {
11899        if (packageName == null) {
11900            Slog.w(TAG, "Attempt to delete null packageName.");
11901            return false;
11902        }
11903        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11904        PackageSetting ps;
11905        boolean dataOnly = false;
11906        int removeUser = -1;
11907        int appId = -1;
11908        synchronized (mPackages) {
11909            ps = mSettings.mPackages.get(packageName);
11910            if (ps == null) {
11911                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11912                return false;
11913            }
11914            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11915                    && user.getIdentifier() != UserHandle.USER_ALL) {
11916                // The caller is asking that the package only be deleted for a single
11917                // user.  To do this, we just mark its uninstalled state and delete
11918                // its data.  If this is a system app, we only allow this to happen if
11919                // they have set the special DELETE_SYSTEM_APP which requests different
11920                // semantics than normal for uninstalling system apps.
11921                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11922                ps.setUserState(user.getIdentifier(),
11923                        COMPONENT_ENABLED_STATE_DEFAULT,
11924                        false, //installed
11925                        true,  //stopped
11926                        true,  //notLaunched
11927                        false, //hidden
11928                        null, null, null,
11929                        false, // blockUninstall
11930                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
11931                if (!isSystemApp(ps)) {
11932                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11933                        // Other user still have this package installed, so all
11934                        // we need to do is clear this user's data and save that
11935                        // it is uninstalled.
11936                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11937                        removeUser = user.getIdentifier();
11938                        appId = ps.appId;
11939                        scheduleWritePackageRestrictionsLocked(removeUser);
11940                    } else {
11941                        // We need to set it back to 'installed' so the uninstall
11942                        // broadcasts will be sent correctly.
11943                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11944                        ps.setInstalled(true, user.getIdentifier());
11945                    }
11946                } else {
11947                    // This is a system app, so we assume that the
11948                    // other users still have this package installed, so all
11949                    // we need to do is clear this user's data and save that
11950                    // it is uninstalled.
11951                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11952                    removeUser = user.getIdentifier();
11953                    appId = ps.appId;
11954                    scheduleWritePackageRestrictionsLocked(removeUser);
11955                }
11956            }
11957        }
11958
11959        if (removeUser >= 0) {
11960            // From above, we determined that we are deleting this only
11961            // for a single user.  Continue the work here.
11962            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11963            if (outInfo != null) {
11964                outInfo.removedPackage = packageName;
11965                outInfo.removedAppId = appId;
11966                outInfo.removedUsers = new int[] {removeUser};
11967            }
11968            mInstaller.clearUserData(packageName, removeUser);
11969            removeKeystoreDataIfNeeded(removeUser, appId);
11970            schedulePackageCleaning(packageName, removeUser, false);
11971            synchronized (mPackages) {
11972                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
11973                    scheduleWritePackageRestrictionsLocked(removeUser);
11974                }
11975            }
11976            return true;
11977        }
11978
11979        if (dataOnly) {
11980            // Delete application data first
11981            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11982            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11983            return true;
11984        }
11985
11986        boolean ret = false;
11987        if (isSystemApp(ps)) {
11988            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11989            // When an updated system application is deleted we delete the existing resources as well and
11990            // fall back to existing code in system partition
11991            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11992                    flags, outInfo, writeSettings);
11993        } else {
11994            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11995            // Kill application pre-emptively especially for apps on sd.
11996            killApplication(packageName, ps.appId, "uninstall pkg");
11997            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11998                    allUserHandles, perUserInstalled,
11999                    outInfo, writeSettings);
12000        }
12001
12002        return ret;
12003    }
12004
12005    private final class ClearStorageConnection implements ServiceConnection {
12006        IMediaContainerService mContainerService;
12007
12008        @Override
12009        public void onServiceConnected(ComponentName name, IBinder service) {
12010            synchronized (this) {
12011                mContainerService = IMediaContainerService.Stub.asInterface(service);
12012                notifyAll();
12013            }
12014        }
12015
12016        @Override
12017        public void onServiceDisconnected(ComponentName name) {
12018        }
12019    }
12020
12021    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12022        final boolean mounted;
12023        if (Environment.isExternalStorageEmulated()) {
12024            mounted = true;
12025        } else {
12026            final String status = Environment.getExternalStorageState();
12027
12028            mounted = status.equals(Environment.MEDIA_MOUNTED)
12029                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12030        }
12031
12032        if (!mounted) {
12033            return;
12034        }
12035
12036        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12037        int[] users;
12038        if (userId == UserHandle.USER_ALL) {
12039            users = sUserManager.getUserIds();
12040        } else {
12041            users = new int[] { userId };
12042        }
12043        final ClearStorageConnection conn = new ClearStorageConnection();
12044        if (mContext.bindServiceAsUser(
12045                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12046            try {
12047                for (int curUser : users) {
12048                    long timeout = SystemClock.uptimeMillis() + 5000;
12049                    synchronized (conn) {
12050                        long now = SystemClock.uptimeMillis();
12051                        while (conn.mContainerService == null && now < timeout) {
12052                            try {
12053                                conn.wait(timeout - now);
12054                            } catch (InterruptedException e) {
12055                            }
12056                        }
12057                    }
12058                    if (conn.mContainerService == null) {
12059                        return;
12060                    }
12061
12062                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12063                    clearDirectory(conn.mContainerService,
12064                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12065                    if (allData) {
12066                        clearDirectory(conn.mContainerService,
12067                                userEnv.buildExternalStorageAppDataDirs(packageName));
12068                        clearDirectory(conn.mContainerService,
12069                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12070                    }
12071                }
12072            } finally {
12073                mContext.unbindService(conn);
12074            }
12075        }
12076    }
12077
12078    @Override
12079    public void clearApplicationUserData(final String packageName,
12080            final IPackageDataObserver observer, final int userId) {
12081        mContext.enforceCallingOrSelfPermission(
12082                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12083        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12084        // Queue up an async operation since the package deletion may take a little while.
12085        mHandler.post(new Runnable() {
12086            public void run() {
12087                mHandler.removeCallbacks(this);
12088                final boolean succeeded;
12089                synchronized (mInstallLock) {
12090                    succeeded = clearApplicationUserDataLI(packageName, userId);
12091                }
12092                clearExternalStorageDataSync(packageName, userId, true);
12093                if (succeeded) {
12094                    // invoke DeviceStorageMonitor's update method to clear any notifications
12095                    DeviceStorageMonitorInternal
12096                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12097                    if (dsm != null) {
12098                        dsm.checkMemory();
12099                    }
12100                }
12101                if(observer != null) {
12102                    try {
12103                        observer.onRemoveCompleted(packageName, succeeded);
12104                    } catch (RemoteException e) {
12105                        Log.i(TAG, "Observer no longer exists.");
12106                    }
12107                } //end if observer
12108            } //end run
12109        });
12110    }
12111
12112    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12113        if (packageName == null) {
12114            Slog.w(TAG, "Attempt to delete null packageName.");
12115            return false;
12116        }
12117
12118        // Try finding details about the requested package
12119        PackageParser.Package pkg;
12120        synchronized (mPackages) {
12121            pkg = mPackages.get(packageName);
12122            if (pkg == null) {
12123                final PackageSetting ps = mSettings.mPackages.get(packageName);
12124                if (ps != null) {
12125                    pkg = ps.pkg;
12126                }
12127            }
12128        }
12129
12130        if (pkg == null) {
12131            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12132        }
12133
12134        // Always delete data directories for package, even if we found no other
12135        // record of app. This helps users recover from UID mismatches without
12136        // resorting to a full data wipe.
12137        int retCode = mInstaller.clearUserData(packageName, userId);
12138        if (retCode < 0) {
12139            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12140            return false;
12141        }
12142
12143        if (pkg == null) {
12144            return false;
12145        }
12146
12147        if (pkg != null && pkg.applicationInfo != null) {
12148            final int appId = pkg.applicationInfo.uid;
12149            removeKeystoreDataIfNeeded(userId, appId);
12150        }
12151
12152        // Create a native library symlink only if we have native libraries
12153        // and if the native libraries are 32 bit libraries. We do not provide
12154        // this symlink for 64 bit libraries.
12155        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
12156                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12157            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12158            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
12159                Slog.w(TAG, "Failed linking native library dir");
12160                return false;
12161            }
12162        }
12163
12164        return true;
12165    }
12166
12167    /**
12168     * Remove entries from the keystore daemon. Will only remove it if the
12169     * {@code appId} is valid.
12170     */
12171    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12172        if (appId < 0) {
12173            return;
12174        }
12175
12176        final KeyStore keyStore = KeyStore.getInstance();
12177        if (keyStore != null) {
12178            if (userId == UserHandle.USER_ALL) {
12179                for (final int individual : sUserManager.getUserIds()) {
12180                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12181                }
12182            } else {
12183                keyStore.clearUid(UserHandle.getUid(userId, appId));
12184            }
12185        } else {
12186            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12187        }
12188    }
12189
12190    @Override
12191    public void deleteApplicationCacheFiles(final String packageName,
12192            final IPackageDataObserver observer) {
12193        mContext.enforceCallingOrSelfPermission(
12194                android.Manifest.permission.DELETE_CACHE_FILES, null);
12195        // Queue up an async operation since the package deletion may take a little while.
12196        final int userId = UserHandle.getCallingUserId();
12197        mHandler.post(new Runnable() {
12198            public void run() {
12199                mHandler.removeCallbacks(this);
12200                final boolean succeded;
12201                synchronized (mInstallLock) {
12202                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12203                }
12204                clearExternalStorageDataSync(packageName, userId, false);
12205                if(observer != null) {
12206                    try {
12207                        observer.onRemoveCompleted(packageName, succeded);
12208                    } catch (RemoteException e) {
12209                        Log.i(TAG, "Observer no longer exists.");
12210                    }
12211                } //end if observer
12212            } //end run
12213        });
12214    }
12215
12216    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12217        if (packageName == null) {
12218            Slog.w(TAG, "Attempt to delete null packageName.");
12219            return false;
12220        }
12221        PackageParser.Package p;
12222        synchronized (mPackages) {
12223            p = mPackages.get(packageName);
12224        }
12225        if (p == null) {
12226            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12227            return false;
12228        }
12229        final ApplicationInfo applicationInfo = p.applicationInfo;
12230        if (applicationInfo == null) {
12231            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12232            return false;
12233        }
12234        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
12235        if (retCode < 0) {
12236            Slog.w(TAG, "Couldn't remove cache files for package: "
12237                       + packageName + " u" + userId);
12238            return false;
12239        }
12240        return true;
12241    }
12242
12243    @Override
12244    public void getPackageSizeInfo(final String packageName, int userHandle,
12245            final IPackageStatsObserver observer) {
12246        mContext.enforceCallingOrSelfPermission(
12247                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12248        if (packageName == null) {
12249            throw new IllegalArgumentException("Attempt to get size of null packageName");
12250        }
12251
12252        PackageStats stats = new PackageStats(packageName, userHandle);
12253
12254        /*
12255         * Queue up an async operation since the package measurement may take a
12256         * little while.
12257         */
12258        Message msg = mHandler.obtainMessage(INIT_COPY);
12259        msg.obj = new MeasureParams(stats, observer);
12260        mHandler.sendMessage(msg);
12261    }
12262
12263    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12264            PackageStats pStats) {
12265        if (packageName == null) {
12266            Slog.w(TAG, "Attempt to get size of null packageName.");
12267            return false;
12268        }
12269        PackageParser.Package p;
12270        boolean dataOnly = false;
12271        String libDirRoot = null;
12272        String asecPath = null;
12273        PackageSetting ps = null;
12274        synchronized (mPackages) {
12275            p = mPackages.get(packageName);
12276            ps = mSettings.mPackages.get(packageName);
12277            if(p == null) {
12278                dataOnly = true;
12279                if((ps == null) || (ps.pkg == null)) {
12280                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12281                    return false;
12282                }
12283                p = ps.pkg;
12284            }
12285            if (ps != null) {
12286                libDirRoot = ps.legacyNativeLibraryPathString;
12287            }
12288            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12289                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12290                if (secureContainerId != null) {
12291                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12292                }
12293            }
12294        }
12295        String publicSrcDir = null;
12296        if(!dataOnly) {
12297            final ApplicationInfo applicationInfo = p.applicationInfo;
12298            if (applicationInfo == null) {
12299                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12300                return false;
12301            }
12302            if (p.isForwardLocked()) {
12303                publicSrcDir = applicationInfo.getBaseResourcePath();
12304            }
12305        }
12306        // TODO: extend to measure size of split APKs
12307        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12308        // not just the first level.
12309        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12310        // just the primary.
12311        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12312        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
12313                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12314        if (res < 0) {
12315            return false;
12316        }
12317
12318        // Fix-up for forward-locked applications in ASEC containers.
12319        if (!isExternal(p)) {
12320            pStats.codeSize += pStats.externalCodeSize;
12321            pStats.externalCodeSize = 0L;
12322        }
12323
12324        return true;
12325    }
12326
12327
12328    @Override
12329    public void addPackageToPreferred(String packageName) {
12330        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12331    }
12332
12333    @Override
12334    public void removePackageFromPreferred(String packageName) {
12335        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12336    }
12337
12338    @Override
12339    public List<PackageInfo> getPreferredPackages(int flags) {
12340        return new ArrayList<PackageInfo>();
12341    }
12342
12343    private int getUidTargetSdkVersionLockedLPr(int uid) {
12344        Object obj = mSettings.getUserIdLPr(uid);
12345        if (obj instanceof SharedUserSetting) {
12346            final SharedUserSetting sus = (SharedUserSetting) obj;
12347            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12348            final Iterator<PackageSetting> it = sus.packages.iterator();
12349            while (it.hasNext()) {
12350                final PackageSetting ps = it.next();
12351                if (ps.pkg != null) {
12352                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12353                    if (v < vers) vers = v;
12354                }
12355            }
12356            return vers;
12357        } else if (obj instanceof PackageSetting) {
12358            final PackageSetting ps = (PackageSetting) obj;
12359            if (ps.pkg != null) {
12360                return ps.pkg.applicationInfo.targetSdkVersion;
12361            }
12362        }
12363        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12364    }
12365
12366    @Override
12367    public void addPreferredActivity(IntentFilter filter, int match,
12368            ComponentName[] set, ComponentName activity, int userId) {
12369        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12370                "Adding preferred");
12371    }
12372
12373    private void addPreferredActivityInternal(IntentFilter filter, int match,
12374            ComponentName[] set, ComponentName activity, boolean always, int userId,
12375            String opname) {
12376        // writer
12377        int callingUid = Binder.getCallingUid();
12378        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12379        if (filter.countActions() == 0) {
12380            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12381            return;
12382        }
12383        synchronized (mPackages) {
12384            if (mContext.checkCallingOrSelfPermission(
12385                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12386                    != PackageManager.PERMISSION_GRANTED) {
12387                if (getUidTargetSdkVersionLockedLPr(callingUid)
12388                        < Build.VERSION_CODES.FROYO) {
12389                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12390                            + callingUid);
12391                    return;
12392                }
12393                mContext.enforceCallingOrSelfPermission(
12394                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12395            }
12396
12397            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12398            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12399                    + userId + ":");
12400            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12401            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12402            scheduleWritePackageRestrictionsLocked(userId);
12403        }
12404    }
12405
12406    @Override
12407    public void replacePreferredActivity(IntentFilter filter, int match,
12408            ComponentName[] set, ComponentName activity, int userId) {
12409        if (filter.countActions() != 1) {
12410            throw new IllegalArgumentException(
12411                    "replacePreferredActivity expects filter to have only 1 action.");
12412        }
12413        if (filter.countDataAuthorities() != 0
12414                || filter.countDataPaths() != 0
12415                || filter.countDataSchemes() > 1
12416                || filter.countDataTypes() != 0) {
12417            throw new IllegalArgumentException(
12418                    "replacePreferredActivity expects filter to have no data authorities, " +
12419                    "paths, or types; and at most one scheme.");
12420        }
12421
12422        final int callingUid = Binder.getCallingUid();
12423        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12424        synchronized (mPackages) {
12425            if (mContext.checkCallingOrSelfPermission(
12426                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12427                    != PackageManager.PERMISSION_GRANTED) {
12428                if (getUidTargetSdkVersionLockedLPr(callingUid)
12429                        < Build.VERSION_CODES.FROYO) {
12430                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12431                            + Binder.getCallingUid());
12432                    return;
12433                }
12434                mContext.enforceCallingOrSelfPermission(
12435                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12436            }
12437
12438            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12439            if (pir != null) {
12440                // Get all of the existing entries that exactly match this filter.
12441                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
12442                if (existing != null && existing.size() == 1) {
12443                    PreferredActivity cur = existing.get(0);
12444                    if (DEBUG_PREFERRED) {
12445                        Slog.i(TAG, "Checking replace of preferred:");
12446                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12447                        if (!cur.mPref.mAlways) {
12448                            Slog.i(TAG, "  -- CUR; not mAlways!");
12449                        } else {
12450                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
12451                            Slog.i(TAG, "  -- CUR: mSet="
12452                                    + Arrays.toString(cur.mPref.mSetComponents));
12453                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
12454                            Slog.i(TAG, "  -- NEW: mMatch="
12455                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
12456                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
12457                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
12458                        }
12459                    }
12460                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
12461                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
12462                            && cur.mPref.sameSet(set)) {
12463                        // Setting the preferred activity to what it happens to be already
12464                        if (DEBUG_PREFERRED) {
12465                            Slog.i(TAG, "Replacing with same preferred activity "
12466                                    + cur.mPref.mShortComponent + " for user "
12467                                    + userId + ":");
12468                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12469                        }
12470                        return;
12471                    }
12472                }
12473
12474                if (existing != null) {
12475                    if (DEBUG_PREFERRED) {
12476                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
12477                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12478                    }
12479                    for (int i = 0; i < existing.size(); i++) {
12480                        PreferredActivity pa = existing.get(i);
12481                        if (DEBUG_PREFERRED) {
12482                            Slog.i(TAG, "Removing existing preferred activity "
12483                                    + pa.mPref.mComponent + ":");
12484                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
12485                        }
12486                        pir.removeFilter(pa);
12487                    }
12488                }
12489            }
12490            addPreferredActivityInternal(filter, match, set, activity, true, userId,
12491                    "Replacing preferred");
12492        }
12493    }
12494
12495    @Override
12496    public void clearPackagePreferredActivities(String packageName) {
12497        final int uid = Binder.getCallingUid();
12498        // writer
12499        synchronized (mPackages) {
12500            PackageParser.Package pkg = mPackages.get(packageName);
12501            if (pkg == null || pkg.applicationInfo.uid != uid) {
12502                if (mContext.checkCallingOrSelfPermission(
12503                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12504                        != PackageManager.PERMISSION_GRANTED) {
12505                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
12506                            < Build.VERSION_CODES.FROYO) {
12507                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
12508                                + Binder.getCallingUid());
12509                        return;
12510                    }
12511                    mContext.enforceCallingOrSelfPermission(
12512                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12513                }
12514            }
12515
12516            int user = UserHandle.getCallingUserId();
12517            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
12518                scheduleWritePackageRestrictionsLocked(user);
12519            }
12520        }
12521    }
12522
12523    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12524    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
12525        ArrayList<PreferredActivity> removed = null;
12526        boolean changed = false;
12527        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12528            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
12529            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12530            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
12531                continue;
12532            }
12533            Iterator<PreferredActivity> it = pir.filterIterator();
12534            while (it.hasNext()) {
12535                PreferredActivity pa = it.next();
12536                // Mark entry for removal only if it matches the package name
12537                // and the entry is of type "always".
12538                if (packageName == null ||
12539                        (pa.mPref.mComponent.getPackageName().equals(packageName)
12540                                && pa.mPref.mAlways)) {
12541                    if (removed == null) {
12542                        removed = new ArrayList<PreferredActivity>();
12543                    }
12544                    removed.add(pa);
12545                }
12546            }
12547            if (removed != null) {
12548                for (int j=0; j<removed.size(); j++) {
12549                    PreferredActivity pa = removed.get(j);
12550                    pir.removeFilter(pa);
12551                }
12552                changed = true;
12553            }
12554        }
12555        return changed;
12556    }
12557
12558    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12559    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
12560        if (userId == UserHandle.USER_ALL) {
12561            mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds());
12562            for (int oneUserId : sUserManager.getUserIds()) {
12563                scheduleWritePackageRestrictionsLocked(oneUserId);
12564            }
12565        } else {
12566            mSettings.removeIntentFilterVerificationLPw(packageName, userId);
12567            scheduleWritePackageRestrictionsLocked(userId);
12568        }
12569    }
12570
12571    @Override
12572    public void resetPreferredActivities(int userId) {
12573        /* TODO: Actually use userId. Why is it being passed in? */
12574        mContext.enforceCallingOrSelfPermission(
12575                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12576        // writer
12577        synchronized (mPackages) {
12578            int user = UserHandle.getCallingUserId();
12579            clearPackagePreferredActivitiesLPw(null, user);
12580            mSettings.readDefaultPreferredAppsLPw(this, user);
12581            scheduleWritePackageRestrictionsLocked(user);
12582        }
12583    }
12584
12585    @Override
12586    public int getPreferredActivities(List<IntentFilter> outFilters,
12587            List<ComponentName> outActivities, String packageName) {
12588
12589        int num = 0;
12590        final int userId = UserHandle.getCallingUserId();
12591        // reader
12592        synchronized (mPackages) {
12593            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12594            if (pir != null) {
12595                final Iterator<PreferredActivity> it = pir.filterIterator();
12596                while (it.hasNext()) {
12597                    final PreferredActivity pa = it.next();
12598                    if (packageName == null
12599                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
12600                                    && pa.mPref.mAlways)) {
12601                        if (outFilters != null) {
12602                            outFilters.add(new IntentFilter(pa));
12603                        }
12604                        if (outActivities != null) {
12605                            outActivities.add(pa.mPref.mComponent);
12606                        }
12607                    }
12608                }
12609            }
12610        }
12611
12612        return num;
12613    }
12614
12615    @Override
12616    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
12617            int userId) {
12618        int callingUid = Binder.getCallingUid();
12619        if (callingUid != Process.SYSTEM_UID) {
12620            throw new SecurityException(
12621                    "addPersistentPreferredActivity can only be run by the system");
12622        }
12623        if (filter.countActions() == 0) {
12624            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12625            return;
12626        }
12627        synchronized (mPackages) {
12628            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
12629                    " :");
12630            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12631            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
12632                    new PersistentPreferredActivity(filter, activity));
12633            scheduleWritePackageRestrictionsLocked(userId);
12634        }
12635    }
12636
12637    @Override
12638    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
12639        int callingUid = Binder.getCallingUid();
12640        if (callingUid != Process.SYSTEM_UID) {
12641            throw new SecurityException(
12642                    "clearPackagePersistentPreferredActivities can only be run by the system");
12643        }
12644        ArrayList<PersistentPreferredActivity> removed = null;
12645        boolean changed = false;
12646        synchronized (mPackages) {
12647            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
12648                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
12649                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
12650                        .valueAt(i);
12651                if (userId != thisUserId) {
12652                    continue;
12653                }
12654                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
12655                while (it.hasNext()) {
12656                    PersistentPreferredActivity ppa = it.next();
12657                    // Mark entry for removal only if it matches the package name.
12658                    if (ppa.mComponent.getPackageName().equals(packageName)) {
12659                        if (removed == null) {
12660                            removed = new ArrayList<PersistentPreferredActivity>();
12661                        }
12662                        removed.add(ppa);
12663                    }
12664                }
12665                if (removed != null) {
12666                    for (int j=0; j<removed.size(); j++) {
12667                        PersistentPreferredActivity ppa = removed.get(j);
12668                        ppir.removeFilter(ppa);
12669                    }
12670                    changed = true;
12671                }
12672            }
12673
12674            if (changed) {
12675                scheduleWritePackageRestrictionsLocked(userId);
12676            }
12677        }
12678    }
12679
12680    /**
12681     * Non-Binder method, support for the backup/restore mechanism: write the
12682     * full set of preferred activities in its canonical XML format.  Returns true
12683     * on success; false otherwise.
12684     */
12685    @Override
12686    public byte[] getPreferredActivityBackup(int userId) {
12687        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
12688            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
12689        }
12690
12691        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
12692        try {
12693            final XmlSerializer serializer = new FastXmlSerializer();
12694            serializer.setOutput(dataStream, "utf-8");
12695            serializer.startDocument(null, true);
12696            serializer.startTag(null, TAG_PREFERRED_BACKUP);
12697
12698            synchronized (mPackages) {
12699                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
12700            }
12701
12702            serializer.endTag(null, TAG_PREFERRED_BACKUP);
12703            serializer.endDocument();
12704            serializer.flush();
12705        } catch (Exception e) {
12706            if (DEBUG_BACKUP) {
12707                Slog.e(TAG, "Unable to write preferred activities for backup", e);
12708            }
12709            return null;
12710        }
12711
12712        return dataStream.toByteArray();
12713    }
12714
12715    @Override
12716    public void restorePreferredActivities(byte[] backup, int userId) {
12717        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
12718            throw new SecurityException("Only the system may call restorePreferredActivities()");
12719        }
12720
12721        try {
12722            final XmlPullParser parser = Xml.newPullParser();
12723            parser.setInput(new ByteArrayInputStream(backup), null);
12724
12725            int type;
12726            while ((type = parser.next()) != XmlPullParser.START_TAG
12727                    && type != XmlPullParser.END_DOCUMENT) {
12728            }
12729            if (type != XmlPullParser.START_TAG) {
12730                // oops didn't find a start tag?!
12731                if (DEBUG_BACKUP) {
12732                    Slog.e(TAG, "Didn't find start tag during restore");
12733                }
12734                return;
12735            }
12736
12737            // this is supposed to be TAG_PREFERRED_BACKUP
12738            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
12739                if (DEBUG_BACKUP) {
12740                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
12741                }
12742                return;
12743            }
12744
12745            // skip interfering stuff, then we're aligned with the backing implementation
12746            while ((type = parser.next()) == XmlPullParser.TEXT) { }
12747            synchronized (mPackages) {
12748                mSettings.readPreferredActivitiesLPw(parser, userId);
12749            }
12750        } catch (Exception e) {
12751            if (DEBUG_BACKUP) {
12752                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
12753            }
12754        }
12755    }
12756
12757    @Override
12758    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
12759            int sourceUserId, int targetUserId, int flags) {
12760        mContext.enforceCallingOrSelfPermission(
12761                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12762        int callingUid = Binder.getCallingUid();
12763        enforceOwnerRights(ownerPackage, callingUid);
12764        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12765        if (intentFilter.countActions() == 0) {
12766            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
12767            return;
12768        }
12769        synchronized (mPackages) {
12770            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
12771                    ownerPackage, targetUserId, flags);
12772            CrossProfileIntentResolver resolver =
12773                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12774            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
12775            // We have all those whose filter is equal. Now checking if the rest is equal as well.
12776            if (existing != null) {
12777                int size = existing.size();
12778                for (int i = 0; i < size; i++) {
12779                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
12780                        return;
12781                    }
12782                }
12783            }
12784            resolver.addFilter(newFilter);
12785            scheduleWritePackageRestrictionsLocked(sourceUserId);
12786        }
12787    }
12788
12789    @Override
12790    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
12791        mContext.enforceCallingOrSelfPermission(
12792                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12793        int callingUid = Binder.getCallingUid();
12794        enforceOwnerRights(ownerPackage, callingUid);
12795        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12796        synchronized (mPackages) {
12797            CrossProfileIntentResolver resolver =
12798                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12799            ArraySet<CrossProfileIntentFilter> set =
12800                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
12801            for (CrossProfileIntentFilter filter : set) {
12802                if (filter.getOwnerPackage().equals(ownerPackage)) {
12803                    resolver.removeFilter(filter);
12804                }
12805            }
12806            scheduleWritePackageRestrictionsLocked(sourceUserId);
12807        }
12808    }
12809
12810    // Enforcing that callingUid is owning pkg on userId
12811    private void enforceOwnerRights(String pkg, int callingUid) {
12812        // The system owns everything.
12813        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
12814            return;
12815        }
12816        int callingUserId = UserHandle.getUserId(callingUid);
12817        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
12818        if (pi == null) {
12819            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
12820                    + callingUserId);
12821        }
12822        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
12823            throw new SecurityException("Calling uid " + callingUid
12824                    + " does not own package " + pkg);
12825        }
12826    }
12827
12828    @Override
12829    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
12830        Intent intent = new Intent(Intent.ACTION_MAIN);
12831        intent.addCategory(Intent.CATEGORY_HOME);
12832
12833        final int callingUserId = UserHandle.getCallingUserId();
12834        List<ResolveInfo> list = queryIntentActivities(intent, null,
12835                PackageManager.GET_META_DATA, callingUserId);
12836        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
12837                true, false, false, callingUserId);
12838
12839        allHomeCandidates.clear();
12840        if (list != null) {
12841            for (ResolveInfo ri : list) {
12842                allHomeCandidates.add(ri);
12843            }
12844        }
12845        return (preferred == null || preferred.activityInfo == null)
12846                ? null
12847                : new ComponentName(preferred.activityInfo.packageName,
12848                        preferred.activityInfo.name);
12849    }
12850
12851    @Override
12852    public void setApplicationEnabledSetting(String appPackageName,
12853            int newState, int flags, int userId, String callingPackage) {
12854        if (!sUserManager.exists(userId)) return;
12855        if (callingPackage == null) {
12856            callingPackage = Integer.toString(Binder.getCallingUid());
12857        }
12858        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
12859    }
12860
12861    @Override
12862    public void setComponentEnabledSetting(ComponentName componentName,
12863            int newState, int flags, int userId) {
12864        if (!sUserManager.exists(userId)) return;
12865        setEnabledSetting(componentName.getPackageName(),
12866                componentName.getClassName(), newState, flags, userId, null);
12867    }
12868
12869    private void setEnabledSetting(final String packageName, String className, int newState,
12870            final int flags, int userId, String callingPackage) {
12871        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
12872              || newState == COMPONENT_ENABLED_STATE_ENABLED
12873              || newState == COMPONENT_ENABLED_STATE_DISABLED
12874              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
12875              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
12876            throw new IllegalArgumentException("Invalid new component state: "
12877                    + newState);
12878        }
12879        PackageSetting pkgSetting;
12880        final int uid = Binder.getCallingUid();
12881        final int permission = mContext.checkCallingOrSelfPermission(
12882                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12883        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
12884        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12885        boolean sendNow = false;
12886        boolean isApp = (className == null);
12887        String componentName = isApp ? packageName : className;
12888        int packageUid = -1;
12889        ArrayList<String> components;
12890
12891        // writer
12892        synchronized (mPackages) {
12893            pkgSetting = mSettings.mPackages.get(packageName);
12894            if (pkgSetting == null) {
12895                if (className == null) {
12896                    throw new IllegalArgumentException(
12897                            "Unknown package: " + packageName);
12898                }
12899                throw new IllegalArgumentException(
12900                        "Unknown component: " + packageName
12901                        + "/" + className);
12902            }
12903            // Allow root and verify that userId is not being specified by a different user
12904            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
12905                throw new SecurityException(
12906                        "Permission Denial: attempt to change component state from pid="
12907                        + Binder.getCallingPid()
12908                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
12909            }
12910            if (className == null) {
12911                // We're dealing with an application/package level state change
12912                if (pkgSetting.getEnabled(userId) == newState) {
12913                    // Nothing to do
12914                    return;
12915                }
12916                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
12917                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
12918                    // Don't care about who enables an app.
12919                    callingPackage = null;
12920                }
12921                pkgSetting.setEnabled(newState, userId, callingPackage);
12922                // pkgSetting.pkg.mSetEnabled = newState;
12923            } else {
12924                // We're dealing with a component level state change
12925                // First, verify that this is a valid class name.
12926                PackageParser.Package pkg = pkgSetting.pkg;
12927                if (pkg == null || !pkg.hasComponentClassName(className)) {
12928                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
12929                        throw new IllegalArgumentException("Component class " + className
12930                                + " does not exist in " + packageName);
12931                    } else {
12932                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
12933                                + className + " does not exist in " + packageName);
12934                    }
12935                }
12936                switch (newState) {
12937                case COMPONENT_ENABLED_STATE_ENABLED:
12938                    if (!pkgSetting.enableComponentLPw(className, userId)) {
12939                        return;
12940                    }
12941                    break;
12942                case COMPONENT_ENABLED_STATE_DISABLED:
12943                    if (!pkgSetting.disableComponentLPw(className, userId)) {
12944                        return;
12945                    }
12946                    break;
12947                case COMPONENT_ENABLED_STATE_DEFAULT:
12948                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
12949                        return;
12950                    }
12951                    break;
12952                default:
12953                    Slog.e(TAG, "Invalid new component state: " + newState);
12954                    return;
12955                }
12956            }
12957            scheduleWritePackageRestrictionsLocked(userId);
12958            components = mPendingBroadcasts.get(userId, packageName);
12959            final boolean newPackage = components == null;
12960            if (newPackage) {
12961                components = new ArrayList<String>();
12962            }
12963            if (!components.contains(componentName)) {
12964                components.add(componentName);
12965            }
12966            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12967                sendNow = true;
12968                // Purge entry from pending broadcast list if another one exists already
12969                // since we are sending one right away.
12970                mPendingBroadcasts.remove(userId, packageName);
12971            } else {
12972                if (newPackage) {
12973                    mPendingBroadcasts.put(userId, packageName, components);
12974                }
12975                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12976                    // Schedule a message
12977                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12978                }
12979            }
12980        }
12981
12982        long callingId = Binder.clearCallingIdentity();
12983        try {
12984            if (sendNow) {
12985                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12986                sendPackageChangedBroadcast(packageName,
12987                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12988            }
12989        } finally {
12990            Binder.restoreCallingIdentity(callingId);
12991        }
12992    }
12993
12994    private void sendPackageChangedBroadcast(String packageName,
12995            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12996        if (DEBUG_INSTALL)
12997            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12998                    + componentNames);
12999        Bundle extras = new Bundle(4);
13000        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13001        String nameList[] = new String[componentNames.size()];
13002        componentNames.toArray(nameList);
13003        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13004        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13005        extras.putInt(Intent.EXTRA_UID, packageUid);
13006        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13007                new int[] {UserHandle.getUserId(packageUid)});
13008    }
13009
13010    @Override
13011    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13012        if (!sUserManager.exists(userId)) return;
13013        final int uid = Binder.getCallingUid();
13014        final int permission = mContext.checkCallingOrSelfPermission(
13015                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13016        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13017        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13018        // writer
13019        synchronized (mPackages) {
13020            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
13021                    uid, userId)) {
13022                scheduleWritePackageRestrictionsLocked(userId);
13023            }
13024        }
13025    }
13026
13027    @Override
13028    public String getInstallerPackageName(String packageName) {
13029        // reader
13030        synchronized (mPackages) {
13031            return mSettings.getInstallerPackageNameLPr(packageName);
13032        }
13033    }
13034
13035    @Override
13036    public int getApplicationEnabledSetting(String packageName, int userId) {
13037        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13038        int uid = Binder.getCallingUid();
13039        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13040        // reader
13041        synchronized (mPackages) {
13042            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13043        }
13044    }
13045
13046    @Override
13047    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13048        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13049        int uid = Binder.getCallingUid();
13050        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13051        // reader
13052        synchronized (mPackages) {
13053            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13054        }
13055    }
13056
13057    @Override
13058    public void enterSafeMode() {
13059        enforceSystemOrRoot("Only the system can request entering safe mode");
13060
13061        if (!mSystemReady) {
13062            mSafeMode = true;
13063        }
13064    }
13065
13066    @Override
13067    public void systemReady() {
13068        mSystemReady = true;
13069
13070        // Read the compatibilty setting when the system is ready.
13071        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13072                mContext.getContentResolver(),
13073                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13074        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13075        if (DEBUG_SETTINGS) {
13076            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13077        }
13078
13079        synchronized (mPackages) {
13080            // Verify that all of the preferred activity components actually
13081            // exist.  It is possible for applications to be updated and at
13082            // that point remove a previously declared activity component that
13083            // had been set as a preferred activity.  We try to clean this up
13084            // the next time we encounter that preferred activity, but it is
13085            // possible for the user flow to never be able to return to that
13086            // situation so here we do a sanity check to make sure we haven't
13087            // left any junk around.
13088            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13089            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13090                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13091                removed.clear();
13092                for (PreferredActivity pa : pir.filterSet()) {
13093                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13094                        removed.add(pa);
13095                    }
13096                }
13097                if (removed.size() > 0) {
13098                    for (int r=0; r<removed.size(); r++) {
13099                        PreferredActivity pa = removed.get(r);
13100                        Slog.w(TAG, "Removing dangling preferred activity: "
13101                                + pa.mPref.mComponent);
13102                        pir.removeFilter(pa);
13103                    }
13104                    mSettings.writePackageRestrictionsLPr(
13105                            mSettings.mPreferredActivities.keyAt(i));
13106                }
13107            }
13108        }
13109        sUserManager.systemReady();
13110
13111        // Kick off any messages waiting for system ready
13112        if (mPostSystemReadyMessages != null) {
13113            for (Message msg : mPostSystemReadyMessages) {
13114                msg.sendToTarget();
13115            }
13116            mPostSystemReadyMessages = null;
13117        }
13118
13119        // Watch for external volumes that come and go over time
13120        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13121        storage.registerListener(mStorageListener);
13122
13123        mInstallerService.systemReady();
13124    }
13125
13126    @Override
13127    public boolean isSafeMode() {
13128        return mSafeMode;
13129    }
13130
13131    @Override
13132    public boolean hasSystemUidErrors() {
13133        return mHasSystemUidErrors;
13134    }
13135
13136    static String arrayToString(int[] array) {
13137        StringBuffer buf = new StringBuffer(128);
13138        buf.append('[');
13139        if (array != null) {
13140            for (int i=0; i<array.length; i++) {
13141                if (i > 0) buf.append(", ");
13142                buf.append(array[i]);
13143            }
13144        }
13145        buf.append(']');
13146        return buf.toString();
13147    }
13148
13149    static class DumpState {
13150        public static final int DUMP_LIBS = 1 << 0;
13151        public static final int DUMP_FEATURES = 1 << 1;
13152        public static final int DUMP_RESOLVERS = 1 << 2;
13153        public static final int DUMP_PERMISSIONS = 1 << 3;
13154        public static final int DUMP_PACKAGES = 1 << 4;
13155        public static final int DUMP_SHARED_USERS = 1 << 5;
13156        public static final int DUMP_MESSAGES = 1 << 6;
13157        public static final int DUMP_PROVIDERS = 1 << 7;
13158        public static final int DUMP_VERIFIERS = 1 << 8;
13159        public static final int DUMP_PREFERRED = 1 << 9;
13160        public static final int DUMP_PREFERRED_XML = 1 << 10;
13161        public static final int DUMP_KEYSETS = 1 << 11;
13162        public static final int DUMP_VERSION = 1 << 12;
13163        public static final int DUMP_INSTALLS = 1 << 13;
13164        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13165        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13166
13167        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13168
13169        private int mTypes;
13170
13171        private int mOptions;
13172
13173        private boolean mTitlePrinted;
13174
13175        private SharedUserSetting mSharedUser;
13176
13177        public boolean isDumping(int type) {
13178            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13179                return true;
13180            }
13181
13182            return (mTypes & type) != 0;
13183        }
13184
13185        public void setDump(int type) {
13186            mTypes |= type;
13187        }
13188
13189        public boolean isOptionEnabled(int option) {
13190            return (mOptions & option) != 0;
13191        }
13192
13193        public void setOptionEnabled(int option) {
13194            mOptions |= option;
13195        }
13196
13197        public boolean onTitlePrinted() {
13198            final boolean printed = mTitlePrinted;
13199            mTitlePrinted = true;
13200            return printed;
13201        }
13202
13203        public boolean getTitlePrinted() {
13204            return mTitlePrinted;
13205        }
13206
13207        public void setTitlePrinted(boolean enabled) {
13208            mTitlePrinted = enabled;
13209        }
13210
13211        public SharedUserSetting getSharedUser() {
13212            return mSharedUser;
13213        }
13214
13215        public void setSharedUser(SharedUserSetting user) {
13216            mSharedUser = user;
13217        }
13218    }
13219
13220    @Override
13221    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13222        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13223                != PackageManager.PERMISSION_GRANTED) {
13224            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13225                    + Binder.getCallingPid()
13226                    + ", uid=" + Binder.getCallingUid()
13227                    + " without permission "
13228                    + android.Manifest.permission.DUMP);
13229            return;
13230        }
13231
13232        DumpState dumpState = new DumpState();
13233        boolean fullPreferred = false;
13234        boolean checkin = false;
13235
13236        String packageName = null;
13237
13238        int opti = 0;
13239        while (opti < args.length) {
13240            String opt = args[opti];
13241            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13242                break;
13243            }
13244            opti++;
13245
13246            if ("-a".equals(opt)) {
13247                // Right now we only know how to print all.
13248            } else if ("-h".equals(opt)) {
13249                pw.println("Package manager dump options:");
13250                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13251                pw.println("    --checkin: dump for a checkin");
13252                pw.println("    -f: print details of intent filters");
13253                pw.println("    -h: print this help");
13254                pw.println("  cmd may be one of:");
13255                pw.println("    l[ibraries]: list known shared libraries");
13256                pw.println("    f[ibraries]: list device features");
13257                pw.println("    k[eysets]: print known keysets");
13258                pw.println("    r[esolvers]: dump intent resolvers");
13259                pw.println("    perm[issions]: dump permissions");
13260                pw.println("    pref[erred]: print preferred package settings");
13261                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13262                pw.println("    prov[iders]: dump content providers");
13263                pw.println("    p[ackages]: dump installed packages");
13264                pw.println("    s[hared-users]: dump shared user IDs");
13265                pw.println("    m[essages]: print collected runtime messages");
13266                pw.println("    v[erifiers]: print package verifier info");
13267                pw.println("    version: print database version info");
13268                pw.println("    write: write current settings now");
13269                pw.println("    <package.name>: info about given package");
13270                pw.println("    installs: details about install sessions");
13271                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13272                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13273                return;
13274            } else if ("--checkin".equals(opt)) {
13275                checkin = true;
13276            } else if ("-f".equals(opt)) {
13277                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13278            } else {
13279                pw.println("Unknown argument: " + opt + "; use -h for help");
13280            }
13281        }
13282
13283        // Is the caller requesting to dump a particular piece of data?
13284        if (opti < args.length) {
13285            String cmd = args[opti];
13286            opti++;
13287            // Is this a package name?
13288            if ("android".equals(cmd) || cmd.contains(".")) {
13289                packageName = cmd;
13290                // When dumping a single package, we always dump all of its
13291                // filter information since the amount of data will be reasonable.
13292                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13293            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13294                dumpState.setDump(DumpState.DUMP_LIBS);
13295            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13296                dumpState.setDump(DumpState.DUMP_FEATURES);
13297            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13298                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13299            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13300                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13301            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13302                dumpState.setDump(DumpState.DUMP_PREFERRED);
13303            } else if ("preferred-xml".equals(cmd)) {
13304                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13305                if (opti < args.length && "--full".equals(args[opti])) {
13306                    fullPreferred = true;
13307                    opti++;
13308                }
13309            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13310                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13311            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13312                dumpState.setDump(DumpState.DUMP_PACKAGES);
13313            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13314                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13315            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13316                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13317            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13318                dumpState.setDump(DumpState.DUMP_MESSAGES);
13319            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13320                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13321            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13322                    || "intent-filter-verifiers".equals(cmd)) {
13323                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13324            } else if ("version".equals(cmd)) {
13325                dumpState.setDump(DumpState.DUMP_VERSION);
13326            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13327                dumpState.setDump(DumpState.DUMP_KEYSETS);
13328            } else if ("installs".equals(cmd)) {
13329                dumpState.setDump(DumpState.DUMP_INSTALLS);
13330            } else if ("write".equals(cmd)) {
13331                synchronized (mPackages) {
13332                    mSettings.writeLPr();
13333                    pw.println("Settings written.");
13334                    return;
13335                }
13336            }
13337        }
13338
13339        if (checkin) {
13340            pw.println("vers,1");
13341        }
13342
13343        // reader
13344        synchronized (mPackages) {
13345            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13346                if (!checkin) {
13347                    if (dumpState.onTitlePrinted())
13348                        pw.println();
13349                    pw.println("Database versions:");
13350                    pw.print("  SDK Version:");
13351                    pw.print(" internal=");
13352                    pw.print(mSettings.mInternalSdkPlatform);
13353                    pw.print(" external=");
13354                    pw.println(mSettings.mExternalSdkPlatform);
13355                    pw.print("  DB Version:");
13356                    pw.print(" internal=");
13357                    pw.print(mSettings.mInternalDatabaseVersion);
13358                    pw.print(" external=");
13359                    pw.println(mSettings.mExternalDatabaseVersion);
13360                }
13361            }
13362
13363            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13364                if (!checkin) {
13365                    if (dumpState.onTitlePrinted())
13366                        pw.println();
13367                    pw.println("Verifiers:");
13368                    pw.print("  Required: ");
13369                    pw.print(mRequiredVerifierPackage);
13370                    pw.print(" (uid=");
13371                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13372                    pw.println(")");
13373                } else if (mRequiredVerifierPackage != null) {
13374                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13375                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13376                }
13377            }
13378
13379            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13380                    packageName == null) {
13381                if (mIntentFilterVerifierComponent != null) {
13382                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13383                    if (!checkin) {
13384                        if (dumpState.onTitlePrinted())
13385                            pw.println();
13386                        pw.println("Intent Filter Verifier:");
13387                        pw.print("  Using: ");
13388                        pw.print(verifierPackageName);
13389                        pw.print(" (uid=");
13390                        pw.print(getPackageUid(verifierPackageName, 0));
13391                        pw.println(")");
13392                    } else if (verifierPackageName != null) {
13393                        pw.print("ifv,"); pw.print(verifierPackageName);
13394                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13395                    }
13396                } else {
13397                    pw.println();
13398                    pw.println("No Intent Filter Verifier available!");
13399                }
13400            }
13401
13402            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13403                boolean printedHeader = false;
13404                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13405                while (it.hasNext()) {
13406                    String name = it.next();
13407                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13408                    if (!checkin) {
13409                        if (!printedHeader) {
13410                            if (dumpState.onTitlePrinted())
13411                                pw.println();
13412                            pw.println("Libraries:");
13413                            printedHeader = true;
13414                        }
13415                        pw.print("  ");
13416                    } else {
13417                        pw.print("lib,");
13418                    }
13419                    pw.print(name);
13420                    if (!checkin) {
13421                        pw.print(" -> ");
13422                    }
13423                    if (ent.path != null) {
13424                        if (!checkin) {
13425                            pw.print("(jar) ");
13426                            pw.print(ent.path);
13427                        } else {
13428                            pw.print(",jar,");
13429                            pw.print(ent.path);
13430                        }
13431                    } else {
13432                        if (!checkin) {
13433                            pw.print("(apk) ");
13434                            pw.print(ent.apk);
13435                        } else {
13436                            pw.print(",apk,");
13437                            pw.print(ent.apk);
13438                        }
13439                    }
13440                    pw.println();
13441                }
13442            }
13443
13444            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
13445                if (dumpState.onTitlePrinted())
13446                    pw.println();
13447                if (!checkin) {
13448                    pw.println("Features:");
13449                }
13450                Iterator<String> it = mAvailableFeatures.keySet().iterator();
13451                while (it.hasNext()) {
13452                    String name = it.next();
13453                    if (!checkin) {
13454                        pw.print("  ");
13455                    } else {
13456                        pw.print("feat,");
13457                    }
13458                    pw.println(name);
13459                }
13460            }
13461
13462            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
13463                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
13464                        : "Activity Resolver Table:", "  ", packageName,
13465                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13466                    dumpState.setTitlePrinted(true);
13467                }
13468                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
13469                        : "Receiver Resolver Table:", "  ", packageName,
13470                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13471                    dumpState.setTitlePrinted(true);
13472                }
13473                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
13474                        : "Service Resolver Table:", "  ", packageName,
13475                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13476                    dumpState.setTitlePrinted(true);
13477                }
13478                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
13479                        : "Provider Resolver Table:", "  ", packageName,
13480                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13481                    dumpState.setTitlePrinted(true);
13482                }
13483            }
13484
13485            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
13486                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13487                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13488                    int user = mSettings.mPreferredActivities.keyAt(i);
13489                    if (pir.dump(pw,
13490                            dumpState.getTitlePrinted()
13491                                ? "\nPreferred Activities User " + user + ":"
13492                                : "Preferred Activities User " + user + ":", "  ",
13493                            packageName, true, false)) {
13494                        dumpState.setTitlePrinted(true);
13495                    }
13496                }
13497            }
13498
13499            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
13500                pw.flush();
13501                FileOutputStream fout = new FileOutputStream(fd);
13502                BufferedOutputStream str = new BufferedOutputStream(fout);
13503                XmlSerializer serializer = new FastXmlSerializer();
13504                try {
13505                    serializer.setOutput(str, "utf-8");
13506                    serializer.startDocument(null, true);
13507                    serializer.setFeature(
13508                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
13509                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
13510                    serializer.endDocument();
13511                    serializer.flush();
13512                } catch (IllegalArgumentException e) {
13513                    pw.println("Failed writing: " + e);
13514                } catch (IllegalStateException e) {
13515                    pw.println("Failed writing: " + e);
13516                } catch (IOException e) {
13517                    pw.println("Failed writing: " + e);
13518                }
13519            }
13520
13521            if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) {
13522                pw.println();
13523                int count = mSettings.mPackages.size();
13524                if (count == 0) {
13525                    pw.println("No domain preferred apps!");
13526                    pw.println();
13527                } else {
13528                    final String prefix = "  ";
13529                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
13530                    if (allPackageSettings.size() == 0) {
13531                        pw.println("No domain preferred apps!");
13532                        pw.println();
13533                    } else {
13534                        pw.println("Domain preferred apps status:");
13535                        pw.println();
13536                        count = 0;
13537                        for (PackageSetting ps : allPackageSettings) {
13538                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13539                            if (ivi == null || ivi.getPackageName() == null) continue;
13540                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
13541                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
13542                            pw.println(prefix + "Status: " + ivi.getStatusString());
13543                            pw.println();
13544                            count++;
13545                        }
13546                        if (count == 0) {
13547                            pw.println(prefix + "No domain preferred app status!");
13548                            pw.println();
13549                        }
13550                        for (int userId : sUserManager.getUserIds()) {
13551                            pw.println("Domain preferred apps for User " + userId + ":");
13552                            pw.println();
13553                            count = 0;
13554                            for (PackageSetting ps : allPackageSettings) {
13555                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13556                                if (ivi == null || ivi.getPackageName() == null) {
13557                                    continue;
13558                                }
13559                                final int status = ps.getDomainVerificationStatusForUser(userId);
13560                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
13561                                    continue;
13562                                }
13563                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
13564                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
13565                                String statusStr = IntentFilterVerificationInfo.
13566                                        getStatusStringFromValue(status);
13567                                pw.println(prefix + "Status: " + statusStr);
13568                                pw.println();
13569                                count++;
13570                            }
13571                            if (count == 0) {
13572                                pw.println(prefix + "No domain preferred apps!");
13573                                pw.println();
13574                            }
13575                        }
13576                    }
13577                }
13578            }
13579
13580            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
13581                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
13582                if (packageName == null) {
13583                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
13584                        if (iperm == 0) {
13585                            if (dumpState.onTitlePrinted())
13586                                pw.println();
13587                            pw.println("AppOp Permissions:");
13588                        }
13589                        pw.print("  AppOp Permission ");
13590                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
13591                        pw.println(":");
13592                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
13593                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
13594                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
13595                        }
13596                    }
13597                }
13598            }
13599
13600            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
13601                boolean printedSomething = false;
13602                for (PackageParser.Provider p : mProviders.mProviders.values()) {
13603                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13604                        continue;
13605                    }
13606                    if (!printedSomething) {
13607                        if (dumpState.onTitlePrinted())
13608                            pw.println();
13609                        pw.println("Registered ContentProviders:");
13610                        printedSomething = true;
13611                    }
13612                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
13613                    pw.print("    "); pw.println(p.toString());
13614                }
13615                printedSomething = false;
13616                for (Map.Entry<String, PackageParser.Provider> entry :
13617                        mProvidersByAuthority.entrySet()) {
13618                    PackageParser.Provider p = entry.getValue();
13619                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13620                        continue;
13621                    }
13622                    if (!printedSomething) {
13623                        if (dumpState.onTitlePrinted())
13624                            pw.println();
13625                        pw.println("ContentProvider Authorities:");
13626                        printedSomething = true;
13627                    }
13628                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
13629                    pw.print("    "); pw.println(p.toString());
13630                    if (p.info != null && p.info.applicationInfo != null) {
13631                        final String appInfo = p.info.applicationInfo.toString();
13632                        pw.print("      applicationInfo="); pw.println(appInfo);
13633                    }
13634                }
13635            }
13636
13637            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
13638                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
13639            }
13640
13641            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
13642                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
13643            }
13644
13645            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
13646                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
13647            }
13648
13649            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
13650                // XXX should handle packageName != null by dumping only install data that
13651                // the given package is involved with.
13652                if (dumpState.onTitlePrinted()) pw.println();
13653                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
13654            }
13655
13656            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
13657                if (dumpState.onTitlePrinted()) pw.println();
13658                mSettings.dumpReadMessagesLPr(pw, dumpState);
13659
13660                pw.println();
13661                pw.println("Package warning messages:");
13662                BufferedReader in = null;
13663                String line = null;
13664                try {
13665                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
13666                    while ((line = in.readLine()) != null) {
13667                        if (line.contains("ignored: updated version")) continue;
13668                        pw.println(line);
13669                    }
13670                } catch (IOException ignored) {
13671                } finally {
13672                    IoUtils.closeQuietly(in);
13673                }
13674            }
13675
13676            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
13677                BufferedReader in = null;
13678                String line = null;
13679                try {
13680                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
13681                    while ((line = in.readLine()) != null) {
13682                        if (line.contains("ignored: updated version")) continue;
13683                        pw.print("msg,");
13684                        pw.println(line);
13685                    }
13686                } catch (IOException ignored) {
13687                } finally {
13688                    IoUtils.closeQuietly(in);
13689                }
13690            }
13691        }
13692    }
13693
13694    // ------- apps on sdcard specific code -------
13695    static final boolean DEBUG_SD_INSTALL = false;
13696
13697    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
13698
13699    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
13700
13701    private boolean mMediaMounted = false;
13702
13703    static String getEncryptKey() {
13704        try {
13705            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
13706                    SD_ENCRYPTION_KEYSTORE_NAME);
13707            if (sdEncKey == null) {
13708                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
13709                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
13710                if (sdEncKey == null) {
13711                    Slog.e(TAG, "Failed to create encryption keys");
13712                    return null;
13713                }
13714            }
13715            return sdEncKey;
13716        } catch (NoSuchAlgorithmException nsae) {
13717            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
13718            return null;
13719        } catch (IOException ioe) {
13720            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
13721            return null;
13722        }
13723    }
13724
13725    /*
13726     * Update media status on PackageManager.
13727     */
13728    @Override
13729    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
13730        int callingUid = Binder.getCallingUid();
13731        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
13732            throw new SecurityException("Media status can only be updated by the system");
13733        }
13734        // reader; this apparently protects mMediaMounted, but should probably
13735        // be a different lock in that case.
13736        synchronized (mPackages) {
13737            Log.i(TAG, "Updating external media status from "
13738                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
13739                    + (mediaStatus ? "mounted" : "unmounted"));
13740            if (DEBUG_SD_INSTALL)
13741                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
13742                        + ", mMediaMounted=" + mMediaMounted);
13743            if (mediaStatus == mMediaMounted) {
13744                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
13745                        : 0, -1);
13746                mHandler.sendMessage(msg);
13747                return;
13748            }
13749            mMediaMounted = mediaStatus;
13750        }
13751        // Queue up an async operation since the package installation may take a
13752        // little while.
13753        mHandler.post(new Runnable() {
13754            public void run() {
13755                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
13756            }
13757        });
13758    }
13759
13760    /**
13761     * Called by MountService when the initial ASECs to scan are available.
13762     * Should block until all the ASEC containers are finished being scanned.
13763     */
13764    public void scanAvailableAsecs() {
13765        updateExternalMediaStatusInner(true, false, false);
13766        if (mShouldRestoreconData) {
13767            SELinuxMMAC.setRestoreconDone();
13768            mShouldRestoreconData = false;
13769        }
13770    }
13771
13772    /*
13773     * Collect information of applications on external media, map them against
13774     * existing containers and update information based on current mount status.
13775     * Please note that we always have to report status if reportStatus has been
13776     * set to true especially when unloading packages.
13777     */
13778    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
13779            boolean externalStorage) {
13780        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
13781        int[] uidArr = EmptyArray.INT;
13782
13783        final String[] list = PackageHelper.getSecureContainerList();
13784        if (ArrayUtils.isEmpty(list)) {
13785            Log.i(TAG, "No secure containers found");
13786        } else {
13787            // Process list of secure containers and categorize them
13788            // as active or stale based on their package internal state.
13789
13790            // reader
13791            synchronized (mPackages) {
13792                for (String cid : list) {
13793                    // Leave stages untouched for now; installer service owns them
13794                    if (PackageInstallerService.isStageName(cid)) continue;
13795
13796                    if (DEBUG_SD_INSTALL)
13797                        Log.i(TAG, "Processing container " + cid);
13798                    String pkgName = getAsecPackageName(cid);
13799                    if (pkgName == null) {
13800                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
13801                        continue;
13802                    }
13803                    if (DEBUG_SD_INSTALL)
13804                        Log.i(TAG, "Looking for pkg : " + pkgName);
13805
13806                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
13807                    if (ps == null) {
13808                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
13809                        continue;
13810                    }
13811
13812                    /*
13813                     * Skip packages that are not external if we're unmounting
13814                     * external storage.
13815                     */
13816                    if (externalStorage && !isMounted && !isExternal(ps)) {
13817                        continue;
13818                    }
13819
13820                    final AsecInstallArgs args = new AsecInstallArgs(cid,
13821                            getAppDexInstructionSets(ps), ps.isForwardLocked());
13822                    // The package status is changed only if the code path
13823                    // matches between settings and the container id.
13824                    if (ps.codePathString != null
13825                            && ps.codePathString.startsWith(args.getCodePath())) {
13826                        if (DEBUG_SD_INSTALL) {
13827                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
13828                                    + " at code path: " + ps.codePathString);
13829                        }
13830
13831                        // We do have a valid package installed on sdcard
13832                        processCids.put(args, ps.codePathString);
13833                        final int uid = ps.appId;
13834                        if (uid != -1) {
13835                            uidArr = ArrayUtils.appendInt(uidArr, uid);
13836                        }
13837                    } else {
13838                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
13839                                + ps.codePathString);
13840                    }
13841                }
13842            }
13843
13844            Arrays.sort(uidArr);
13845        }
13846
13847        // Process packages with valid entries.
13848        if (isMounted) {
13849            if (DEBUG_SD_INSTALL)
13850                Log.i(TAG, "Loading packages");
13851            loadMediaPackages(processCids, uidArr);
13852            startCleaningPackages();
13853            mInstallerService.onSecureContainersAvailable();
13854        } else {
13855            if (DEBUG_SD_INSTALL)
13856                Log.i(TAG, "Unloading packages");
13857            unloadMediaPackages(processCids, uidArr, reportStatus);
13858        }
13859    }
13860
13861    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13862            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
13863        final int size = infos.size();
13864        final String[] packageNames = new String[size];
13865        final int[] packageUids = new int[size];
13866        for (int i = 0; i < size; i++) {
13867            final ApplicationInfo info = infos.get(i);
13868            packageNames[i] = info.packageName;
13869            packageUids[i] = info.uid;
13870        }
13871        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
13872                finishedReceiver);
13873    }
13874
13875    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13876            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
13877        sendResourcesChangedBroadcast(mediaStatus, replacing,
13878                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
13879    }
13880
13881    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13882            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
13883        int size = pkgList.length;
13884        if (size > 0) {
13885            // Send broadcasts here
13886            Bundle extras = new Bundle();
13887            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13888            if (uidArr != null) {
13889                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
13890            }
13891            if (replacing) {
13892                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
13893            }
13894            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
13895                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
13896            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
13897        }
13898    }
13899
13900   /*
13901     * Look at potentially valid container ids from processCids If package
13902     * information doesn't match the one on record or package scanning fails,
13903     * the cid is added to list of removeCids. We currently don't delete stale
13904     * containers.
13905     */
13906    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
13907        ArrayList<String> pkgList = new ArrayList<String>();
13908        Set<AsecInstallArgs> keys = processCids.keySet();
13909
13910        for (AsecInstallArgs args : keys) {
13911            String codePath = processCids.get(args);
13912            if (DEBUG_SD_INSTALL)
13913                Log.i(TAG, "Loading container : " + args.cid);
13914            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13915            try {
13916                // Make sure there are no container errors first.
13917                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
13918                    Slog.e(TAG, "Failed to mount cid : " + args.cid
13919                            + " when installing from sdcard");
13920                    continue;
13921                }
13922                // Check code path here.
13923                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
13924                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
13925                            + " does not match one in settings " + codePath);
13926                    continue;
13927                }
13928                // Parse package
13929                int parseFlags = mDefParseFlags;
13930                if (args.isExternalAsec()) {
13931                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
13932                }
13933                if (args.isFwdLocked()) {
13934                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
13935                }
13936
13937                synchronized (mInstallLock) {
13938                    PackageParser.Package pkg = null;
13939                    try {
13940                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
13941                    } catch (PackageManagerException e) {
13942                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
13943                    }
13944                    // Scan the package
13945                    if (pkg != null) {
13946                        /*
13947                         * TODO why is the lock being held? doPostInstall is
13948                         * called in other places without the lock. This needs
13949                         * to be straightened out.
13950                         */
13951                        // writer
13952                        synchronized (mPackages) {
13953                            retCode = PackageManager.INSTALL_SUCCEEDED;
13954                            pkgList.add(pkg.packageName);
13955                            // Post process args
13956                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
13957                                    pkg.applicationInfo.uid);
13958                        }
13959                    } else {
13960                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
13961                    }
13962                }
13963
13964            } finally {
13965                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
13966                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
13967                }
13968            }
13969        }
13970        // writer
13971        synchronized (mPackages) {
13972            // If the platform SDK has changed since the last time we booted,
13973            // we need to re-grant app permission to catch any new ones that
13974            // appear. This is really a hack, and means that apps can in some
13975            // cases get permissions that the user didn't initially explicitly
13976            // allow... it would be nice to have some better way to handle
13977            // this situation.
13978            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
13979            if (regrantPermissions)
13980                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
13981                        + mSdkVersion + "; regranting permissions for external storage");
13982            mSettings.mExternalSdkPlatform = mSdkVersion;
13983
13984            // Make sure group IDs have been assigned, and any permission
13985            // changes in other apps are accounted for
13986            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
13987                    | (regrantPermissions
13988                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
13989                            : 0));
13990
13991            mSettings.updateExternalDatabaseVersion();
13992
13993            // can downgrade to reader
13994            // Persist settings
13995            mSettings.writeLPr();
13996        }
13997        // Send a broadcast to let everyone know we are done processing
13998        if (pkgList.size() > 0) {
13999            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14000        }
14001    }
14002
14003   /*
14004     * Utility method to unload a list of specified containers
14005     */
14006    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14007        // Just unmount all valid containers.
14008        for (AsecInstallArgs arg : cidArgs) {
14009            synchronized (mInstallLock) {
14010                arg.doPostDeleteLI(false);
14011           }
14012       }
14013   }
14014
14015    /*
14016     * Unload packages mounted on external media. This involves deleting package
14017     * data from internal structures, sending broadcasts about diabled packages,
14018     * gc'ing to free up references, unmounting all secure containers
14019     * corresponding to packages on external media, and posting a
14020     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14021     * that we always have to post this message if status has been requested no
14022     * matter what.
14023     */
14024    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14025            final boolean reportStatus) {
14026        if (DEBUG_SD_INSTALL)
14027            Log.i(TAG, "unloading media packages");
14028        ArrayList<String> pkgList = new ArrayList<String>();
14029        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14030        final Set<AsecInstallArgs> keys = processCids.keySet();
14031        for (AsecInstallArgs args : keys) {
14032            String pkgName = args.getPackageName();
14033            if (DEBUG_SD_INSTALL)
14034                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14035            // Delete package internally
14036            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14037            synchronized (mInstallLock) {
14038                boolean res = deletePackageLI(pkgName, null, false, null, null,
14039                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14040                if (res) {
14041                    pkgList.add(pkgName);
14042                } else {
14043                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14044                    failedList.add(args);
14045                }
14046            }
14047        }
14048
14049        // reader
14050        synchronized (mPackages) {
14051            // We didn't update the settings after removing each package;
14052            // write them now for all packages.
14053            mSettings.writeLPr();
14054        }
14055
14056        // We have to absolutely send UPDATED_MEDIA_STATUS only
14057        // after confirming that all the receivers processed the ordered
14058        // broadcast when packages get disabled, force a gc to clean things up.
14059        // and unload all the containers.
14060        if (pkgList.size() > 0) {
14061            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14062                    new IIntentReceiver.Stub() {
14063                public void performReceive(Intent intent, int resultCode, String data,
14064                        Bundle extras, boolean ordered, boolean sticky,
14065                        int sendingUser) throws RemoteException {
14066                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14067                            reportStatus ? 1 : 0, 1, keys);
14068                    mHandler.sendMessage(msg);
14069                }
14070            });
14071        } else {
14072            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14073                    keys);
14074            mHandler.sendMessage(msg);
14075        }
14076    }
14077
14078    private void loadPrivatePackages(VolumeInfo vol) {
14079        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14080        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14081        synchronized (mPackages) {
14082            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14083            for (PackageSetting ps : packages) {
14084                synchronized (mInstallLock) {
14085                    final PackageParser.Package pkg;
14086                    try {
14087                        pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14088                        loaded.add(pkg.applicationInfo);
14089                    } catch (PackageManagerException e) {
14090                        Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14091                    }
14092                }
14093            }
14094
14095            // TODO: regrant any permissions that changed based since original install
14096
14097            mSettings.writeLPr();
14098        }
14099
14100        Slog.d(TAG, "Loaded packages " + loaded);
14101        sendResourcesChangedBroadcast(true, false, loaded, null);
14102    }
14103
14104    private void unloadPrivatePackages(VolumeInfo vol) {
14105        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14106        synchronized (mPackages) {
14107            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14108            for (PackageSetting ps : packages) {
14109                if (ps.pkg == null) continue;
14110                synchronized (mInstallLock) {
14111                    final ApplicationInfo info = ps.pkg.applicationInfo;
14112                    final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14113                    if (deletePackageLI(ps.name, null, false, null, null,
14114                            PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14115                        unloaded.add(info);
14116                    } else {
14117                        Slog.w(TAG, "Failed to unload " + ps.codePath);
14118                    }
14119                }
14120            }
14121
14122            mSettings.writeLPr();
14123        }
14124
14125        Slog.d(TAG, "Unloaded packages " + unloaded);
14126        sendResourcesChangedBroadcast(false, false, unloaded, null);
14127    }
14128
14129    @Override
14130    public void movePackage(final String packageName, final IPackageMoveObserver observer,
14131            final int flags) {
14132        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14133
14134        final int installFlags;
14135        if ((flags & MOVE_INTERNAL) != 0) {
14136            installFlags = INSTALL_INTERNAL;
14137        } else if ((flags & MOVE_EXTERNAL_MEDIA) != 0) {
14138            installFlags = INSTALL_EXTERNAL;
14139        } else {
14140            throw new IllegalArgumentException("Unsupported move flags " + flags);
14141        }
14142
14143        try {
14144            movePackageInternal(packageName, null, installFlags, false, observer);
14145        } catch (PackageManagerException e) {
14146            Slog.d(TAG, "Failed to move " + packageName, e);
14147            try {
14148                observer.packageMoved(packageName, e.error);
14149            } catch (RemoteException ignored) {
14150            }
14151        }
14152    }
14153
14154    @Override
14155    public void movePackageAndData(final String packageName, final String volumeUuid,
14156            final IPackageMoveObserver observer) {
14157        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14158        try {
14159            movePackageInternal(packageName, volumeUuid, INSTALL_INTERNAL, true, observer);
14160        } catch (PackageManagerException e) {
14161            Slog.d(TAG, "Failed to move " + packageName, e);
14162            try {
14163                observer.packageMoved(packageName, e.error);
14164            } catch (RemoteException ignored) {
14165            }
14166        }
14167    }
14168
14169    private void movePackageInternal(final String packageName, String volumeUuid, int installFlags,
14170            boolean andData, final IPackageMoveObserver observer) throws PackageManagerException {
14171        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14172
14173        final String currentVolumeUuid;
14174        final File codeFile;
14175        final String installerPackageName;
14176        final String packageAbiOverride;
14177        final int appId;
14178        final String seinfo;
14179
14180        // reader
14181        synchronized (mPackages) {
14182            final PackageParser.Package pkg = mPackages.get(packageName);
14183            final PackageSetting ps = mSettings.mPackages.get(packageName);
14184            if (pkg == null || ps == null) {
14185                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14186            }
14187
14188            if (pkg.applicationInfo.isSystemApp()) {
14189                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14190                        "Cannot move system application");
14191            } else if (pkg.mOperationPending) {
14192                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14193                        "Attempt to move package which has pending operations");
14194            }
14195
14196            // TODO: yell if already in desired location
14197
14198            pkg.mOperationPending = true;
14199
14200            currentVolumeUuid = ps.volumeUuid;
14201            codeFile = new File(pkg.codePath);
14202            installerPackageName = ps.installerPackageName;
14203            packageAbiOverride = ps.cpuAbiOverrideString;
14204            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14205            seinfo = pkg.applicationInfo.seinfo;
14206        }
14207
14208        if (andData) {
14209            Slog.d(TAG, "Moving " + packageName + " private data from " + currentVolumeUuid + " to "
14210                    + volumeUuid);
14211            synchronized (mInstallLock) {
14212                if (mInstaller.moveUserDataDirs(currentVolumeUuid, volumeUuid, packageName, appId,
14213                        seinfo) != 0) {
14214                    synchronized (mPackages) {
14215                        final PackageParser.Package pkg = mPackages.get(packageName);
14216                        if (pkg != null) {
14217                            pkg.mOperationPending = false;
14218                        }
14219                    }
14220
14221                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14222                            "Failed to move private data");
14223                }
14224            }
14225        }
14226
14227        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14228            @Override
14229            public void onUserActionRequired(Intent intent) throws RemoteException {
14230                throw new IllegalStateException();
14231            }
14232
14233            @Override
14234            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14235                    Bundle extras) throws RemoteException {
14236                Slog.d(TAG, "Install result for move: "
14237                        + PackageManager.installStatusToString(returnCode, msg));
14238
14239                // We usually have a new package now after the install, but if
14240                // we failed we need to clear the pending flag on the original
14241                // package object.
14242                synchronized (mPackages) {
14243                    final PackageParser.Package pkg = mPackages.get(packageName);
14244                    if (pkg != null) {
14245                        pkg.mOperationPending = false;
14246                    }
14247                }
14248
14249                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14250                switch (status) {
14251                    case PackageInstaller.STATUS_SUCCESS:
14252                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
14253                        break;
14254                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14255                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14256                        break;
14257                    default:
14258                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14259                        break;
14260                }
14261            }
14262        };
14263
14264        // Treat a move like reinstalling an existing app, which ensures that we
14265        // process everythign uniformly, like unpacking native libraries.
14266        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14267
14268        final Message msg = mHandler.obtainMessage(INIT_COPY);
14269        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14270        msg.obj = new InstallParams(origin, installObserver, installFlags,
14271                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14272        mHandler.sendMessage(msg);
14273    }
14274
14275    @Override
14276    public boolean setInstallLocation(int loc) {
14277        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14278                null);
14279        if (getInstallLocation() == loc) {
14280            return true;
14281        }
14282        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14283                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14284            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14285                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14286            return true;
14287        }
14288        return false;
14289   }
14290
14291    @Override
14292    public int getInstallLocation() {
14293        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14294                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14295                PackageHelper.APP_INSTALL_AUTO);
14296    }
14297
14298    /** Called by UserManagerService */
14299    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14300        mDirtyUsers.remove(userHandle);
14301        mSettings.removeUserLPw(userHandle);
14302        mPendingBroadcasts.remove(userHandle);
14303        if (mInstaller != null) {
14304            // Technically, we shouldn't be doing this with the package lock
14305            // held.  However, this is very rare, and there is already so much
14306            // other disk I/O going on, that we'll let it slide for now.
14307            mInstaller.removeUserDataDirs(userHandle);
14308        }
14309        mUserNeedsBadging.delete(userHandle);
14310        removeUnusedPackagesLILPw(userManager, userHandle);
14311    }
14312
14313    /**
14314     * We're removing userHandle and would like to remove any downloaded packages
14315     * that are no longer in use by any other user.
14316     * @param userHandle the user being removed
14317     */
14318    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
14319        final boolean DEBUG_CLEAN_APKS = false;
14320        int [] users = userManager.getUserIdsLPr();
14321        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
14322        while (psit.hasNext()) {
14323            PackageSetting ps = psit.next();
14324            if (ps.pkg == null) {
14325                continue;
14326            }
14327            final String packageName = ps.pkg.packageName;
14328            // Skip over if system app
14329            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14330                continue;
14331            }
14332            if (DEBUG_CLEAN_APKS) {
14333                Slog.i(TAG, "Checking package " + packageName);
14334            }
14335            boolean keep = false;
14336            for (int i = 0; i < users.length; i++) {
14337                if (users[i] != userHandle && ps.getInstalled(users[i])) {
14338                    keep = true;
14339                    if (DEBUG_CLEAN_APKS) {
14340                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
14341                                + users[i]);
14342                    }
14343                    break;
14344                }
14345            }
14346            if (!keep) {
14347                if (DEBUG_CLEAN_APKS) {
14348                    Slog.i(TAG, "  Removing package " + packageName);
14349                }
14350                mHandler.post(new Runnable() {
14351                    public void run() {
14352                        deletePackageX(packageName, userHandle, 0);
14353                    } //end run
14354                });
14355            }
14356        }
14357    }
14358
14359    /** Called by UserManagerService */
14360    void createNewUserLILPw(int userHandle, File path) {
14361        if (mInstaller != null) {
14362            mInstaller.createUserConfig(userHandle);
14363            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
14364        }
14365    }
14366
14367    void newUserCreatedLILPw(int userHandle) {
14368        // Adding a user requires updating runtime permissions for system apps.
14369        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
14370    }
14371
14372    @Override
14373    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
14374        mContext.enforceCallingOrSelfPermission(
14375                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14376                "Only package verification agents can read the verifier device identity");
14377
14378        synchronized (mPackages) {
14379            return mSettings.getVerifierDeviceIdentityLPw();
14380        }
14381    }
14382
14383    @Override
14384    public void setPermissionEnforced(String permission, boolean enforced) {
14385        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
14386        if (READ_EXTERNAL_STORAGE.equals(permission)) {
14387            synchronized (mPackages) {
14388                if (mSettings.mReadExternalStorageEnforced == null
14389                        || mSettings.mReadExternalStorageEnforced != enforced) {
14390                    mSettings.mReadExternalStorageEnforced = enforced;
14391                    mSettings.writeLPr();
14392                }
14393            }
14394            // kill any non-foreground processes so we restart them and
14395            // grant/revoke the GID.
14396            final IActivityManager am = ActivityManagerNative.getDefault();
14397            if (am != null) {
14398                final long token = Binder.clearCallingIdentity();
14399                try {
14400                    am.killProcessesBelowForeground("setPermissionEnforcement");
14401                } catch (RemoteException e) {
14402                } finally {
14403                    Binder.restoreCallingIdentity(token);
14404                }
14405            }
14406        } else {
14407            throw new IllegalArgumentException("No selective enforcement for " + permission);
14408        }
14409    }
14410
14411    @Override
14412    @Deprecated
14413    public boolean isPermissionEnforced(String permission) {
14414        return true;
14415    }
14416
14417    @Override
14418    public boolean isStorageLow() {
14419        final long token = Binder.clearCallingIdentity();
14420        try {
14421            final DeviceStorageMonitorInternal
14422                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14423            if (dsm != null) {
14424                return dsm.isMemoryLow();
14425            } else {
14426                return false;
14427            }
14428        } finally {
14429            Binder.restoreCallingIdentity(token);
14430        }
14431    }
14432
14433    @Override
14434    public IPackageInstaller getPackageInstaller() {
14435        return mInstallerService;
14436    }
14437
14438    private boolean userNeedsBadging(int userId) {
14439        int index = mUserNeedsBadging.indexOfKey(userId);
14440        if (index < 0) {
14441            final UserInfo userInfo;
14442            final long token = Binder.clearCallingIdentity();
14443            try {
14444                userInfo = sUserManager.getUserInfo(userId);
14445            } finally {
14446                Binder.restoreCallingIdentity(token);
14447            }
14448            final boolean b;
14449            if (userInfo != null && userInfo.isManagedProfile()) {
14450                b = true;
14451            } else {
14452                b = false;
14453            }
14454            mUserNeedsBadging.put(userId, b);
14455            return b;
14456        }
14457        return mUserNeedsBadging.valueAt(index);
14458    }
14459
14460    @Override
14461    public KeySet getKeySetByAlias(String packageName, String alias) {
14462        if (packageName == null || alias == null) {
14463            return null;
14464        }
14465        synchronized(mPackages) {
14466            final PackageParser.Package pkg = mPackages.get(packageName);
14467            if (pkg == null) {
14468                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14469                throw new IllegalArgumentException("Unknown package: " + packageName);
14470            }
14471            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14472            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
14473        }
14474    }
14475
14476    @Override
14477    public KeySet getSigningKeySet(String packageName) {
14478        if (packageName == null) {
14479            return null;
14480        }
14481        synchronized(mPackages) {
14482            final PackageParser.Package pkg = mPackages.get(packageName);
14483            if (pkg == null) {
14484                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14485                throw new IllegalArgumentException("Unknown package: " + packageName);
14486            }
14487            if (pkg.applicationInfo.uid != Binder.getCallingUid()
14488                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
14489                throw new SecurityException("May not access signing KeySet of other apps.");
14490            }
14491            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14492            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
14493        }
14494    }
14495
14496    @Override
14497    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
14498        if (packageName == null || ks == null) {
14499            return false;
14500        }
14501        synchronized(mPackages) {
14502            final PackageParser.Package pkg = mPackages.get(packageName);
14503            if (pkg == null) {
14504                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14505                throw new IllegalArgumentException("Unknown package: " + packageName);
14506            }
14507            IBinder ksh = ks.getToken();
14508            if (ksh instanceof KeySetHandle) {
14509                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14510                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
14511            }
14512            return false;
14513        }
14514    }
14515
14516    @Override
14517    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
14518        if (packageName == null || ks == null) {
14519            return false;
14520        }
14521        synchronized(mPackages) {
14522            final PackageParser.Package pkg = mPackages.get(packageName);
14523            if (pkg == null) {
14524                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14525                throw new IllegalArgumentException("Unknown package: " + packageName);
14526            }
14527            IBinder ksh = ks.getToken();
14528            if (ksh instanceof KeySetHandle) {
14529                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14530                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
14531            }
14532            return false;
14533        }
14534    }
14535
14536    public void getUsageStatsIfNoPackageUsageInfo() {
14537        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
14538            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
14539            if (usm == null) {
14540                throw new IllegalStateException("UsageStatsManager must be initialized");
14541            }
14542            long now = System.currentTimeMillis();
14543            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
14544            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
14545                String packageName = entry.getKey();
14546                PackageParser.Package pkg = mPackages.get(packageName);
14547                if (pkg == null) {
14548                    continue;
14549                }
14550                UsageStats usage = entry.getValue();
14551                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
14552                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
14553            }
14554        }
14555    }
14556
14557    /**
14558     * Check and throw if the given before/after packages would be considered a
14559     * downgrade.
14560     */
14561    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
14562            throws PackageManagerException {
14563        if (after.versionCode < before.mVersionCode) {
14564            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14565                    "Update version code " + after.versionCode + " is older than current "
14566                    + before.mVersionCode);
14567        } else if (after.versionCode == before.mVersionCode) {
14568            if (after.baseRevisionCode < before.baseRevisionCode) {
14569                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14570                        "Update base revision code " + after.baseRevisionCode
14571                        + " is older than current " + before.baseRevisionCode);
14572            }
14573
14574            if (!ArrayUtils.isEmpty(after.splitNames)) {
14575                for (int i = 0; i < after.splitNames.length; i++) {
14576                    final String splitName = after.splitNames[i];
14577                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
14578                    if (j != -1) {
14579                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
14580                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14581                                    "Update split " + splitName + " revision code "
14582                                    + after.splitRevisionCodes[i] + " is older than current "
14583                                    + before.splitRevisionCodes[j]);
14584                        }
14585                    }
14586                }
14587            }
14588        }
14589    }
14590}
14591