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