PackageManagerService.java revision e48c137acdddd477d671417eb93ec120a1931cbb
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_OPERATION_PENDING;
55import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
56import static android.content.pm.PackageManager.MOVE_INTERNAL;
57import static android.content.pm.PackageParser.isApkFile;
58import static android.os.Process.PACKAGE_INFO_GID;
59import static android.os.Process.SYSTEM_UID;
60import static android.system.OsConstants.O_CREAT;
61import static android.system.OsConstants.O_RDWR;
62import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
64import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
65import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
66import static com.android.internal.util.ArrayUtils.appendInt;
67import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
68import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
70import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
71import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
72
73import android.Manifest;
74import org.xmlpull.v1.XmlPullParser;
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.XmlSerializer;
206
207import java.io.BufferedInputStream;
208import java.io.BufferedOutputStream;
209import java.io.BufferedReader;
210import java.io.ByteArrayInputStream;
211import java.io.ByteArrayOutputStream;
212import java.io.File;
213import java.io.FileDescriptor;
214import java.io.FileNotFoundException;
215import java.io.FileOutputStream;
216import java.io.FileReader;
217import java.io.FilenameFilter;
218import java.io.IOException;
219import java.io.InputStream;
220import java.io.PrintWriter;
221import java.nio.charset.StandardCharsets;
222import java.security.NoSuchAlgorithmException;
223import java.security.PublicKey;
224import java.security.cert.CertificateEncodingException;
225import java.security.cert.CertificateException;
226import java.text.SimpleDateFormat;
227import java.util.ArrayList;
228import java.util.Arrays;
229import java.util.Collection;
230import java.util.Collections;
231import java.util.Comparator;
232import java.util.Date;
233import java.util.Iterator;
234import java.util.List;
235import java.util.Map;
236import java.util.Objects;
237import java.util.Set;
238import java.util.concurrent.atomic.AtomicBoolean;
239import java.util.concurrent.atomic.AtomicLong;
240
241/**
242 * Keep track of all those .apks everywhere.
243 *
244 * This is very central to the platform's security; please run the unit
245 * tests whenever making modifications here:
246 *
247mmm frameworks/base/tests/AndroidTests
248adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
249adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
250 *
251 * {@hide}
252 */
253public class PackageManagerService extends IPackageManager.Stub {
254    static final String TAG = "PackageManager";
255    static final boolean DEBUG_SETTINGS = false;
256    static final boolean DEBUG_PREFERRED = false;
257    static final boolean DEBUG_UPGRADE = false;
258    private static final boolean DEBUG_BACKUP = true;
259    private static final boolean DEBUG_INSTALL = false;
260    private static final boolean DEBUG_REMOVE = false;
261    private static final boolean DEBUG_BROADCASTS = false;
262    private static final boolean DEBUG_SHOW_INFO = false;
263    private static final boolean DEBUG_PACKAGE_INFO = false;
264    private static final boolean DEBUG_INTENT_MATCHING = false;
265    private static final boolean DEBUG_PACKAGE_SCANNING = false;
266    private static final boolean DEBUG_VERIFY = false;
267    private static final boolean DEBUG_DEXOPT = false;
268    private static final boolean DEBUG_ABI_SELECTION = false;
269
270    static final boolean RUNTIME_PERMISSIONS_ENABLED = true;
271
272    private static final int RADIO_UID = Process.PHONE_UID;
273    private static final int LOG_UID = Process.LOG_UID;
274    private static final int NFC_UID = Process.NFC_UID;
275    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
276    private static final int SHELL_UID = Process.SHELL_UID;
277
278    // Cap the size of permission trees that 3rd party apps can define
279    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
280
281    // Suffix used during package installation when copying/moving
282    // package apks to install directory.
283    private static final String INSTALL_PACKAGE_SUFFIX = "-";
284
285    static final int SCAN_NO_DEX = 1<<1;
286    static final int SCAN_FORCE_DEX = 1<<2;
287    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
288    static final int SCAN_NEW_INSTALL = 1<<4;
289    static final int SCAN_NO_PATHS = 1<<5;
290    static final int SCAN_UPDATE_TIME = 1<<6;
291    static final int SCAN_DEFER_DEX = 1<<7;
292    static final int SCAN_BOOTING = 1<<8;
293    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
294    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
295    static final int SCAN_REPLACING = 1<<11;
296    static final int SCAN_REQUIRE_KNOWN = 1<<12;
297
298    static final int REMOVE_CHATTY = 1<<16;
299
300    /**
301     * Timeout (in milliseconds) after which the watchdog should declare that
302     * our handler thread is wedged.  The usual default for such things is one
303     * minute but we sometimes do very lengthy I/O operations on this thread,
304     * such as installing multi-gigabyte applications, so ours needs to be longer.
305     */
306    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
307
308    /**
309     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
310     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
311     * settings entry if available, otherwise we use the hardcoded default.  If it's been
312     * more than this long since the last fstrim, we force one during the boot sequence.
313     *
314     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
315     * one gets run at the next available charging+idle time.  This final mandatory
316     * no-fstrim check kicks in only of the other scheduling criteria is never met.
317     */
318    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
319
320    /**
321     * Whether verification is enabled by default.
322     */
323    private static final boolean DEFAULT_VERIFY_ENABLE = true;
324
325    /**
326     * The default maximum time to wait for the verification agent to return in
327     * milliseconds.
328     */
329    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
330
331    /**
332     * The default response for package verification timeout.
333     *
334     * This can be either PackageManager.VERIFICATION_ALLOW or
335     * PackageManager.VERIFICATION_REJECT.
336     */
337    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
338
339    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
340
341    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
342            DEFAULT_CONTAINER_PACKAGE,
343            "com.android.defcontainer.DefaultContainerService");
344
345    private static final String KILL_APP_REASON_GIDS_CHANGED =
346            "permission grant or revoke changed gids";
347
348    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
349            "permissions revoked";
350
351    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
352
353    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
354
355    /** Permission grant: not grant the permission. */
356    private static final int GRANT_DENIED = 1;
357
358    /** Permission grant: grant the permission as an install permission. */
359    private static final int GRANT_INSTALL = 2;
360
361    /** Permission grant: grant the permission as a runtime one. */
362    private static final int GRANT_RUNTIME = 3;
363
364    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
365    private static final int GRANT_UPGRADE = 4;
366
367    final ServiceThread mHandlerThread;
368
369    final PackageHandler mHandler;
370
371    /**
372     * Messages for {@link #mHandler} that need to wait for system ready before
373     * being dispatched.
374     */
375    private ArrayList<Message> mPostSystemReadyMessages;
376
377    final int mSdkVersion = Build.VERSION.SDK_INT;
378
379    final Context mContext;
380    final boolean mFactoryTest;
381    final boolean mOnlyCore;
382    final boolean mLazyDexOpt;
383    final long mDexOptLRUThresholdInMills;
384    final DisplayMetrics mMetrics;
385    final int mDefParseFlags;
386    final String[] mSeparateProcesses;
387    final boolean mIsUpgrade;
388
389    // This is where all application persistent data goes.
390    final File mAppDataDir;
391
392    // This is where all application persistent data goes for secondary users.
393    final File mUserAppDataDir;
394
395    /** The location for ASEC container files on internal storage. */
396    final String mAsecInternalPath;
397
398    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
399    // LOCK HELD.  Can be called with mInstallLock held.
400    final Installer mInstaller;
401
402    /** Directory where installed third-party apps stored */
403    final File mAppInstallDir;
404
405    /**
406     * Directory to which applications installed internally have their
407     * 32 bit native libraries copied.
408     */
409    private File mAppLib32InstallDir;
410
411    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
412    // apps.
413    final File mDrmAppPrivateInstallDir;
414
415    // ----------------------------------------------------------------
416
417    // Lock for state used when installing and doing other long running
418    // operations.  Methods that must be called with this lock held have
419    // the suffix "LI".
420    final Object mInstallLock = new Object();
421
422    // ----------------------------------------------------------------
423
424    // Keys are String (package name), values are Package.  This also serves
425    // as the lock for the global state.  Methods that must be called with
426    // this lock held have the prefix "LP".
427    final ArrayMap<String, PackageParser.Package> mPackages =
428            new ArrayMap<String, PackageParser.Package>();
429
430    // Tracks available target package names -> overlay package paths.
431    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
432        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
433
434    final Settings mSettings;
435    boolean mRestoredSettings;
436
437    // System configuration read by SystemConfig.
438    final int[] mGlobalGids;
439    final SparseArray<ArraySet<String>> mSystemPermissions;
440    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
441
442    // If mac_permissions.xml was found for seinfo labeling.
443    boolean mFoundPolicyFile;
444
445    // If a recursive restorecon of /data/data/<pkg> is needed.
446    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
447
448    public static final class SharedLibraryEntry {
449        public final String path;
450        public final String apk;
451
452        SharedLibraryEntry(String _path, String _apk) {
453            path = _path;
454            apk = _apk;
455        }
456    }
457
458    // Currently known shared libraries.
459    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
460            new ArrayMap<String, SharedLibraryEntry>();
461
462    // All available activities, for your resolving pleasure.
463    final ActivityIntentResolver mActivities =
464            new ActivityIntentResolver();
465
466    // All available receivers, for your resolving pleasure.
467    final ActivityIntentResolver mReceivers =
468            new ActivityIntentResolver();
469
470    // All available services, for your resolving pleasure.
471    final ServiceIntentResolver mServices = new ServiceIntentResolver();
472
473    // All available providers, for your resolving pleasure.
474    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
475
476    // Mapping from provider base names (first directory in content URI codePath)
477    // to the provider information.
478    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
479            new ArrayMap<String, PackageParser.Provider>();
480
481    // Mapping from instrumentation class names to info about them.
482    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
483            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
484
485    // Mapping from permission names to info about them.
486    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
487            new ArrayMap<String, PackageParser.PermissionGroup>();
488
489    // Packages whose data we have transfered into another package, thus
490    // should no longer exist.
491    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
492
493    // Broadcast actions that are only available to the system.
494    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
495
496    /** List of packages waiting for verification. */
497    final SparseArray<PackageVerificationState> mPendingVerification
498            = new SparseArray<PackageVerificationState>();
499
500    /** Set of packages associated with each app op permission. */
501    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
502
503    final PackageInstallerService mInstallerService;
504
505    private final PackageDexOptimizer mPackageDexOptimizer;
506    // Cache of users who need badging.
507    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
508
509    /** Token for keys in mPendingVerification. */
510    private int mPendingVerificationToken = 0;
511
512    volatile boolean mSystemReady;
513    volatile boolean mSafeMode;
514    volatile boolean mHasSystemUidErrors;
515
516    ApplicationInfo mAndroidApplication;
517    final ActivityInfo mResolveActivity = new ActivityInfo();
518    final ResolveInfo mResolveInfo = new ResolveInfo();
519    ComponentName mResolveComponentName;
520    PackageParser.Package mPlatformPackage;
521    ComponentName mCustomResolverComponentName;
522
523    boolean mResolverReplaced = false;
524
525    private final ComponentName mIntentFilterVerifierComponent;
526    private int mIntentFilterVerificationToken = 0;
527
528    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
529            = new SparseArray<IntentFilterVerificationState>();
530
531    private interface IntentFilterVerifier<T extends IntentFilter> {
532        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
533                                               T filter, String packageName);
534        void startVerifications(int userId);
535        void receiveVerificationResponse(int verificationId);
536    }
537
538    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
539        private Context mContext;
540        private ComponentName mIntentFilterVerifierComponent;
541        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
542
543        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
544            mContext = context;
545            mIntentFilterVerifierComponent = verifierComponent;
546        }
547
548        private String getDefaultScheme() {
549            // TODO: replace SCHEME_HTTP with SCHEME_HTTPS
550            return IntentFilter.SCHEME_HTTP;
551        }
552
553        @Override
554        public void startVerifications(int userId) {
555            // Launch verifications requests
556            int count = mCurrentIntentFilterVerifications.size();
557            for (int n=0; n<count; n++) {
558                int verificationId = mCurrentIntentFilterVerifications.get(n);
559                final IntentFilterVerificationState ivs =
560                        mIntentFilterVerificationStates.get(verificationId);
561
562                String packageName = ivs.getPackageName();
563
564                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
565                final int filterCount = filters.size();
566                ArraySet<String> domainsSet = new ArraySet<>();
567                for (int m=0; m<filterCount; m++) {
568                    PackageParser.ActivityIntentInfo filter = filters.get(m);
569                    domainsSet.addAll(filter.getHostsList());
570                }
571                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
572                synchronized (mPackages) {
573                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
574                            packageName, domainsList) != null) {
575                        scheduleWriteSettingsLocked();
576                    }
577                }
578                sendVerificationRequest(userId, verificationId, ivs);
579            }
580            mCurrentIntentFilterVerifications.clear();
581        }
582
583        private void sendVerificationRequest(int userId, int verificationId,
584                IntentFilterVerificationState ivs) {
585
586            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
587            verificationIntent.putExtra(
588                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
589                    verificationId);
590            verificationIntent.putExtra(
591                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
592                    getDefaultScheme());
593            verificationIntent.putExtra(
594                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
595                    ivs.getHostsString());
596            verificationIntent.putExtra(
597                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
598                    ivs.getPackageName());
599            verificationIntent.setComponent(mIntentFilterVerifierComponent);
600            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
601
602            UserHandle user = new UserHandle(userId);
603            mContext.sendBroadcastAsUser(verificationIntent, user);
604            Slog.d(TAG, "Sending IntenFilter verification broadcast");
605        }
606
607        public void receiveVerificationResponse(int verificationId) {
608            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
609
610            final boolean verified = ivs.isVerified();
611
612            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
613            final int count = filters.size();
614            for (int n=0; n<count; n++) {
615                PackageParser.ActivityIntentInfo filter = filters.get(n);
616                filter.setVerified(verified);
617
618                Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:"
619                        + verified + " and hosts:" + ivs.getHostsString());
620            }
621
622            mIntentFilterVerificationStates.remove(verificationId);
623
624            final String packageName = ivs.getPackageName();
625            IntentFilterVerificationInfo ivi = null;
626
627            synchronized (mPackages) {
628                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
629            }
630            if (ivi == null) {
631                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
632                        + verificationId + " packageName:" + packageName);
633                return;
634            }
635            Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:"
636                    + verificationId);
637
638            synchronized (mPackages) {
639                if (verified) {
640                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
641                } else {
642                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
643                }
644                scheduleWriteSettingsLocked();
645
646                final int userId = ivs.getUserId();
647                if (userId != UserHandle.USER_ALL) {
648                    final int userStatus =
649                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
650
651                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
652                    boolean needUpdate = false;
653
654                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
655                    // already been set by the User thru the Disambiguation dialog
656                    switch (userStatus) {
657                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
658                            if (verified) {
659                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
660                            } else {
661                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
662                            }
663                            needUpdate = true;
664                            break;
665
666                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
667                            if (verified) {
668                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
669                                needUpdate = true;
670                            }
671                            break;
672
673                        default:
674                            // Nothing to do
675                    }
676
677                    if (needUpdate) {
678                        mSettings.updateIntentFilterVerificationStatusLPw(
679                                packageName, updatedStatus, userId);
680                        scheduleWritePackageRestrictionsLocked(userId);
681                    }
682                }
683            }
684        }
685
686        @Override
687        public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
688                    ActivityIntentInfo filter, String packageName) {
689            if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
690                    filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
691                Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme");
692                return false;
693            }
694            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
695            if (ivs == null) {
696                ivs = createDomainVerificationState(verifierId, userId, verificationId,
697                        packageName);
698            }
699            if (!hasValidDomains(filter)) {
700                return false;
701            }
702            ivs.addFilter(filter);
703            return true;
704        }
705
706        private IntentFilterVerificationState createDomainVerificationState(int verifierId,
707                int userId, int verificationId, String packageName) {
708            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
709                    verifierId, userId, packageName);
710            ivs.setPendingState();
711            synchronized (mPackages) {
712                mIntentFilterVerificationStates.append(verificationId, ivs);
713                mCurrentIntentFilterVerifications.add(verificationId);
714            }
715            return ivs;
716        }
717    }
718
719    private static boolean hasValidDomains(ActivityIntentInfo filter) {
720        return hasValidDomains(filter, true);
721    }
722
723    private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) {
724        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
725                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
726        if (!hasHTTPorHTTPS) {
727            if (logging) {
728                Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme");
729            }
730            return false;
731        }
732        ArrayList<String> hosts = filter.getHostsList();
733        if (hosts.size() == 0) {
734            if (logging) {
735                Slog.d(TAG, "IntentFilter does not contain any data hosts");
736            }
737            // We still return true as this is the case of any Browser
738            return true;
739        }
740        String hostEndBase = null;
741        for (String host : hosts) {
742            String[] hostParts = host.split("\\.");
743            // Should be at minimum a host like "example.com"
744            if (hostParts.length < 2) {
745                if (logging) {
746                    Slog.d(TAG, "IntentFilter does not contain a valid data host name: " + host);
747                }
748                return false;
749            }
750            // Verify that we have the same ending domain
751            int length = hostParts.length;
752            String hostEnd = hostParts[length - 1] + hostParts[length - 2];
753            if (hostEndBase == null) {
754                hostEndBase = hostEnd;
755            }
756            if (!hostEnd.equalsIgnoreCase(hostEndBase)) {
757                if (logging) {
758                    Slog.d(TAG, "IntentFilter does not contain the same data domains");
759                }
760                return false;
761            }
762        }
763        return true;
764    }
765
766    private IntentFilterVerifier mIntentFilterVerifier;
767
768    // Set of pending broadcasts for aggregating enable/disable of components.
769    static class PendingPackageBroadcasts {
770        // for each user id, a map of <package name -> components within that package>
771        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
772
773        public PendingPackageBroadcasts() {
774            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
775        }
776
777        public ArrayList<String> get(int userId, String packageName) {
778            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
779            return packages.get(packageName);
780        }
781
782        public void put(int userId, String packageName, ArrayList<String> components) {
783            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
784            packages.put(packageName, components);
785        }
786
787        public void remove(int userId, String packageName) {
788            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
789            if (packages != null) {
790                packages.remove(packageName);
791            }
792        }
793
794        public void remove(int userId) {
795            mUidMap.remove(userId);
796        }
797
798        public int userIdCount() {
799            return mUidMap.size();
800        }
801
802        public int userIdAt(int n) {
803            return mUidMap.keyAt(n);
804        }
805
806        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
807            return mUidMap.get(userId);
808        }
809
810        public int size() {
811            // total number of pending broadcast entries across all userIds
812            int num = 0;
813            for (int i = 0; i< mUidMap.size(); i++) {
814                num += mUidMap.valueAt(i).size();
815            }
816            return num;
817        }
818
819        public void clear() {
820            mUidMap.clear();
821        }
822
823        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
824            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
825            if (map == null) {
826                map = new ArrayMap<String, ArrayList<String>>();
827                mUidMap.put(userId, map);
828            }
829            return map;
830        }
831    }
832    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
833
834    // Service Connection to remote media container service to copy
835    // package uri's from external media onto secure containers
836    // or internal storage.
837    private IMediaContainerService mContainerService = null;
838
839    static final int SEND_PENDING_BROADCAST = 1;
840    static final int MCS_BOUND = 3;
841    static final int END_COPY = 4;
842    static final int INIT_COPY = 5;
843    static final int MCS_UNBIND = 6;
844    static final int START_CLEANING_PACKAGE = 7;
845    static final int FIND_INSTALL_LOC = 8;
846    static final int POST_INSTALL = 9;
847    static final int MCS_RECONNECT = 10;
848    static final int MCS_GIVE_UP = 11;
849    static final int UPDATED_MEDIA_STATUS = 12;
850    static final int WRITE_SETTINGS = 13;
851    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
852    static final int PACKAGE_VERIFIED = 15;
853    static final int CHECK_PENDING_VERIFICATION = 16;
854    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
855    static final int INTENT_FILTER_VERIFIED = 18;
856
857    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
858
859    // Delay time in millisecs
860    static final int BROADCAST_DELAY = 10 * 1000;
861
862    static UserManagerService sUserManager;
863
864    // Stores a list of users whose package restrictions file needs to be updated
865    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
866
867    final private DefaultContainerConnection mDefContainerConn =
868            new DefaultContainerConnection();
869    class DefaultContainerConnection implements ServiceConnection {
870        public void onServiceConnected(ComponentName name, IBinder service) {
871            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
872            IMediaContainerService imcs =
873                IMediaContainerService.Stub.asInterface(service);
874            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
875        }
876
877        public void onServiceDisconnected(ComponentName name) {
878            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
879        }
880    };
881
882    // Recordkeeping of restore-after-install operations that are currently in flight
883    // between the Package Manager and the Backup Manager
884    class PostInstallData {
885        public InstallArgs args;
886        public PackageInstalledInfo res;
887
888        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
889            args = _a;
890            res = _r;
891        }
892    };
893    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
894    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
895
896    // backup/restore of preferred activity state
897    private static final String TAG_PREFERRED_BACKUP = "pa";
898
899    private final String mRequiredVerifierPackage;
900
901    private final PackageUsage mPackageUsage = new PackageUsage();
902
903    private class PackageUsage {
904        private static final int WRITE_INTERVAL
905            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
906
907        private final Object mFileLock = new Object();
908        private final AtomicLong mLastWritten = new AtomicLong(0);
909        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
910
911        private boolean mIsHistoricalPackageUsageAvailable = true;
912
913        boolean isHistoricalPackageUsageAvailable() {
914            return mIsHistoricalPackageUsageAvailable;
915        }
916
917        void write(boolean force) {
918            if (force) {
919                writeInternal();
920                return;
921            }
922            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
923                && !DEBUG_DEXOPT) {
924                return;
925            }
926            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
927                new Thread("PackageUsage_DiskWriter") {
928                    @Override
929                    public void run() {
930                        try {
931                            writeInternal();
932                        } finally {
933                            mBackgroundWriteRunning.set(false);
934                        }
935                    }
936                }.start();
937            }
938        }
939
940        private void writeInternal() {
941            synchronized (mPackages) {
942                synchronized (mFileLock) {
943                    AtomicFile file = getFile();
944                    FileOutputStream f = null;
945                    try {
946                        f = file.startWrite();
947                        BufferedOutputStream out = new BufferedOutputStream(f);
948                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
949                        StringBuilder sb = new StringBuilder();
950                        for (PackageParser.Package pkg : mPackages.values()) {
951                            if (pkg.mLastPackageUsageTimeInMills == 0) {
952                                continue;
953                            }
954                            sb.setLength(0);
955                            sb.append(pkg.packageName);
956                            sb.append(' ');
957                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
958                            sb.append('\n');
959                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
960                        }
961                        out.flush();
962                        file.finishWrite(f);
963                    } catch (IOException e) {
964                        if (f != null) {
965                            file.failWrite(f);
966                        }
967                        Log.e(TAG, "Failed to write package usage times", e);
968                    }
969                }
970            }
971            mLastWritten.set(SystemClock.elapsedRealtime());
972        }
973
974        void readLP() {
975            synchronized (mFileLock) {
976                AtomicFile file = getFile();
977                BufferedInputStream in = null;
978                try {
979                    in = new BufferedInputStream(file.openRead());
980                    StringBuffer sb = new StringBuffer();
981                    while (true) {
982                        String packageName = readToken(in, sb, ' ');
983                        if (packageName == null) {
984                            break;
985                        }
986                        String timeInMillisString = readToken(in, sb, '\n');
987                        if (timeInMillisString == null) {
988                            throw new IOException("Failed to find last usage time for package "
989                                                  + packageName);
990                        }
991                        PackageParser.Package pkg = mPackages.get(packageName);
992                        if (pkg == null) {
993                            continue;
994                        }
995                        long timeInMillis;
996                        try {
997                            timeInMillis = Long.parseLong(timeInMillisString.toString());
998                        } catch (NumberFormatException e) {
999                            throw new IOException("Failed to parse " + timeInMillisString
1000                                                  + " as a long.", e);
1001                        }
1002                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1003                    }
1004                } catch (FileNotFoundException expected) {
1005                    mIsHistoricalPackageUsageAvailable = false;
1006                } catch (IOException e) {
1007                    Log.w(TAG, "Failed to read package usage times", e);
1008                } finally {
1009                    IoUtils.closeQuietly(in);
1010                }
1011            }
1012            mLastWritten.set(SystemClock.elapsedRealtime());
1013        }
1014
1015        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1016                throws IOException {
1017            sb.setLength(0);
1018            while (true) {
1019                int ch = in.read();
1020                if (ch == -1) {
1021                    if (sb.length() == 0) {
1022                        return null;
1023                    }
1024                    throw new IOException("Unexpected EOF");
1025                }
1026                if (ch == endOfToken) {
1027                    return sb.toString();
1028                }
1029                sb.append((char)ch);
1030            }
1031        }
1032
1033        private AtomicFile getFile() {
1034            File dataDir = Environment.getDataDirectory();
1035            File systemDir = new File(dataDir, "system");
1036            File fname = new File(systemDir, "package-usage.list");
1037            return new AtomicFile(fname);
1038        }
1039    }
1040
1041    class PackageHandler extends Handler {
1042        private boolean mBound = false;
1043        final ArrayList<HandlerParams> mPendingInstalls =
1044            new ArrayList<HandlerParams>();
1045
1046        private boolean connectToService() {
1047            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1048                    " DefaultContainerService");
1049            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1050            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1051            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1052                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1053                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1054                mBound = true;
1055                return true;
1056            }
1057            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1058            return false;
1059        }
1060
1061        private void disconnectService() {
1062            mContainerService = null;
1063            mBound = false;
1064            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1065            mContext.unbindService(mDefContainerConn);
1066            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1067        }
1068
1069        PackageHandler(Looper looper) {
1070            super(looper);
1071        }
1072
1073        public void handleMessage(Message msg) {
1074            try {
1075                doHandleMessage(msg);
1076            } finally {
1077                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1078            }
1079        }
1080
1081        void doHandleMessage(Message msg) {
1082            switch (msg.what) {
1083                case INIT_COPY: {
1084                    HandlerParams params = (HandlerParams) msg.obj;
1085                    int idx = mPendingInstalls.size();
1086                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1087                    // If a bind was already initiated we dont really
1088                    // need to do anything. The pending install
1089                    // will be processed later on.
1090                    if (!mBound) {
1091                        // If this is the only one pending we might
1092                        // have to bind to the service again.
1093                        if (!connectToService()) {
1094                            Slog.e(TAG, "Failed to bind to media container service");
1095                            params.serviceError();
1096                            return;
1097                        } else {
1098                            // Once we bind to the service, the first
1099                            // pending request will be processed.
1100                            mPendingInstalls.add(idx, params);
1101                        }
1102                    } else {
1103                        mPendingInstalls.add(idx, params);
1104                        // Already bound to the service. Just make
1105                        // sure we trigger off processing the first request.
1106                        if (idx == 0) {
1107                            mHandler.sendEmptyMessage(MCS_BOUND);
1108                        }
1109                    }
1110                    break;
1111                }
1112                case MCS_BOUND: {
1113                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1114                    if (msg.obj != null) {
1115                        mContainerService = (IMediaContainerService) msg.obj;
1116                    }
1117                    if (mContainerService == null) {
1118                        // Something seriously wrong. Bail out
1119                        Slog.e(TAG, "Cannot bind to media container service");
1120                        for (HandlerParams params : mPendingInstalls) {
1121                            // Indicate service bind error
1122                            params.serviceError();
1123                        }
1124                        mPendingInstalls.clear();
1125                    } else if (mPendingInstalls.size() > 0) {
1126                        HandlerParams params = mPendingInstalls.get(0);
1127                        if (params != null) {
1128                            if (params.startCopy()) {
1129                                // We are done...  look for more work or to
1130                                // go idle.
1131                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1132                                        "Checking for more work or unbind...");
1133                                // Delete pending install
1134                                if (mPendingInstalls.size() > 0) {
1135                                    mPendingInstalls.remove(0);
1136                                }
1137                                if (mPendingInstalls.size() == 0) {
1138                                    if (mBound) {
1139                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1140                                                "Posting delayed MCS_UNBIND");
1141                                        removeMessages(MCS_UNBIND);
1142                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1143                                        // Unbind after a little delay, to avoid
1144                                        // continual thrashing.
1145                                        sendMessageDelayed(ubmsg, 10000);
1146                                    }
1147                                } else {
1148                                    // There are more pending requests in queue.
1149                                    // Just post MCS_BOUND message to trigger processing
1150                                    // of next pending install.
1151                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1152                                            "Posting MCS_BOUND for next work");
1153                                    mHandler.sendEmptyMessage(MCS_BOUND);
1154                                }
1155                            }
1156                        }
1157                    } else {
1158                        // Should never happen ideally.
1159                        Slog.w(TAG, "Empty queue");
1160                    }
1161                    break;
1162                }
1163                case MCS_RECONNECT: {
1164                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1165                    if (mPendingInstalls.size() > 0) {
1166                        if (mBound) {
1167                            disconnectService();
1168                        }
1169                        if (!connectToService()) {
1170                            Slog.e(TAG, "Failed to bind to media container service");
1171                            for (HandlerParams params : mPendingInstalls) {
1172                                // Indicate service bind error
1173                                params.serviceError();
1174                            }
1175                            mPendingInstalls.clear();
1176                        }
1177                    }
1178                    break;
1179                }
1180                case MCS_UNBIND: {
1181                    // If there is no actual work left, then time to unbind.
1182                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1183
1184                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1185                        if (mBound) {
1186                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1187
1188                            disconnectService();
1189                        }
1190                    } else if (mPendingInstalls.size() > 0) {
1191                        // There are more pending requests in queue.
1192                        // Just post MCS_BOUND message to trigger processing
1193                        // of next pending install.
1194                        mHandler.sendEmptyMessage(MCS_BOUND);
1195                    }
1196
1197                    break;
1198                }
1199                case MCS_GIVE_UP: {
1200                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1201                    mPendingInstalls.remove(0);
1202                    break;
1203                }
1204                case SEND_PENDING_BROADCAST: {
1205                    String packages[];
1206                    ArrayList<String> components[];
1207                    int size = 0;
1208                    int uids[];
1209                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1210                    synchronized (mPackages) {
1211                        if (mPendingBroadcasts == null) {
1212                            return;
1213                        }
1214                        size = mPendingBroadcasts.size();
1215                        if (size <= 0) {
1216                            // Nothing to be done. Just return
1217                            return;
1218                        }
1219                        packages = new String[size];
1220                        components = new ArrayList[size];
1221                        uids = new int[size];
1222                        int i = 0;  // filling out the above arrays
1223
1224                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1225                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1226                            Iterator<Map.Entry<String, ArrayList<String>>> it
1227                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1228                                            .entrySet().iterator();
1229                            while (it.hasNext() && i < size) {
1230                                Map.Entry<String, ArrayList<String>> ent = it.next();
1231                                packages[i] = ent.getKey();
1232                                components[i] = ent.getValue();
1233                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1234                                uids[i] = (ps != null)
1235                                        ? UserHandle.getUid(packageUserId, ps.appId)
1236                                        : -1;
1237                                i++;
1238                            }
1239                        }
1240                        size = i;
1241                        mPendingBroadcasts.clear();
1242                    }
1243                    // Send broadcasts
1244                    for (int i = 0; i < size; i++) {
1245                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1246                    }
1247                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1248                    break;
1249                }
1250                case START_CLEANING_PACKAGE: {
1251                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1252                    final String packageName = (String)msg.obj;
1253                    final int userId = msg.arg1;
1254                    final boolean andCode = msg.arg2 != 0;
1255                    synchronized (mPackages) {
1256                        if (userId == UserHandle.USER_ALL) {
1257                            int[] users = sUserManager.getUserIds();
1258                            for (int user : users) {
1259                                mSettings.addPackageToCleanLPw(
1260                                        new PackageCleanItem(user, packageName, andCode));
1261                            }
1262                        } else {
1263                            mSettings.addPackageToCleanLPw(
1264                                    new PackageCleanItem(userId, packageName, andCode));
1265                        }
1266                    }
1267                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1268                    startCleaningPackages();
1269                } break;
1270                case POST_INSTALL: {
1271                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1272                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1273                    mRunningInstalls.delete(msg.arg1);
1274                    boolean deleteOld = false;
1275
1276                    if (data != null) {
1277                        InstallArgs args = data.args;
1278                        PackageInstalledInfo res = data.res;
1279
1280                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1281                            res.removedInfo.sendBroadcast(false, true, false);
1282                            Bundle extras = new Bundle(1);
1283                            extras.putInt(Intent.EXTRA_UID, res.uid);
1284
1285                            // Now that we successfully installed the package, grant runtime
1286                            // permissions if requested before broadcasting the install.
1287                            if ((args.installFlags
1288                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1289                                grantRequestedRuntimePermissions(res.pkg,
1290                                        args.user.getIdentifier());
1291                            }
1292
1293                            // Determine the set of users who are adding this
1294                            // package for the first time vs. those who are seeing
1295                            // an update.
1296                            int[] firstUsers;
1297                            int[] updateUsers = new int[0];
1298                            if (res.origUsers == null || res.origUsers.length == 0) {
1299                                firstUsers = res.newUsers;
1300                            } else {
1301                                firstUsers = new int[0];
1302                                for (int i=0; i<res.newUsers.length; i++) {
1303                                    int user = res.newUsers[i];
1304                                    boolean isNew = true;
1305                                    for (int j=0; j<res.origUsers.length; j++) {
1306                                        if (res.origUsers[j] == user) {
1307                                            isNew = false;
1308                                            break;
1309                                        }
1310                                    }
1311                                    if (isNew) {
1312                                        int[] newFirst = new int[firstUsers.length+1];
1313                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1314                                                firstUsers.length);
1315                                        newFirst[firstUsers.length] = user;
1316                                        firstUsers = newFirst;
1317                                    } else {
1318                                        int[] newUpdate = new int[updateUsers.length+1];
1319                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1320                                                updateUsers.length);
1321                                        newUpdate[updateUsers.length] = user;
1322                                        updateUsers = newUpdate;
1323                                    }
1324                                }
1325                            }
1326                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1327                                    res.pkg.applicationInfo.packageName,
1328                                    extras, null, null, firstUsers);
1329                            final boolean update = res.removedInfo.removedPackage != null;
1330                            if (update) {
1331                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1332                            }
1333                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1334                                    res.pkg.applicationInfo.packageName,
1335                                    extras, null, null, updateUsers);
1336                            if (update) {
1337                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1338                                        res.pkg.applicationInfo.packageName,
1339                                        extras, null, null, updateUsers);
1340                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1341                                        null, null,
1342                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1343
1344                                // treat asec-hosted packages like removable media on upgrade
1345                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1346                                    if (DEBUG_INSTALL) {
1347                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1348                                                + " is ASEC-hosted -> AVAILABLE");
1349                                    }
1350                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1351                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1352                                    pkgList.add(res.pkg.applicationInfo.packageName);
1353                                    sendResourcesChangedBroadcast(true, true,
1354                                            pkgList,uidArray, null);
1355                                }
1356                            }
1357                            if (res.removedInfo.args != null) {
1358                                // Remove the replaced package's older resources safely now
1359                                deleteOld = true;
1360                            }
1361
1362                            // Log current value of "unknown sources" setting
1363                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1364                                getUnknownSourcesSettings());
1365                        }
1366                        // Force a gc to clear up things
1367                        Runtime.getRuntime().gc();
1368                        // We delete after a gc for applications  on sdcard.
1369                        if (deleteOld) {
1370                            synchronized (mInstallLock) {
1371                                res.removedInfo.args.doPostDeleteLI(true);
1372                            }
1373                        }
1374                        if (args.observer != null) {
1375                            try {
1376                                Bundle extras = extrasForInstallResult(res);
1377                                args.observer.onPackageInstalled(res.name, res.returnCode,
1378                                        res.returnMsg, extras);
1379                            } catch (RemoteException e) {
1380                                Slog.i(TAG, "Observer no longer exists.");
1381                            }
1382                        }
1383                    } else {
1384                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1385                    }
1386                } break;
1387                case UPDATED_MEDIA_STATUS: {
1388                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1389                    boolean reportStatus = msg.arg1 == 1;
1390                    boolean doGc = msg.arg2 == 1;
1391                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1392                    if (doGc) {
1393                        // Force a gc to clear up stale containers.
1394                        Runtime.getRuntime().gc();
1395                    }
1396                    if (msg.obj != null) {
1397                        @SuppressWarnings("unchecked")
1398                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1399                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1400                        // Unload containers
1401                        unloadAllContainers(args);
1402                    }
1403                    if (reportStatus) {
1404                        try {
1405                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1406                            PackageHelper.getMountService().finishMediaUpdate();
1407                        } catch (RemoteException e) {
1408                            Log.e(TAG, "MountService not running?");
1409                        }
1410                    }
1411                } break;
1412                case WRITE_SETTINGS: {
1413                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1414                    synchronized (mPackages) {
1415                        removeMessages(WRITE_SETTINGS);
1416                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1417                        mSettings.writeLPr();
1418                        mDirtyUsers.clear();
1419                    }
1420                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1421                } break;
1422                case WRITE_PACKAGE_RESTRICTIONS: {
1423                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1424                    synchronized (mPackages) {
1425                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1426                        for (int userId : mDirtyUsers) {
1427                            mSettings.writePackageRestrictionsLPr(userId);
1428                        }
1429                        mDirtyUsers.clear();
1430                    }
1431                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1432                } break;
1433                case CHECK_PENDING_VERIFICATION: {
1434                    final int verificationId = msg.arg1;
1435                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1436
1437                    if ((state != null) && !state.timeoutExtended()) {
1438                        final InstallArgs args = state.getInstallArgs();
1439                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1440
1441                        Slog.i(TAG, "Verification timed out for " + originUri);
1442                        mPendingVerification.remove(verificationId);
1443
1444                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1445
1446                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1447                            Slog.i(TAG, "Continuing with installation of " + originUri);
1448                            state.setVerifierResponse(Binder.getCallingUid(),
1449                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1450                            broadcastPackageVerified(verificationId, originUri,
1451                                    PackageManager.VERIFICATION_ALLOW,
1452                                    state.getInstallArgs().getUser());
1453                            try {
1454                                ret = args.copyApk(mContainerService, true);
1455                            } catch (RemoteException e) {
1456                                Slog.e(TAG, "Could not contact the ContainerService");
1457                            }
1458                        } else {
1459                            broadcastPackageVerified(verificationId, originUri,
1460                                    PackageManager.VERIFICATION_REJECT,
1461                                    state.getInstallArgs().getUser());
1462                        }
1463
1464                        processPendingInstall(args, ret);
1465                        mHandler.sendEmptyMessage(MCS_UNBIND);
1466                    }
1467                    break;
1468                }
1469                case PACKAGE_VERIFIED: {
1470                    final int verificationId = msg.arg1;
1471
1472                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1473                    if (state == null) {
1474                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1475                        break;
1476                    }
1477
1478                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1479
1480                    state.setVerifierResponse(response.callerUid, response.code);
1481
1482                    if (state.isVerificationComplete()) {
1483                        mPendingVerification.remove(verificationId);
1484
1485                        final InstallArgs args = state.getInstallArgs();
1486                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1487
1488                        int ret;
1489                        if (state.isInstallAllowed()) {
1490                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1491                            broadcastPackageVerified(verificationId, originUri,
1492                                    response.code, state.getInstallArgs().getUser());
1493                            try {
1494                                ret = args.copyApk(mContainerService, true);
1495                            } catch (RemoteException e) {
1496                                Slog.e(TAG, "Could not contact the ContainerService");
1497                            }
1498                        } else {
1499                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1500                        }
1501
1502                        processPendingInstall(args, ret);
1503
1504                        mHandler.sendEmptyMessage(MCS_UNBIND);
1505                    }
1506
1507                    break;
1508                }
1509                case START_INTENT_FILTER_VERIFICATIONS: {
1510                    int userId = msg.arg1;
1511                    int verifierUid = msg.arg2;
1512                    PackageParser.Package pkg = (PackageParser.Package)msg.obj;
1513
1514                    verifyIntentFiltersIfNeeded(userId, verifierUid, pkg);
1515                    break;
1516                }
1517                case INTENT_FILTER_VERIFIED: {
1518                    final int verificationId = msg.arg1;
1519
1520                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1521                            verificationId);
1522                    if (state == null) {
1523                        Slog.w(TAG, "Invalid IntentFilter verification token "
1524                                + verificationId + " received");
1525                        break;
1526                    }
1527
1528                    final int userId = state.getUserId();
1529
1530                    Slog.d(TAG, "Processing IntentFilter verification with token:"
1531                            + verificationId + " and userId:" + userId);
1532
1533                    final IntentFilterVerificationResponse response =
1534                            (IntentFilterVerificationResponse) msg.obj;
1535
1536                    state.setVerifierResponse(response.callerUid, response.code);
1537
1538                    Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1539                            + " and userId:" + userId
1540                            + " is settings verifier response with response code:"
1541                            + response.code);
1542
1543                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1544                        Slog.d(TAG, "Domains failing verification: "
1545                                + response.getFailedDomainsString());
1546                    }
1547
1548                    if (state.isVerificationComplete()) {
1549                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1550                    } else {
1551                        Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1552                                + " was not said to be complete");
1553                    }
1554
1555                    break;
1556                }
1557            }
1558        }
1559    }
1560
1561    private StorageEventListener mStorageListener = new StorageEventListener() {
1562        @Override
1563        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1564            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1565                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1566                    loadPrivatePackages(vol);
1567                } else if (vol.state == VolumeInfo.STATE_UNMOUNTING) {
1568                    unloadPrivatePackages(vol);
1569                }
1570            }
1571
1572            if (vol.isPrimary() && vol.type == VolumeInfo.TYPE_PUBLIC) {
1573                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1574                    updateExternalMediaStatus(true, false);
1575                } else if (vol.state == VolumeInfo.STATE_UNMOUNTING) {
1576                    updateExternalMediaStatus(false, false);
1577                }
1578            }
1579        }
1580    };
1581
1582    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1583        if (userId >= UserHandle.USER_OWNER) {
1584            grantRequestedRuntimePermissionsForUser(pkg, userId);
1585        } else if (userId == UserHandle.USER_ALL) {
1586            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1587                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1588            }
1589        }
1590    }
1591
1592    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1593        SettingBase sb = (SettingBase) pkg.mExtras;
1594        if (sb == null) {
1595            return;
1596        }
1597
1598        PermissionsState permissionsState = sb.getPermissionsState();
1599
1600        for (String permission : pkg.requestedPermissions) {
1601            BasePermission bp = mSettings.mPermissions.get(permission);
1602            if (bp != null && bp.isRuntime()) {
1603                permissionsState.grantRuntimePermission(bp, userId);
1604            }
1605        }
1606    }
1607
1608    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1609        Bundle extras = null;
1610        switch (res.returnCode) {
1611            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1612                extras = new Bundle();
1613                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1614                        res.origPermission);
1615                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1616                        res.origPackage);
1617                break;
1618            }
1619        }
1620        return extras;
1621    }
1622
1623    void scheduleWriteSettingsLocked() {
1624        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1625            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1626        }
1627    }
1628
1629    void scheduleWritePackageRestrictionsLocked(int userId) {
1630        if (!sUserManager.exists(userId)) return;
1631        mDirtyUsers.add(userId);
1632        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1633            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1634        }
1635    }
1636
1637    public static PackageManagerService main(Context context, Installer installer,
1638            boolean factoryTest, boolean onlyCore) {
1639        PackageManagerService m = new PackageManagerService(context, installer,
1640                factoryTest, onlyCore);
1641        ServiceManager.addService("package", m);
1642        return m;
1643    }
1644
1645    static String[] splitString(String str, char sep) {
1646        int count = 1;
1647        int i = 0;
1648        while ((i=str.indexOf(sep, i)) >= 0) {
1649            count++;
1650            i++;
1651        }
1652
1653        String[] res = new String[count];
1654        i=0;
1655        count = 0;
1656        int lastI=0;
1657        while ((i=str.indexOf(sep, i)) >= 0) {
1658            res[count] = str.substring(lastI, i);
1659            count++;
1660            i++;
1661            lastI = i;
1662        }
1663        res[count] = str.substring(lastI, str.length());
1664        return res;
1665    }
1666
1667    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1668        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1669                Context.DISPLAY_SERVICE);
1670        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1671    }
1672
1673    public PackageManagerService(Context context, Installer installer,
1674            boolean factoryTest, boolean onlyCore) {
1675        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1676                SystemClock.uptimeMillis());
1677
1678        if (mSdkVersion <= 0) {
1679            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1680        }
1681
1682        mContext = context;
1683        mFactoryTest = factoryTest;
1684        mOnlyCore = onlyCore;
1685        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1686        mMetrics = new DisplayMetrics();
1687        mSettings = new Settings(mPackages);
1688        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1689                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1690        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1691                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1692        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1693                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1694        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1695                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1696        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1697                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1698        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1699                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1700
1701        // TODO: add a property to control this?
1702        long dexOptLRUThresholdInMinutes;
1703        if (mLazyDexOpt) {
1704            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1705        } else {
1706            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1707        }
1708        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1709
1710        String separateProcesses = SystemProperties.get("debug.separate_processes");
1711        if (separateProcesses != null && separateProcesses.length() > 0) {
1712            if ("*".equals(separateProcesses)) {
1713                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1714                mSeparateProcesses = null;
1715                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1716            } else {
1717                mDefParseFlags = 0;
1718                mSeparateProcesses = separateProcesses.split(",");
1719                Slog.w(TAG, "Running with debug.separate_processes: "
1720                        + separateProcesses);
1721            }
1722        } else {
1723            mDefParseFlags = 0;
1724            mSeparateProcesses = null;
1725        }
1726
1727        mInstaller = installer;
1728        mPackageDexOptimizer = new PackageDexOptimizer(this);
1729
1730        getDefaultDisplayMetrics(context, mMetrics);
1731
1732        SystemConfig systemConfig = SystemConfig.getInstance();
1733        mGlobalGids = systemConfig.getGlobalGids();
1734        mSystemPermissions = systemConfig.getSystemPermissions();
1735        mAvailableFeatures = systemConfig.getAvailableFeatures();
1736
1737        synchronized (mInstallLock) {
1738        // writer
1739        synchronized (mPackages) {
1740            mHandlerThread = new ServiceThread(TAG,
1741                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1742            mHandlerThread.start();
1743            mHandler = new PackageHandler(mHandlerThread.getLooper());
1744            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1745
1746            File dataDir = Environment.getDataDirectory();
1747            mAppDataDir = new File(dataDir, "data");
1748            mAppInstallDir = new File(dataDir, "app");
1749            mAppLib32InstallDir = new File(dataDir, "app-lib");
1750            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1751            mUserAppDataDir = new File(dataDir, "user");
1752            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1753
1754            sUserManager = new UserManagerService(context, this,
1755                    mInstallLock, mPackages);
1756
1757            // Propagate permission configuration in to package manager.
1758            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1759                    = systemConfig.getPermissions();
1760            for (int i=0; i<permConfig.size(); i++) {
1761                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1762                BasePermission bp = mSettings.mPermissions.get(perm.name);
1763                if (bp == null) {
1764                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1765                    mSettings.mPermissions.put(perm.name, bp);
1766                }
1767                if (perm.gids != null) {
1768                    bp.setGids(perm.gids, perm.perUser);
1769                }
1770            }
1771
1772            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1773            for (int i=0; i<libConfig.size(); i++) {
1774                mSharedLibraries.put(libConfig.keyAt(i),
1775                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1776            }
1777
1778            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1779
1780            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1781                    mSdkVersion, mOnlyCore);
1782
1783            String customResolverActivity = Resources.getSystem().getString(
1784                    R.string.config_customResolverActivity);
1785            if (TextUtils.isEmpty(customResolverActivity)) {
1786                customResolverActivity = null;
1787            } else {
1788                mCustomResolverComponentName = ComponentName.unflattenFromString(
1789                        customResolverActivity);
1790            }
1791
1792            long startTime = SystemClock.uptimeMillis();
1793
1794            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1795                    startTime);
1796
1797            // Set flag to monitor and not change apk file paths when
1798            // scanning install directories.
1799            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1800
1801            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1802
1803            /**
1804             * Add everything in the in the boot class path to the
1805             * list of process files because dexopt will have been run
1806             * if necessary during zygote startup.
1807             */
1808            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1809            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1810
1811            if (bootClassPath != null) {
1812                String[] bootClassPathElements = splitString(bootClassPath, ':');
1813                for (String element : bootClassPathElements) {
1814                    alreadyDexOpted.add(element);
1815                }
1816            } else {
1817                Slog.w(TAG, "No BOOTCLASSPATH found!");
1818            }
1819
1820            if (systemServerClassPath != null) {
1821                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1822                for (String element : systemServerClassPathElements) {
1823                    alreadyDexOpted.add(element);
1824                }
1825            } else {
1826                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1827            }
1828
1829            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1830            final String[] dexCodeInstructionSets =
1831                    getDexCodeInstructionSets(
1832                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1833
1834            /**
1835             * Ensure all external libraries have had dexopt run on them.
1836             */
1837            if (mSharedLibraries.size() > 0) {
1838                // NOTE: For now, we're compiling these system "shared libraries"
1839                // (and framework jars) into all available architectures. It's possible
1840                // to compile them only when we come across an app that uses them (there's
1841                // already logic for that in scanPackageLI) but that adds some complexity.
1842                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1843                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1844                        final String lib = libEntry.path;
1845                        if (lib == null) {
1846                            continue;
1847                        }
1848
1849                        try {
1850                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1851                                                                                 dexCodeInstructionSet,
1852                                                                                 false);
1853                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1854                                alreadyDexOpted.add(lib);
1855
1856                                // The list of "shared libraries" we have at this point is
1857                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1858                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1859                                } else {
1860                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1861                                }
1862                            }
1863                        } catch (FileNotFoundException e) {
1864                            Slog.w(TAG, "Library not found: " + lib);
1865                        } catch (IOException e) {
1866                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1867                                    + e.getMessage());
1868                        }
1869                    }
1870                }
1871            }
1872
1873            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1874
1875            // Gross hack for now: we know this file doesn't contain any
1876            // code, so don't dexopt it to avoid the resulting log spew.
1877            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1878
1879            // Gross hack for now: we know this file is only part of
1880            // the boot class path for art, so don't dexopt it to
1881            // avoid the resulting log spew.
1882            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1883
1884            /**
1885             * And there are a number of commands implemented in Java, which
1886             * we currently need to do the dexopt on so that they can be
1887             * run from a non-root shell.
1888             */
1889            String[] frameworkFiles = frameworkDir.list();
1890            if (frameworkFiles != null) {
1891                // TODO: We could compile these only for the most preferred ABI. We should
1892                // first double check that the dex files for these commands are not referenced
1893                // by other system apps.
1894                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1895                    for (int i=0; i<frameworkFiles.length; i++) {
1896                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1897                        String path = libPath.getPath();
1898                        // Skip the file if we already did it.
1899                        if (alreadyDexOpted.contains(path)) {
1900                            continue;
1901                        }
1902                        // Skip the file if it is not a type we want to dexopt.
1903                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1904                            continue;
1905                        }
1906                        try {
1907                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1908                                                                                 dexCodeInstructionSet,
1909                                                                                 false);
1910                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1911                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1912                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1913                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1914                            }
1915                        } catch (FileNotFoundException e) {
1916                            Slog.w(TAG, "Jar not found: " + path);
1917                        } catch (IOException e) {
1918                            Slog.w(TAG, "Exception reading jar: " + path, e);
1919                        }
1920                    }
1921                }
1922            }
1923
1924            // Collect vendor overlay packages.
1925            // (Do this before scanning any apps.)
1926            // For security and version matching reason, only consider
1927            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1928            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1929            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1930                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1931
1932            // Find base frameworks (resource packages without code).
1933            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1934                    | PackageParser.PARSE_IS_SYSTEM_DIR
1935                    | PackageParser.PARSE_IS_PRIVILEGED,
1936                    scanFlags | SCAN_NO_DEX, 0);
1937
1938            // Collected privileged system packages.
1939            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1940            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1941                    | PackageParser.PARSE_IS_SYSTEM_DIR
1942                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1943
1944            // Collect ordinary system packages.
1945            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1946            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1947                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1948
1949            // Collect all vendor packages.
1950            File vendorAppDir = new File("/vendor/app");
1951            try {
1952                vendorAppDir = vendorAppDir.getCanonicalFile();
1953            } catch (IOException e) {
1954                // failed to look up canonical path, continue with original one
1955            }
1956            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1957                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1958
1959            // Collect all OEM packages.
1960            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1961            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1962                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1963
1964            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1965            mInstaller.moveFiles();
1966
1967            // Prune any system packages that no longer exist.
1968            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1969            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1970            if (!mOnlyCore) {
1971                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1972                while (psit.hasNext()) {
1973                    PackageSetting ps = psit.next();
1974
1975                    /*
1976                     * If this is not a system app, it can't be a
1977                     * disable system app.
1978                     */
1979                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1980                        continue;
1981                    }
1982
1983                    /*
1984                     * If the package is scanned, it's not erased.
1985                     */
1986                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1987                    if (scannedPkg != null) {
1988                        /*
1989                         * If the system app is both scanned and in the
1990                         * disabled packages list, then it must have been
1991                         * added via OTA. Remove it from the currently
1992                         * scanned package so the previously user-installed
1993                         * application can be scanned.
1994                         */
1995                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1996                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1997                                    + ps.name + "; removing system app.  Last known codePath="
1998                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1999                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2000                                    + scannedPkg.mVersionCode);
2001                            removePackageLI(ps, true);
2002                            expectingBetter.put(ps.name, ps.codePath);
2003                        }
2004
2005                        continue;
2006                    }
2007
2008                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2009                        psit.remove();
2010                        logCriticalInfo(Log.WARN, "System package " + ps.name
2011                                + " no longer exists; wiping its data");
2012                        removeDataDirsLI(ps.name);
2013                    } else {
2014                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2015                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2016                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2017                        }
2018                    }
2019                }
2020            }
2021
2022            //look for any incomplete package installations
2023            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2024            //clean up list
2025            for(int i = 0; i < deletePkgsList.size(); i++) {
2026                //clean up here
2027                cleanupInstallFailedPackage(deletePkgsList.get(i));
2028            }
2029            //delete tmp files
2030            deleteTempPackageFiles();
2031
2032            // Remove any shared userIDs that have no associated packages
2033            mSettings.pruneSharedUsersLPw();
2034
2035            if (!mOnlyCore) {
2036                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2037                        SystemClock.uptimeMillis());
2038                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2039
2040                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2041                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2042
2043                /**
2044                 * Remove disable package settings for any updated system
2045                 * apps that were removed via an OTA. If they're not a
2046                 * previously-updated app, remove them completely.
2047                 * Otherwise, just revoke their system-level permissions.
2048                 */
2049                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2050                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2051                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2052
2053                    String msg;
2054                    if (deletedPkg == null) {
2055                        msg = "Updated system package " + deletedAppName
2056                                + " no longer exists; wiping its data";
2057                        removeDataDirsLI(deletedAppName);
2058                    } else {
2059                        msg = "Updated system app + " + deletedAppName
2060                                + " no longer present; removing system privileges for "
2061                                + deletedAppName;
2062
2063                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2064
2065                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2066                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2067                    }
2068                    logCriticalInfo(Log.WARN, msg);
2069                }
2070
2071                /**
2072                 * Make sure all system apps that we expected to appear on
2073                 * the userdata partition actually showed up. If they never
2074                 * appeared, crawl back and revive the system version.
2075                 */
2076                for (int i = 0; i < expectingBetter.size(); i++) {
2077                    final String packageName = expectingBetter.keyAt(i);
2078                    if (!mPackages.containsKey(packageName)) {
2079                        final File scanFile = expectingBetter.valueAt(i);
2080
2081                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2082                                + " but never showed up; reverting to system");
2083
2084                        final int reparseFlags;
2085                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2086                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2087                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2088                                    | PackageParser.PARSE_IS_PRIVILEGED;
2089                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2090                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2091                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2092                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2093                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2094                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2095                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2096                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2097                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2098                        } else {
2099                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2100                            continue;
2101                        }
2102
2103                        mSettings.enableSystemPackageLPw(packageName);
2104
2105                        try {
2106                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2107                        } catch (PackageManagerException e) {
2108                            Slog.e(TAG, "Failed to parse original system package: "
2109                                    + e.getMessage());
2110                        }
2111                    }
2112                }
2113            }
2114
2115            // Now that we know all of the shared libraries, update all clients to have
2116            // the correct library paths.
2117            updateAllSharedLibrariesLPw();
2118
2119            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2120                // NOTE: We ignore potential failures here during a system scan (like
2121                // the rest of the commands above) because there's precious little we
2122                // can do about it. A settings error is reported, though.
2123                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2124                        false /* force dexopt */, false /* defer dexopt */);
2125            }
2126
2127            // Now that we know all the packages we are keeping,
2128            // read and update their last usage times.
2129            mPackageUsage.readLP();
2130
2131            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2132                    SystemClock.uptimeMillis());
2133            Slog.i(TAG, "Time to scan packages: "
2134                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2135                    + " seconds");
2136
2137            // If the platform SDK has changed since the last time we booted,
2138            // we need to re-grant app permission to catch any new ones that
2139            // appear.  This is really a hack, and means that apps can in some
2140            // cases get permissions that the user didn't initially explicitly
2141            // allow...  it would be nice to have some better way to handle
2142            // this situation.
2143            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2144                    != mSdkVersion;
2145            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2146                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2147                    + "; regranting permissions for internal storage");
2148            mSettings.mInternalSdkPlatform = mSdkVersion;
2149
2150            // For now runtime permissions are toggled via a system property.
2151            if (!RUNTIME_PERMISSIONS_ENABLED) {
2152                // Remove the runtime permissions state if the feature
2153                // was disabled by flipping the system property.
2154                mSettings.deleteRuntimePermissionsFiles();
2155            }
2156
2157            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2158                    | (regrantPermissions
2159                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2160                            : 0));
2161
2162            // If this is the first boot, and it is a normal boot, then
2163            // we need to initialize the default preferred apps.
2164            if (!mRestoredSettings && !onlyCore) {
2165                mSettings.readDefaultPreferredAppsLPw(this, 0);
2166            }
2167
2168            // If this is first boot after an OTA, and a normal boot, then
2169            // we need to clear code cache directories.
2170            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2171            if (mIsUpgrade && !onlyCore) {
2172                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2173                for (String pkgName : mSettings.mPackages.keySet()) {
2174                    deleteCodeCacheDirsLI(pkgName);
2175                }
2176                mSettings.mFingerprint = Build.FINGERPRINT;
2177            }
2178
2179            // All the changes are done during package scanning.
2180            mSettings.updateInternalDatabaseVersion();
2181
2182            // can downgrade to reader
2183            mSettings.writeLPr();
2184
2185            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2186                    SystemClock.uptimeMillis());
2187
2188            mRequiredVerifierPackage = getRequiredVerifierLPr();
2189
2190            mInstallerService = new PackageInstallerService(context, this);
2191
2192            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2193            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2194                    mIntentFilterVerifierComponent);
2195
2196            primeDomainVerificationsLPw(false);
2197
2198        } // synchronized (mPackages)
2199        } // synchronized (mInstallLock)
2200
2201        // Now after opening every single application zip, make sure they
2202        // are all flushed.  Not really needed, but keeps things nice and
2203        // tidy.
2204        Runtime.getRuntime().gc();
2205    }
2206
2207    @Override
2208    public boolean isFirstBoot() {
2209        return !mRestoredSettings;
2210    }
2211
2212    @Override
2213    public boolean isOnlyCoreApps() {
2214        return mOnlyCore;
2215    }
2216
2217    @Override
2218    public boolean isUpgrade() {
2219        return mIsUpgrade;
2220    }
2221
2222    private String getRequiredVerifierLPr() {
2223        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2224        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2225                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2226
2227        String requiredVerifier = null;
2228
2229        final int N = receivers.size();
2230        for (int i = 0; i < N; i++) {
2231            final ResolveInfo info = receivers.get(i);
2232
2233            if (info.activityInfo == null) {
2234                continue;
2235            }
2236
2237            final String packageName = info.activityInfo.packageName;
2238
2239            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2240                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2241                continue;
2242            }
2243
2244            if (requiredVerifier != null) {
2245                throw new RuntimeException("There can be only one required verifier");
2246            }
2247
2248            requiredVerifier = packageName;
2249        }
2250
2251        return requiredVerifier;
2252    }
2253
2254    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2255        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2256        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2257                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2258
2259        ComponentName verifierComponentName = null;
2260
2261        int priority = -1000;
2262        final int N = receivers.size();
2263        for (int i = 0; i < N; i++) {
2264            final ResolveInfo info = receivers.get(i);
2265
2266            if (info.activityInfo == null) {
2267                continue;
2268            }
2269
2270            final String packageName = info.activityInfo.packageName;
2271
2272            final PackageSetting ps = mSettings.mPackages.get(packageName);
2273            if (ps == null) {
2274                continue;
2275            }
2276
2277            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2278                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2279                continue;
2280            }
2281
2282            // Select the IntentFilterVerifier with the highest priority
2283            if (priority < info.priority) {
2284                priority = info.priority;
2285                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2286                Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName +
2287                        " with priority: " + info.priority);
2288            }
2289        }
2290
2291        return verifierComponentName;
2292    }
2293
2294    private void primeDomainVerificationsLPw(boolean logging) {
2295        Slog.d(TAG, "Start priming domain verification");
2296        boolean updated = false;
2297        ArrayList<String> allHosts = new ArrayList<>();
2298        for (PackageParser.Package pkg : mPackages.values()) {
2299            final String packageName = pkg.packageName;
2300            if (!hasDomainURLs(pkg)) {
2301                if (logging) {
2302                    Slog.d(TAG, "No priming domain verifications for " +
2303                            "package with no domain URLs: " + packageName);
2304                }
2305                continue;
2306            }
2307            for (PackageParser.Activity a : pkg.activities) {
2308                for (ActivityIntentInfo filter : a.intents) {
2309                    if (hasValidDomains(filter, false)) {
2310                        allHosts.addAll(filter.getHostsList());
2311                    }
2312                }
2313            }
2314            if (allHosts.size() > 0) {
2315                allHosts.add("*");
2316            }
2317            IntentFilterVerificationInfo ivi =
2318                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHosts);
2319            if (ivi != null) {
2320                // We will always log this
2321                Slog.d(TAG, "Priming domain verifications for package: " + packageName);
2322                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2323                updated = true;
2324            }
2325            else {
2326                if (logging) {
2327                    Slog.d(TAG, "No priming domain verifications for package: " + packageName);
2328                }
2329            }
2330            allHosts.clear();
2331        }
2332        if (updated) {
2333            scheduleWriteSettingsLocked();
2334        }
2335        Slog.d(TAG, "End priming domain verification");
2336    }
2337
2338    @Override
2339    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2340            throws RemoteException {
2341        try {
2342            return super.onTransact(code, data, reply, flags);
2343        } catch (RuntimeException e) {
2344            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2345                Slog.wtf(TAG, "Package Manager Crash", e);
2346            }
2347            throw e;
2348        }
2349    }
2350
2351    void cleanupInstallFailedPackage(PackageSetting ps) {
2352        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2353
2354        removeDataDirsLI(ps.name);
2355        if (ps.codePath != null) {
2356            if (ps.codePath.isDirectory()) {
2357                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2358            } else {
2359                ps.codePath.delete();
2360            }
2361        }
2362        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2363            if (ps.resourcePath.isDirectory()) {
2364                FileUtils.deleteContents(ps.resourcePath);
2365            }
2366            ps.resourcePath.delete();
2367        }
2368        mSettings.removePackageLPw(ps.name);
2369    }
2370
2371    static int[] appendInts(int[] cur, int[] add) {
2372        if (add == null) return cur;
2373        if (cur == null) return add;
2374        final int N = add.length;
2375        for (int i=0; i<N; i++) {
2376            cur = appendInt(cur, add[i]);
2377        }
2378        return cur;
2379    }
2380
2381    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2382        if (!sUserManager.exists(userId)) return null;
2383        final PackageSetting ps = (PackageSetting) p.mExtras;
2384        if (ps == null) {
2385            return null;
2386        }
2387
2388        final PermissionsState permissionsState = ps.getPermissionsState();
2389
2390        final int[] gids = permissionsState.computeGids(userId);
2391        final Set<String> permissions = permissionsState.getPermissions(userId);
2392        final PackageUserState state = ps.readUserState(userId);
2393
2394        return PackageParser.generatePackageInfo(p, gids, flags,
2395                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2396    }
2397
2398    @Override
2399    public boolean isPackageAvailable(String packageName, int userId) {
2400        if (!sUserManager.exists(userId)) return false;
2401        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2402        synchronized (mPackages) {
2403            PackageParser.Package p = mPackages.get(packageName);
2404            if (p != null) {
2405                final PackageSetting ps = (PackageSetting) p.mExtras;
2406                if (ps != null) {
2407                    final PackageUserState state = ps.readUserState(userId);
2408                    if (state != null) {
2409                        return PackageParser.isAvailable(state);
2410                    }
2411                }
2412            }
2413        }
2414        return false;
2415    }
2416
2417    @Override
2418    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2419        if (!sUserManager.exists(userId)) return null;
2420        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2421        // reader
2422        synchronized (mPackages) {
2423            PackageParser.Package p = mPackages.get(packageName);
2424            if (DEBUG_PACKAGE_INFO)
2425                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2426            if (p != null) {
2427                return generatePackageInfo(p, flags, userId);
2428            }
2429            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2430                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2431            }
2432        }
2433        return null;
2434    }
2435
2436    @Override
2437    public String[] currentToCanonicalPackageNames(String[] names) {
2438        String[] out = new String[names.length];
2439        // reader
2440        synchronized (mPackages) {
2441            for (int i=names.length-1; i>=0; i--) {
2442                PackageSetting ps = mSettings.mPackages.get(names[i]);
2443                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2444            }
2445        }
2446        return out;
2447    }
2448
2449    @Override
2450    public String[] canonicalToCurrentPackageNames(String[] names) {
2451        String[] out = new String[names.length];
2452        // reader
2453        synchronized (mPackages) {
2454            for (int i=names.length-1; i>=0; i--) {
2455                String cur = mSettings.mRenamedPackages.get(names[i]);
2456                out[i] = cur != null ? cur : names[i];
2457            }
2458        }
2459        return out;
2460    }
2461
2462    @Override
2463    public int getPackageUid(String packageName, int userId) {
2464        if (!sUserManager.exists(userId)) return -1;
2465        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2466
2467        // reader
2468        synchronized (mPackages) {
2469            PackageParser.Package p = mPackages.get(packageName);
2470            if(p != null) {
2471                return UserHandle.getUid(userId, p.applicationInfo.uid);
2472            }
2473            PackageSetting ps = mSettings.mPackages.get(packageName);
2474            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2475                return -1;
2476            }
2477            p = ps.pkg;
2478            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2479        }
2480    }
2481
2482    @Override
2483    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2484        if (!sUserManager.exists(userId)) {
2485            return null;
2486        }
2487
2488        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2489                "getPackageGids");
2490
2491        // reader
2492        synchronized (mPackages) {
2493            PackageParser.Package p = mPackages.get(packageName);
2494            if (DEBUG_PACKAGE_INFO) {
2495                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2496            }
2497            if (p != null) {
2498                PackageSetting ps = (PackageSetting) p.mExtras;
2499                return ps.getPermissionsState().computeGids(userId);
2500            }
2501        }
2502
2503        return null;
2504    }
2505
2506    static PermissionInfo generatePermissionInfo(
2507            BasePermission bp, int flags) {
2508        if (bp.perm != null) {
2509            return PackageParser.generatePermissionInfo(bp.perm, flags);
2510        }
2511        PermissionInfo pi = new PermissionInfo();
2512        pi.name = bp.name;
2513        pi.packageName = bp.sourcePackage;
2514        pi.nonLocalizedLabel = bp.name;
2515        pi.protectionLevel = bp.protectionLevel;
2516        return pi;
2517    }
2518
2519    @Override
2520    public PermissionInfo getPermissionInfo(String name, int flags) {
2521        // reader
2522        synchronized (mPackages) {
2523            final BasePermission p = mSettings.mPermissions.get(name);
2524            if (p != null) {
2525                return generatePermissionInfo(p, flags);
2526            }
2527            return null;
2528        }
2529    }
2530
2531    @Override
2532    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2533        // reader
2534        synchronized (mPackages) {
2535            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2536            for (BasePermission p : mSettings.mPermissions.values()) {
2537                if (group == null) {
2538                    if (p.perm == null || p.perm.info.group == null) {
2539                        out.add(generatePermissionInfo(p, flags));
2540                    }
2541                } else {
2542                    if (p.perm != null && group.equals(p.perm.info.group)) {
2543                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2544                    }
2545                }
2546            }
2547
2548            if (out.size() > 0) {
2549                return out;
2550            }
2551            return mPermissionGroups.containsKey(group) ? out : null;
2552        }
2553    }
2554
2555    @Override
2556    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2557        // reader
2558        synchronized (mPackages) {
2559            return PackageParser.generatePermissionGroupInfo(
2560                    mPermissionGroups.get(name), flags);
2561        }
2562    }
2563
2564    @Override
2565    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2566        // reader
2567        synchronized (mPackages) {
2568            final int N = mPermissionGroups.size();
2569            ArrayList<PermissionGroupInfo> out
2570                    = new ArrayList<PermissionGroupInfo>(N);
2571            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2572                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2573            }
2574            return out;
2575        }
2576    }
2577
2578    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2579            int userId) {
2580        if (!sUserManager.exists(userId)) return null;
2581        PackageSetting ps = mSettings.mPackages.get(packageName);
2582        if (ps != null) {
2583            if (ps.pkg == null) {
2584                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2585                        flags, userId);
2586                if (pInfo != null) {
2587                    return pInfo.applicationInfo;
2588                }
2589                return null;
2590            }
2591            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2592                    ps.readUserState(userId), userId);
2593        }
2594        return null;
2595    }
2596
2597    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2598            int userId) {
2599        if (!sUserManager.exists(userId)) return null;
2600        PackageSetting ps = mSettings.mPackages.get(packageName);
2601        if (ps != null) {
2602            PackageParser.Package pkg = ps.pkg;
2603            if (pkg == null) {
2604                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2605                    return null;
2606                }
2607                // Only data remains, so we aren't worried about code paths
2608                pkg = new PackageParser.Package(packageName);
2609                pkg.applicationInfo.packageName = packageName;
2610                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2611                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2612                pkg.applicationInfo.dataDir =
2613                        getDataPathForPackage(packageName, 0).getPath();
2614                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2615                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2616            }
2617            return generatePackageInfo(pkg, flags, userId);
2618        }
2619        return null;
2620    }
2621
2622    @Override
2623    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2624        if (!sUserManager.exists(userId)) return null;
2625        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2626        // writer
2627        synchronized (mPackages) {
2628            PackageParser.Package p = mPackages.get(packageName);
2629            if (DEBUG_PACKAGE_INFO) Log.v(
2630                    TAG, "getApplicationInfo " + packageName
2631                    + ": " + p);
2632            if (p != null) {
2633                PackageSetting ps = mSettings.mPackages.get(packageName);
2634                if (ps == null) return null;
2635                // Note: isEnabledLP() does not apply here - always return info
2636                return PackageParser.generateApplicationInfo(
2637                        p, flags, ps.readUserState(userId), userId);
2638            }
2639            if ("android".equals(packageName)||"system".equals(packageName)) {
2640                return mAndroidApplication;
2641            }
2642            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2643                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2644            }
2645        }
2646        return null;
2647    }
2648
2649
2650    @Override
2651    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2652        mContext.enforceCallingOrSelfPermission(
2653                android.Manifest.permission.CLEAR_APP_CACHE, null);
2654        // Queue up an async operation since clearing cache may take a little while.
2655        mHandler.post(new Runnable() {
2656            public void run() {
2657                mHandler.removeCallbacks(this);
2658                int retCode = -1;
2659                synchronized (mInstallLock) {
2660                    retCode = mInstaller.freeCache(freeStorageSize);
2661                    if (retCode < 0) {
2662                        Slog.w(TAG, "Couldn't clear application caches");
2663                    }
2664                }
2665                if (observer != null) {
2666                    try {
2667                        observer.onRemoveCompleted(null, (retCode >= 0));
2668                    } catch (RemoteException e) {
2669                        Slog.w(TAG, "RemoveException when invoking call back");
2670                    }
2671                }
2672            }
2673        });
2674    }
2675
2676    @Override
2677    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2678        mContext.enforceCallingOrSelfPermission(
2679                android.Manifest.permission.CLEAR_APP_CACHE, null);
2680        // Queue up an async operation since clearing cache may take a little while.
2681        mHandler.post(new Runnable() {
2682            public void run() {
2683                mHandler.removeCallbacks(this);
2684                int retCode = -1;
2685                synchronized (mInstallLock) {
2686                    retCode = mInstaller.freeCache(freeStorageSize);
2687                    if (retCode < 0) {
2688                        Slog.w(TAG, "Couldn't clear application caches");
2689                    }
2690                }
2691                if(pi != null) {
2692                    try {
2693                        // Callback via pending intent
2694                        int code = (retCode >= 0) ? 1 : 0;
2695                        pi.sendIntent(null, code, null,
2696                                null, null);
2697                    } catch (SendIntentException e1) {
2698                        Slog.i(TAG, "Failed to send pending intent");
2699                    }
2700                }
2701            }
2702        });
2703    }
2704
2705    void freeStorage(long freeStorageSize) throws IOException {
2706        synchronized (mInstallLock) {
2707            if (mInstaller.freeCache(freeStorageSize) < 0) {
2708                throw new IOException("Failed to free enough space");
2709            }
2710        }
2711    }
2712
2713    @Override
2714    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2715        if (!sUserManager.exists(userId)) return null;
2716        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2717        synchronized (mPackages) {
2718            PackageParser.Activity a = mActivities.mActivities.get(component);
2719
2720            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2721            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2722                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2723                if (ps == null) return null;
2724                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2725                        userId);
2726            }
2727            if (mResolveComponentName.equals(component)) {
2728                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2729                        new PackageUserState(), userId);
2730            }
2731        }
2732        return null;
2733    }
2734
2735    @Override
2736    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2737            String resolvedType) {
2738        synchronized (mPackages) {
2739            PackageParser.Activity a = mActivities.mActivities.get(component);
2740            if (a == null) {
2741                return false;
2742            }
2743            for (int i=0; i<a.intents.size(); i++) {
2744                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2745                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2746                    return true;
2747                }
2748            }
2749            return false;
2750        }
2751    }
2752
2753    @Override
2754    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2755        if (!sUserManager.exists(userId)) return null;
2756        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2757        synchronized (mPackages) {
2758            PackageParser.Activity a = mReceivers.mActivities.get(component);
2759            if (DEBUG_PACKAGE_INFO) Log.v(
2760                TAG, "getReceiverInfo " + component + ": " + a);
2761            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2762                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2763                if (ps == null) return null;
2764                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2765                        userId);
2766            }
2767        }
2768        return null;
2769    }
2770
2771    @Override
2772    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2773        if (!sUserManager.exists(userId)) return null;
2774        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2775        synchronized (mPackages) {
2776            PackageParser.Service s = mServices.mServices.get(component);
2777            if (DEBUG_PACKAGE_INFO) Log.v(
2778                TAG, "getServiceInfo " + component + ": " + s);
2779            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2780                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2781                if (ps == null) return null;
2782                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2783                        userId);
2784            }
2785        }
2786        return null;
2787    }
2788
2789    @Override
2790    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2791        if (!sUserManager.exists(userId)) return null;
2792        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2793        synchronized (mPackages) {
2794            PackageParser.Provider p = mProviders.mProviders.get(component);
2795            if (DEBUG_PACKAGE_INFO) Log.v(
2796                TAG, "getProviderInfo " + component + ": " + p);
2797            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2798                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2799                if (ps == null) return null;
2800                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2801                        userId);
2802            }
2803        }
2804        return null;
2805    }
2806
2807    @Override
2808    public String[] getSystemSharedLibraryNames() {
2809        Set<String> libSet;
2810        synchronized (mPackages) {
2811            libSet = mSharedLibraries.keySet();
2812            int size = libSet.size();
2813            if (size > 0) {
2814                String[] libs = new String[size];
2815                libSet.toArray(libs);
2816                return libs;
2817            }
2818        }
2819        return null;
2820    }
2821
2822    /**
2823     * @hide
2824     */
2825    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2826        synchronized (mPackages) {
2827            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2828            if (lib != null && lib.apk != null) {
2829                return mPackages.get(lib.apk);
2830            }
2831        }
2832        return null;
2833    }
2834
2835    @Override
2836    public FeatureInfo[] getSystemAvailableFeatures() {
2837        Collection<FeatureInfo> featSet;
2838        synchronized (mPackages) {
2839            featSet = mAvailableFeatures.values();
2840            int size = featSet.size();
2841            if (size > 0) {
2842                FeatureInfo[] features = new FeatureInfo[size+1];
2843                featSet.toArray(features);
2844                FeatureInfo fi = new FeatureInfo();
2845                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2846                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2847                features[size] = fi;
2848                return features;
2849            }
2850        }
2851        return null;
2852    }
2853
2854    @Override
2855    public boolean hasSystemFeature(String name) {
2856        synchronized (mPackages) {
2857            return mAvailableFeatures.containsKey(name);
2858        }
2859    }
2860
2861    private void checkValidCaller(int uid, int userId) {
2862        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2863            return;
2864
2865        throw new SecurityException("Caller uid=" + uid
2866                + " is not privileged to communicate with user=" + userId);
2867    }
2868
2869    @Override
2870    public int checkPermission(String permName, String pkgName, int userId) {
2871        if (!sUserManager.exists(userId)) {
2872            return PackageManager.PERMISSION_DENIED;
2873        }
2874
2875        synchronized (mPackages) {
2876            final PackageParser.Package p = mPackages.get(pkgName);
2877            if (p != null && p.mExtras != null) {
2878                final PackageSetting ps = (PackageSetting) p.mExtras;
2879                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2880                    return PackageManager.PERMISSION_GRANTED;
2881                }
2882            }
2883        }
2884
2885        return PackageManager.PERMISSION_DENIED;
2886    }
2887
2888    @Override
2889    public int checkUidPermission(String permName, int uid) {
2890        final int userId = UserHandle.getUserId(uid);
2891
2892        if (!sUserManager.exists(userId)) {
2893            return PackageManager.PERMISSION_DENIED;
2894        }
2895
2896        synchronized (mPackages) {
2897            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2898            if (obj != null) {
2899                final SettingBase ps = (SettingBase) obj;
2900                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2901                    return PackageManager.PERMISSION_GRANTED;
2902                }
2903            } else {
2904                ArraySet<String> perms = mSystemPermissions.get(uid);
2905                if (perms != null && perms.contains(permName)) {
2906                    return PackageManager.PERMISSION_GRANTED;
2907                }
2908            }
2909        }
2910
2911        return PackageManager.PERMISSION_DENIED;
2912    }
2913
2914    /**
2915     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2916     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2917     * @param checkShell TODO(yamasani):
2918     * @param message the message to log on security exception
2919     */
2920    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2921            boolean checkShell, String message) {
2922        if (userId < 0) {
2923            throw new IllegalArgumentException("Invalid userId " + userId);
2924        }
2925        if (checkShell) {
2926            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2927        }
2928        if (userId == UserHandle.getUserId(callingUid)) return;
2929        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2930            if (requireFullPermission) {
2931                mContext.enforceCallingOrSelfPermission(
2932                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2933            } else {
2934                try {
2935                    mContext.enforceCallingOrSelfPermission(
2936                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2937                } catch (SecurityException se) {
2938                    mContext.enforceCallingOrSelfPermission(
2939                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2940                }
2941            }
2942        }
2943    }
2944
2945    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2946        if (callingUid == Process.SHELL_UID) {
2947            if (userHandle >= 0
2948                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2949                throw new SecurityException("Shell does not have permission to access user "
2950                        + userHandle);
2951            } else if (userHandle < 0) {
2952                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2953                        + Debug.getCallers(3));
2954            }
2955        }
2956    }
2957
2958    private BasePermission findPermissionTreeLP(String permName) {
2959        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2960            if (permName.startsWith(bp.name) &&
2961                    permName.length() > bp.name.length() &&
2962                    permName.charAt(bp.name.length()) == '.') {
2963                return bp;
2964            }
2965        }
2966        return null;
2967    }
2968
2969    private BasePermission checkPermissionTreeLP(String permName) {
2970        if (permName != null) {
2971            BasePermission bp = findPermissionTreeLP(permName);
2972            if (bp != null) {
2973                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2974                    return bp;
2975                }
2976                throw new SecurityException("Calling uid "
2977                        + Binder.getCallingUid()
2978                        + " is not allowed to add to permission tree "
2979                        + bp.name + " owned by uid " + bp.uid);
2980            }
2981        }
2982        throw new SecurityException("No permission tree found for " + permName);
2983    }
2984
2985    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2986        if (s1 == null) {
2987            return s2 == null;
2988        }
2989        if (s2 == null) {
2990            return false;
2991        }
2992        if (s1.getClass() != s2.getClass()) {
2993            return false;
2994        }
2995        return s1.equals(s2);
2996    }
2997
2998    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2999        if (pi1.icon != pi2.icon) return false;
3000        if (pi1.logo != pi2.logo) return false;
3001        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3002        if (!compareStrings(pi1.name, pi2.name)) return false;
3003        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3004        // We'll take care of setting this one.
3005        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3006        // These are not currently stored in settings.
3007        //if (!compareStrings(pi1.group, pi2.group)) return false;
3008        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3009        //if (pi1.labelRes != pi2.labelRes) return false;
3010        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3011        return true;
3012    }
3013
3014    int permissionInfoFootprint(PermissionInfo info) {
3015        int size = info.name.length();
3016        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3017        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3018        return size;
3019    }
3020
3021    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3022        int size = 0;
3023        for (BasePermission perm : mSettings.mPermissions.values()) {
3024            if (perm.uid == tree.uid) {
3025                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3026            }
3027        }
3028        return size;
3029    }
3030
3031    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3032        // We calculate the max size of permissions defined by this uid and throw
3033        // if that plus the size of 'info' would exceed our stated maximum.
3034        if (tree.uid != Process.SYSTEM_UID) {
3035            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3036            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3037                throw new SecurityException("Permission tree size cap exceeded");
3038            }
3039        }
3040    }
3041
3042    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3043        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3044            throw new SecurityException("Label must be specified in permission");
3045        }
3046        BasePermission tree = checkPermissionTreeLP(info.name);
3047        BasePermission bp = mSettings.mPermissions.get(info.name);
3048        boolean added = bp == null;
3049        boolean changed = true;
3050        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3051        if (added) {
3052            enforcePermissionCapLocked(info, tree);
3053            bp = new BasePermission(info.name, tree.sourcePackage,
3054                    BasePermission.TYPE_DYNAMIC);
3055        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3056            throw new SecurityException(
3057                    "Not allowed to modify non-dynamic permission "
3058                    + info.name);
3059        } else {
3060            if (bp.protectionLevel == fixedLevel
3061                    && bp.perm.owner.equals(tree.perm.owner)
3062                    && bp.uid == tree.uid
3063                    && comparePermissionInfos(bp.perm.info, info)) {
3064                changed = false;
3065            }
3066        }
3067        bp.protectionLevel = fixedLevel;
3068        info = new PermissionInfo(info);
3069        info.protectionLevel = fixedLevel;
3070        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3071        bp.perm.info.packageName = tree.perm.info.packageName;
3072        bp.uid = tree.uid;
3073        if (added) {
3074            mSettings.mPermissions.put(info.name, bp);
3075        }
3076        if (changed) {
3077            if (!async) {
3078                mSettings.writeLPr();
3079            } else {
3080                scheduleWriteSettingsLocked();
3081            }
3082        }
3083        return added;
3084    }
3085
3086    @Override
3087    public boolean addPermission(PermissionInfo info) {
3088        synchronized (mPackages) {
3089            return addPermissionLocked(info, false);
3090        }
3091    }
3092
3093    @Override
3094    public boolean addPermissionAsync(PermissionInfo info) {
3095        synchronized (mPackages) {
3096            return addPermissionLocked(info, true);
3097        }
3098    }
3099
3100    @Override
3101    public void removePermission(String name) {
3102        synchronized (mPackages) {
3103            checkPermissionTreeLP(name);
3104            BasePermission bp = mSettings.mPermissions.get(name);
3105            if (bp != null) {
3106                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3107                    throw new SecurityException(
3108                            "Not allowed to modify non-dynamic permission "
3109                            + name);
3110                }
3111                mSettings.mPermissions.remove(name);
3112                mSettings.writeLPr();
3113            }
3114        }
3115    }
3116
3117    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3118            BasePermission bp) {
3119        int index = pkg.requestedPermissions.indexOf(bp.name);
3120        if (index == -1) {
3121            throw new SecurityException("Package " + pkg.packageName
3122                    + " has not requested permission " + bp.name);
3123        }
3124        if (!bp.isRuntime()) {
3125            throw new SecurityException("Permission " + bp.name
3126                    + " is not a changeable permission type");
3127        }
3128    }
3129
3130    @Override
3131    public boolean grantPermission(String packageName, String name, int userId) {
3132        if (!RUNTIME_PERMISSIONS_ENABLED) {
3133            return false;
3134        }
3135
3136        if (!sUserManager.exists(userId)) {
3137            return false;
3138        }
3139
3140        mContext.enforceCallingOrSelfPermission(
3141                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3142                "grantPermission");
3143
3144        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3145                "grantPermission");
3146
3147        boolean gidsChanged = false;
3148        final SettingBase sb;
3149
3150        synchronized (mPackages) {
3151            final PackageParser.Package pkg = mPackages.get(packageName);
3152            if (pkg == null) {
3153                throw new IllegalArgumentException("Unknown package: " + packageName);
3154            }
3155
3156            final BasePermission bp = mSettings.mPermissions.get(name);
3157            if (bp == null) {
3158                throw new IllegalArgumentException("Unknown permission: " + name);
3159            }
3160
3161            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3162
3163            sb = (SettingBase) pkg.mExtras;
3164            if (sb == null) {
3165                throw new IllegalArgumentException("Unknown package: " + packageName);
3166            }
3167
3168            final PermissionsState permissionsState = sb.getPermissionsState();
3169
3170            final int result = permissionsState.grantRuntimePermission(bp, userId);
3171            switch (result) {
3172                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3173                    return false;
3174                }
3175
3176                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3177                    gidsChanged = true;
3178                } break;
3179            }
3180
3181            // Not critical if that is lost - app has to request again.
3182            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3183        }
3184
3185        if (gidsChanged) {
3186            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3187        }
3188
3189        return true;
3190    }
3191
3192    @Override
3193    public boolean revokePermission(String packageName, String name, int userId) {
3194        if (!RUNTIME_PERMISSIONS_ENABLED) {
3195            return false;
3196        }
3197
3198        if (!sUserManager.exists(userId)) {
3199            return false;
3200        }
3201
3202        mContext.enforceCallingOrSelfPermission(
3203                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3204                "revokePermission");
3205
3206        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3207                "revokePermission");
3208
3209        final SettingBase sb;
3210
3211        synchronized (mPackages) {
3212            final PackageParser.Package pkg = mPackages.get(packageName);
3213            if (pkg == null) {
3214                throw new IllegalArgumentException("Unknown package: " + packageName);
3215            }
3216
3217            final BasePermission bp = mSettings.mPermissions.get(name);
3218            if (bp == null) {
3219                throw new IllegalArgumentException("Unknown permission: " + name);
3220            }
3221
3222            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3223
3224            sb = (SettingBase) pkg.mExtras;
3225            if (sb == null) {
3226                throw new IllegalArgumentException("Unknown package: " + packageName);
3227            }
3228
3229            final PermissionsState permissionsState = sb.getPermissionsState();
3230
3231            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3232                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3233                return false;
3234            }
3235
3236            // Critical, after this call all should never have the permission.
3237            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3238        }
3239
3240        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3241
3242        return true;
3243    }
3244
3245    @Override
3246    public boolean isProtectedBroadcast(String actionName) {
3247        synchronized (mPackages) {
3248            return mProtectedBroadcasts.contains(actionName);
3249        }
3250    }
3251
3252    @Override
3253    public int checkSignatures(String pkg1, String pkg2) {
3254        synchronized (mPackages) {
3255            final PackageParser.Package p1 = mPackages.get(pkg1);
3256            final PackageParser.Package p2 = mPackages.get(pkg2);
3257            if (p1 == null || p1.mExtras == null
3258                    || p2 == null || p2.mExtras == null) {
3259                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3260            }
3261            return compareSignatures(p1.mSignatures, p2.mSignatures);
3262        }
3263    }
3264
3265    @Override
3266    public int checkUidSignatures(int uid1, int uid2) {
3267        // Map to base uids.
3268        uid1 = UserHandle.getAppId(uid1);
3269        uid2 = UserHandle.getAppId(uid2);
3270        // reader
3271        synchronized (mPackages) {
3272            Signature[] s1;
3273            Signature[] s2;
3274            Object obj = mSettings.getUserIdLPr(uid1);
3275            if (obj != null) {
3276                if (obj instanceof SharedUserSetting) {
3277                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3278                } else if (obj instanceof PackageSetting) {
3279                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3280                } else {
3281                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3282                }
3283            } else {
3284                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3285            }
3286            obj = mSettings.getUserIdLPr(uid2);
3287            if (obj != null) {
3288                if (obj instanceof SharedUserSetting) {
3289                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3290                } else if (obj instanceof PackageSetting) {
3291                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3292                } else {
3293                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3294                }
3295            } else {
3296                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3297            }
3298            return compareSignatures(s1, s2);
3299        }
3300    }
3301
3302    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3303        final long identity = Binder.clearCallingIdentity();
3304        try {
3305            if (sb instanceof SharedUserSetting) {
3306                SharedUserSetting sus = (SharedUserSetting) sb;
3307                final int packageCount = sus.packages.size();
3308                for (int i = 0; i < packageCount; i++) {
3309                    PackageSetting susPs = sus.packages.valueAt(i);
3310                    if (userId == UserHandle.USER_ALL) {
3311                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3312                    } else {
3313                        final int uid = UserHandle.getUid(userId, susPs.appId);
3314                        killUid(uid, reason);
3315                    }
3316                }
3317            } else if (sb instanceof PackageSetting) {
3318                PackageSetting ps = (PackageSetting) sb;
3319                if (userId == UserHandle.USER_ALL) {
3320                    killApplication(ps.pkg.packageName, ps.appId, reason);
3321                } else {
3322                    final int uid = UserHandle.getUid(userId, ps.appId);
3323                    killUid(uid, reason);
3324                }
3325            }
3326        } finally {
3327            Binder.restoreCallingIdentity(identity);
3328        }
3329    }
3330
3331    private static void killUid(int uid, String reason) {
3332        IActivityManager am = ActivityManagerNative.getDefault();
3333        if (am != null) {
3334            try {
3335                am.killUid(uid, reason);
3336            } catch (RemoteException e) {
3337                /* ignore - same process */
3338            }
3339        }
3340    }
3341
3342    /**
3343     * Compares two sets of signatures. Returns:
3344     * <br />
3345     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3346     * <br />
3347     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3348     * <br />
3349     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3350     * <br />
3351     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3352     * <br />
3353     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3354     */
3355    static int compareSignatures(Signature[] s1, Signature[] s2) {
3356        if (s1 == null) {
3357            return s2 == null
3358                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3359                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3360        }
3361
3362        if (s2 == null) {
3363            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3364        }
3365
3366        if (s1.length != s2.length) {
3367            return PackageManager.SIGNATURE_NO_MATCH;
3368        }
3369
3370        // Since both signature sets are of size 1, we can compare without HashSets.
3371        if (s1.length == 1) {
3372            return s1[0].equals(s2[0]) ?
3373                    PackageManager.SIGNATURE_MATCH :
3374                    PackageManager.SIGNATURE_NO_MATCH;
3375        }
3376
3377        ArraySet<Signature> set1 = new ArraySet<Signature>();
3378        for (Signature sig : s1) {
3379            set1.add(sig);
3380        }
3381        ArraySet<Signature> set2 = new ArraySet<Signature>();
3382        for (Signature sig : s2) {
3383            set2.add(sig);
3384        }
3385        // Make sure s2 contains all signatures in s1.
3386        if (set1.equals(set2)) {
3387            return PackageManager.SIGNATURE_MATCH;
3388        }
3389        return PackageManager.SIGNATURE_NO_MATCH;
3390    }
3391
3392    /**
3393     * If the database version for this type of package (internal storage or
3394     * external storage) is less than the version where package signatures
3395     * were updated, return true.
3396     */
3397    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3398        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3399                DatabaseVersion.SIGNATURE_END_ENTITY))
3400                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3401                        DatabaseVersion.SIGNATURE_END_ENTITY));
3402    }
3403
3404    /**
3405     * Used for backward compatibility to make sure any packages with
3406     * certificate chains get upgraded to the new style. {@code existingSigs}
3407     * will be in the old format (since they were stored on disk from before the
3408     * system upgrade) and {@code scannedSigs} will be in the newer format.
3409     */
3410    private int compareSignaturesCompat(PackageSignatures existingSigs,
3411            PackageParser.Package scannedPkg) {
3412        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3413            return PackageManager.SIGNATURE_NO_MATCH;
3414        }
3415
3416        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3417        for (Signature sig : existingSigs.mSignatures) {
3418            existingSet.add(sig);
3419        }
3420        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3421        for (Signature sig : scannedPkg.mSignatures) {
3422            try {
3423                Signature[] chainSignatures = sig.getChainSignatures();
3424                for (Signature chainSig : chainSignatures) {
3425                    scannedCompatSet.add(chainSig);
3426                }
3427            } catch (CertificateEncodingException e) {
3428                scannedCompatSet.add(sig);
3429            }
3430        }
3431        /*
3432         * Make sure the expanded scanned set contains all signatures in the
3433         * existing one.
3434         */
3435        if (scannedCompatSet.equals(existingSet)) {
3436            // Migrate the old signatures to the new scheme.
3437            existingSigs.assignSignatures(scannedPkg.mSignatures);
3438            // The new KeySets will be re-added later in the scanning process.
3439            synchronized (mPackages) {
3440                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3441            }
3442            return PackageManager.SIGNATURE_MATCH;
3443        }
3444        return PackageManager.SIGNATURE_NO_MATCH;
3445    }
3446
3447    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3448        if (isExternal(scannedPkg)) {
3449            return mSettings.isExternalDatabaseVersionOlderThan(
3450                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3451        } else {
3452            return mSettings.isInternalDatabaseVersionOlderThan(
3453                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3454        }
3455    }
3456
3457    private int compareSignaturesRecover(PackageSignatures existingSigs,
3458            PackageParser.Package scannedPkg) {
3459        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3460            return PackageManager.SIGNATURE_NO_MATCH;
3461        }
3462
3463        String msg = null;
3464        try {
3465            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3466                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3467                        + scannedPkg.packageName);
3468                return PackageManager.SIGNATURE_MATCH;
3469            }
3470        } catch (CertificateException e) {
3471            msg = e.getMessage();
3472        }
3473
3474        logCriticalInfo(Log.INFO,
3475                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3476        return PackageManager.SIGNATURE_NO_MATCH;
3477    }
3478
3479    @Override
3480    public String[] getPackagesForUid(int uid) {
3481        uid = UserHandle.getAppId(uid);
3482        // reader
3483        synchronized (mPackages) {
3484            Object obj = mSettings.getUserIdLPr(uid);
3485            if (obj instanceof SharedUserSetting) {
3486                final SharedUserSetting sus = (SharedUserSetting) obj;
3487                final int N = sus.packages.size();
3488                final String[] res = new String[N];
3489                final Iterator<PackageSetting> it = sus.packages.iterator();
3490                int i = 0;
3491                while (it.hasNext()) {
3492                    res[i++] = it.next().name;
3493                }
3494                return res;
3495            } else if (obj instanceof PackageSetting) {
3496                final PackageSetting ps = (PackageSetting) obj;
3497                return new String[] { ps.name };
3498            }
3499        }
3500        return null;
3501    }
3502
3503    @Override
3504    public String getNameForUid(int uid) {
3505        // reader
3506        synchronized (mPackages) {
3507            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3508            if (obj instanceof SharedUserSetting) {
3509                final SharedUserSetting sus = (SharedUserSetting) obj;
3510                return sus.name + ":" + sus.userId;
3511            } else if (obj instanceof PackageSetting) {
3512                final PackageSetting ps = (PackageSetting) obj;
3513                return ps.name;
3514            }
3515        }
3516        return null;
3517    }
3518
3519    @Override
3520    public int getUidForSharedUser(String sharedUserName) {
3521        if(sharedUserName == null) {
3522            return -1;
3523        }
3524        // reader
3525        synchronized (mPackages) {
3526            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3527            if (suid == null) {
3528                return -1;
3529            }
3530            return suid.userId;
3531        }
3532    }
3533
3534    @Override
3535    public int getFlagsForUid(int uid) {
3536        synchronized (mPackages) {
3537            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3538            if (obj instanceof SharedUserSetting) {
3539                final SharedUserSetting sus = (SharedUserSetting) obj;
3540                return sus.pkgFlags;
3541            } else if (obj instanceof PackageSetting) {
3542                final PackageSetting ps = (PackageSetting) obj;
3543                return ps.pkgFlags;
3544            }
3545        }
3546        return 0;
3547    }
3548
3549    @Override
3550    public int getPrivateFlagsForUid(int uid) {
3551        synchronized (mPackages) {
3552            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3553            if (obj instanceof SharedUserSetting) {
3554                final SharedUserSetting sus = (SharedUserSetting) obj;
3555                return sus.pkgPrivateFlags;
3556            } else if (obj instanceof PackageSetting) {
3557                final PackageSetting ps = (PackageSetting) obj;
3558                return ps.pkgPrivateFlags;
3559            }
3560        }
3561        return 0;
3562    }
3563
3564    @Override
3565    public boolean isUidPrivileged(int uid) {
3566        uid = UserHandle.getAppId(uid);
3567        // reader
3568        synchronized (mPackages) {
3569            Object obj = mSettings.getUserIdLPr(uid);
3570            if (obj instanceof SharedUserSetting) {
3571                final SharedUserSetting sus = (SharedUserSetting) obj;
3572                final Iterator<PackageSetting> it = sus.packages.iterator();
3573                while (it.hasNext()) {
3574                    if (it.next().isPrivileged()) {
3575                        return true;
3576                    }
3577                }
3578            } else if (obj instanceof PackageSetting) {
3579                final PackageSetting ps = (PackageSetting) obj;
3580                return ps.isPrivileged();
3581            }
3582        }
3583        return false;
3584    }
3585
3586    @Override
3587    public String[] getAppOpPermissionPackages(String permissionName) {
3588        synchronized (mPackages) {
3589            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3590            if (pkgs == null) {
3591                return null;
3592            }
3593            return pkgs.toArray(new String[pkgs.size()]);
3594        }
3595    }
3596
3597    @Override
3598    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3599            int flags, int userId) {
3600        if (!sUserManager.exists(userId)) return null;
3601        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3602        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3603        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3604    }
3605
3606    @Override
3607    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3608            IntentFilter filter, int match, ComponentName activity) {
3609        final int userId = UserHandle.getCallingUserId();
3610        if (DEBUG_PREFERRED) {
3611            Log.v(TAG, "setLastChosenActivity intent=" + intent
3612                + " resolvedType=" + resolvedType
3613                + " flags=" + flags
3614                + " filter=" + filter
3615                + " match=" + match
3616                + " activity=" + activity);
3617            filter.dump(new PrintStreamPrinter(System.out), "    ");
3618        }
3619        intent.setComponent(null);
3620        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3621        // Find any earlier preferred or last chosen entries and nuke them
3622        findPreferredActivity(intent, resolvedType,
3623                flags, query, 0, false, true, false, userId);
3624        // Add the new activity as the last chosen for this filter
3625        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3626                "Setting last chosen");
3627    }
3628
3629    @Override
3630    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3631        final int userId = UserHandle.getCallingUserId();
3632        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3633        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3634        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3635                false, false, false, userId);
3636    }
3637
3638    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3639            int flags, List<ResolveInfo> query, int userId) {
3640        if (query != null) {
3641            final int N = query.size();
3642            if (N == 1) {
3643                return query.get(0);
3644            } else if (N > 1) {
3645                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3646                // If there is more than one activity with the same priority,
3647                // then let the user decide between them.
3648                ResolveInfo r0 = query.get(0);
3649                ResolveInfo r1 = query.get(1);
3650                if (DEBUG_INTENT_MATCHING || debug) {
3651                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3652                            + r1.activityInfo.name + "=" + r1.priority);
3653                }
3654                // If the first activity has a higher priority, or a different
3655                // default, then it is always desireable to pick it.
3656                if (r0.priority != r1.priority
3657                        || r0.preferredOrder != r1.preferredOrder
3658                        || r0.isDefault != r1.isDefault) {
3659                    return query.get(0);
3660                }
3661                // If we have saved a preference for a preferred activity for
3662                // this Intent, use that.
3663                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3664                        flags, query, r0.priority, true, false, debug, userId);
3665                if (ri != null) {
3666                    return ri;
3667                }
3668                if (userId != 0) {
3669                    ri = new ResolveInfo(mResolveInfo);
3670                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3671                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3672                            ri.activityInfo.applicationInfo);
3673                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3674                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3675                    return ri;
3676                }
3677                return mResolveInfo;
3678            }
3679        }
3680        return null;
3681    }
3682
3683    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3684            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3685        final int N = query.size();
3686        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3687                .get(userId);
3688        // Get the list of persistent preferred activities that handle the intent
3689        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3690        List<PersistentPreferredActivity> pprefs = ppir != null
3691                ? ppir.queryIntent(intent, resolvedType,
3692                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3693                : null;
3694        if (pprefs != null && pprefs.size() > 0) {
3695            final int M = pprefs.size();
3696            for (int i=0; i<M; i++) {
3697                final PersistentPreferredActivity ppa = pprefs.get(i);
3698                if (DEBUG_PREFERRED || debug) {
3699                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3700                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3701                            + "\n  component=" + ppa.mComponent);
3702                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3703                }
3704                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3705                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3706                if (DEBUG_PREFERRED || debug) {
3707                    Slog.v(TAG, "Found persistent preferred activity:");
3708                    if (ai != null) {
3709                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3710                    } else {
3711                        Slog.v(TAG, "  null");
3712                    }
3713                }
3714                if (ai == null) {
3715                    // This previously registered persistent preferred activity
3716                    // component is no longer known. Ignore it and do NOT remove it.
3717                    continue;
3718                }
3719                for (int j=0; j<N; j++) {
3720                    final ResolveInfo ri = query.get(j);
3721                    if (!ri.activityInfo.applicationInfo.packageName
3722                            .equals(ai.applicationInfo.packageName)) {
3723                        continue;
3724                    }
3725                    if (!ri.activityInfo.name.equals(ai.name)) {
3726                        continue;
3727                    }
3728                    //  Found a persistent preference that can handle the intent.
3729                    if (DEBUG_PREFERRED || debug) {
3730                        Slog.v(TAG, "Returning persistent preferred activity: " +
3731                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3732                    }
3733                    return ri;
3734                }
3735            }
3736        }
3737        return null;
3738    }
3739
3740    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3741            List<ResolveInfo> query, int priority, boolean always,
3742            boolean removeMatches, boolean debug, int userId) {
3743        if (!sUserManager.exists(userId)) return null;
3744        // writer
3745        synchronized (mPackages) {
3746            if (intent.getSelector() != null) {
3747                intent = intent.getSelector();
3748            }
3749            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3750
3751            // Try to find a matching persistent preferred activity.
3752            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3753                    debug, userId);
3754
3755            // If a persistent preferred activity matched, use it.
3756            if (pri != null) {
3757                return pri;
3758            }
3759
3760            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3761            // Get the list of preferred activities that handle the intent
3762            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3763            List<PreferredActivity> prefs = pir != null
3764                    ? pir.queryIntent(intent, resolvedType,
3765                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3766                    : null;
3767            if (prefs != null && prefs.size() > 0) {
3768                boolean changed = false;
3769                try {
3770                    // First figure out how good the original match set is.
3771                    // We will only allow preferred activities that came
3772                    // from the same match quality.
3773                    int match = 0;
3774
3775                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3776
3777                    final int N = query.size();
3778                    for (int j=0; j<N; j++) {
3779                        final ResolveInfo ri = query.get(j);
3780                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3781                                + ": 0x" + Integer.toHexString(match));
3782                        if (ri.match > match) {
3783                            match = ri.match;
3784                        }
3785                    }
3786
3787                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3788                            + Integer.toHexString(match));
3789
3790                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3791                    final int M = prefs.size();
3792                    for (int i=0; i<M; i++) {
3793                        final PreferredActivity pa = prefs.get(i);
3794                        if (DEBUG_PREFERRED || debug) {
3795                            Slog.v(TAG, "Checking PreferredActivity ds="
3796                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3797                                    + "\n  component=" + pa.mPref.mComponent);
3798                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3799                        }
3800                        if (pa.mPref.mMatch != match) {
3801                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3802                                    + Integer.toHexString(pa.mPref.mMatch));
3803                            continue;
3804                        }
3805                        // If it's not an "always" type preferred activity and that's what we're
3806                        // looking for, skip it.
3807                        if (always && !pa.mPref.mAlways) {
3808                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3809                            continue;
3810                        }
3811                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3812                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3813                        if (DEBUG_PREFERRED || debug) {
3814                            Slog.v(TAG, "Found preferred activity:");
3815                            if (ai != null) {
3816                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3817                            } else {
3818                                Slog.v(TAG, "  null");
3819                            }
3820                        }
3821                        if (ai == null) {
3822                            // This previously registered preferred activity
3823                            // component is no longer known.  Most likely an update
3824                            // to the app was installed and in the new version this
3825                            // component no longer exists.  Clean it up by removing
3826                            // it from the preferred activities list, and skip it.
3827                            Slog.w(TAG, "Removing dangling preferred activity: "
3828                                    + pa.mPref.mComponent);
3829                            pir.removeFilter(pa);
3830                            changed = true;
3831                            continue;
3832                        }
3833                        for (int j=0; j<N; j++) {
3834                            final ResolveInfo ri = query.get(j);
3835                            if (!ri.activityInfo.applicationInfo.packageName
3836                                    .equals(ai.applicationInfo.packageName)) {
3837                                continue;
3838                            }
3839                            if (!ri.activityInfo.name.equals(ai.name)) {
3840                                continue;
3841                            }
3842
3843                            if (removeMatches) {
3844                                pir.removeFilter(pa);
3845                                changed = true;
3846                                if (DEBUG_PREFERRED) {
3847                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3848                                }
3849                                break;
3850                            }
3851
3852                            // Okay we found a previously set preferred or last chosen app.
3853                            // If the result set is different from when this
3854                            // was created, we need to clear it and re-ask the
3855                            // user their preference, if we're looking for an "always" type entry.
3856                            if (always && !pa.mPref.sameSet(query)) {
3857                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3858                                        + intent + " type " + resolvedType);
3859                                if (DEBUG_PREFERRED) {
3860                                    Slog.v(TAG, "Removing preferred activity since set changed "
3861                                            + pa.mPref.mComponent);
3862                                }
3863                                pir.removeFilter(pa);
3864                                // Re-add the filter as a "last chosen" entry (!always)
3865                                PreferredActivity lastChosen = new PreferredActivity(
3866                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3867                                pir.addFilter(lastChosen);
3868                                changed = true;
3869                                return null;
3870                            }
3871
3872                            // Yay! Either the set matched or we're looking for the last chosen
3873                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3874                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3875                            return ri;
3876                        }
3877                    }
3878                } finally {
3879                    if (changed) {
3880                        if (DEBUG_PREFERRED) {
3881                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3882                        }
3883                        scheduleWritePackageRestrictionsLocked(userId);
3884                    }
3885                }
3886            }
3887        }
3888        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3889        return null;
3890    }
3891
3892    /*
3893     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3894     */
3895    @Override
3896    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3897            int targetUserId) {
3898        mContext.enforceCallingOrSelfPermission(
3899                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3900        List<CrossProfileIntentFilter> matches =
3901                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3902        if (matches != null) {
3903            int size = matches.size();
3904            for (int i = 0; i < size; i++) {
3905                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3906            }
3907        }
3908        return false;
3909    }
3910
3911    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3912            String resolvedType, int userId) {
3913        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3914        if (resolver != null) {
3915            return resolver.queryIntent(intent, resolvedType, false, userId);
3916        }
3917        return null;
3918    }
3919
3920    @Override
3921    public List<ResolveInfo> queryIntentActivities(Intent intent,
3922            String resolvedType, int flags, int userId) {
3923        if (!sUserManager.exists(userId)) return Collections.emptyList();
3924        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3925        ComponentName comp = intent.getComponent();
3926        if (comp == null) {
3927            if (intent.getSelector() != null) {
3928                intent = intent.getSelector();
3929                comp = intent.getComponent();
3930            }
3931        }
3932
3933        if (comp != null) {
3934            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3935            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3936            if (ai != null) {
3937                final ResolveInfo ri = new ResolveInfo();
3938                ri.activityInfo = ai;
3939                list.add(ri);
3940            }
3941            return list;
3942        }
3943
3944        // reader
3945        synchronized (mPackages) {
3946            final String pkgName = intent.getPackage();
3947            if (pkgName == null) {
3948                List<CrossProfileIntentFilter> matchingFilters =
3949                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3950                // Check for results that need to skip the current profile.
3951                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3952                        resolvedType, flags, userId);
3953                if (resolveInfo != null) {
3954                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3955                    result.add(resolveInfo);
3956                    return filterIfNotPrimaryUser(result, userId);
3957                }
3958                // Check for cross profile results.
3959                resolveInfo = queryCrossProfileIntents(
3960                        matchingFilters, intent, resolvedType, flags, userId);
3961
3962                // Check for results in the current profile.
3963                List<ResolveInfo> result = mActivities.queryIntent(
3964                        intent, resolvedType, flags, userId);
3965                if (resolveInfo != null) {
3966                    result.add(resolveInfo);
3967                    Collections.sort(result, mResolvePrioritySorter);
3968                }
3969                result = filterIfNotPrimaryUser(result, userId);
3970                if (result.size() > 1 && hasWebURI(intent)) {
3971                    return filterCandidatesWithDomainPreferedActivitiesLPr(result);
3972                }
3973                return result;
3974            }
3975            final PackageParser.Package pkg = mPackages.get(pkgName);
3976            if (pkg != null) {
3977                return filterIfNotPrimaryUser(
3978                        mActivities.queryIntentForPackage(
3979                                intent, resolvedType, flags, pkg.activities, userId),
3980                        userId);
3981            }
3982            return new ArrayList<ResolveInfo>();
3983        }
3984    }
3985
3986    /**
3987     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
3988     *
3989     * @return filtered list
3990     */
3991    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
3992        if (userId == UserHandle.USER_OWNER) {
3993            return resolveInfos;
3994        }
3995        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
3996            ResolveInfo info = resolveInfos.get(i);
3997            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
3998                resolveInfos.remove(i);
3999            }
4000        }
4001        return resolveInfos;
4002    }
4003
4004    private static boolean hasWebURI(Intent intent) {
4005        if (intent.getData() == null) {
4006            return false;
4007        }
4008        final String scheme = intent.getScheme();
4009        if (TextUtils.isEmpty(scheme)) {
4010            return false;
4011        }
4012        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4013    }
4014
4015    private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr(
4016            List<ResolveInfo> candidates) {
4017        if (DEBUG_PREFERRED) {
4018            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4019                    candidates.size());
4020        }
4021
4022        final int userId = UserHandle.getCallingUserId();
4023        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4024        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4025        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4026        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4027
4028        synchronized (mPackages) {
4029            final int count = candidates.size();
4030            // First, try to use the domain prefered App
4031            for (int n=0; n<count; n++) {
4032                ResolveInfo info = candidates.get(n);
4033                String packageName = info.activityInfo.packageName;
4034                PackageSetting ps = mSettings.mPackages.get(packageName);
4035                if (ps != null) {
4036                    // Try to get the status from User settings first
4037                    int status = getDomainVerificationStatusLPr(ps, userId);
4038                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4039                        result.add(info);
4040                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4041                        neverList.add(info);
4042                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4043                        undefinedList.add(info);
4044                    }
4045                    // Add to the special match all list (Browser use case)
4046                    if (info.handleAllWebDataURI) {
4047                        matchAllList.add(info);
4048                    }
4049                }
4050            }
4051            // If there is nothing selected, add all candidates and remove the ones that the User
4052            // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and
4053            // also remove any Browser Apps ones.
4054            // If there is still none after this pass, add all undefined one and Browser Apps and
4055            // let the User decide with the Disambiguation dialog if there are several ones.
4056            if (result.size() == 0) {
4057                result.addAll(candidates);
4058            }
4059            result.removeAll(neverList);
4060            result.removeAll(matchAllList);
4061            if (result.size() == 0) {
4062                result.addAll(undefinedList);
4063                result.addAll(matchAllList);
4064            }
4065        }
4066        if (DEBUG_PREFERRED) {
4067            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4068                    result.size());
4069        }
4070        return result;
4071    }
4072
4073    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4074        int status = ps.getDomainVerificationStatusForUser(userId);
4075        // if none available, get the master status
4076        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4077            if (ps.getIntentFilterVerificationInfo() != null) {
4078                status = ps.getIntentFilterVerificationInfo().getStatus();
4079            }
4080        }
4081        return status;
4082    }
4083
4084    private ResolveInfo querySkipCurrentProfileIntents(
4085            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4086            int flags, int sourceUserId) {
4087        if (matchingFilters != null) {
4088            int size = matchingFilters.size();
4089            for (int i = 0; i < size; i ++) {
4090                CrossProfileIntentFilter filter = matchingFilters.get(i);
4091                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4092                    // Checking if there are activities in the target user that can handle the
4093                    // intent.
4094                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4095                            flags, sourceUserId);
4096                    if (resolveInfo != null) {
4097                        return resolveInfo;
4098                    }
4099                }
4100            }
4101        }
4102        return null;
4103    }
4104
4105    // Return matching ResolveInfo if any for skip current profile intent filters.
4106    private ResolveInfo queryCrossProfileIntents(
4107            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4108            int flags, int sourceUserId) {
4109        if (matchingFilters != null) {
4110            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4111            // match the same intent. For performance reasons, it is better not to
4112            // run queryIntent twice for the same userId
4113            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4114            int size = matchingFilters.size();
4115            for (int i = 0; i < size; i++) {
4116                CrossProfileIntentFilter filter = matchingFilters.get(i);
4117                int targetUserId = filter.getTargetUserId();
4118                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4119                        && !alreadyTriedUserIds.get(targetUserId)) {
4120                    // Checking if there are activities in the target user that can handle the
4121                    // intent.
4122                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4123                            flags, sourceUserId);
4124                    if (resolveInfo != null) return resolveInfo;
4125                    alreadyTriedUserIds.put(targetUserId, true);
4126                }
4127            }
4128        }
4129        return null;
4130    }
4131
4132    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4133            String resolvedType, int flags, int sourceUserId) {
4134        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4135                resolvedType, flags, filter.getTargetUserId());
4136        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4137            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4138        }
4139        return null;
4140    }
4141
4142    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4143            int sourceUserId, int targetUserId) {
4144        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4145        String className;
4146        if (targetUserId == UserHandle.USER_OWNER) {
4147            className = FORWARD_INTENT_TO_USER_OWNER;
4148        } else {
4149            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4150        }
4151        ComponentName forwardingActivityComponentName = new ComponentName(
4152                mAndroidApplication.packageName, className);
4153        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4154                sourceUserId);
4155        if (targetUserId == UserHandle.USER_OWNER) {
4156            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4157            forwardingResolveInfo.noResourceId = true;
4158        }
4159        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4160        forwardingResolveInfo.priority = 0;
4161        forwardingResolveInfo.preferredOrder = 0;
4162        forwardingResolveInfo.match = 0;
4163        forwardingResolveInfo.isDefault = true;
4164        forwardingResolveInfo.filter = filter;
4165        forwardingResolveInfo.targetUserId = targetUserId;
4166        return forwardingResolveInfo;
4167    }
4168
4169    @Override
4170    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4171            Intent[] specifics, String[] specificTypes, Intent intent,
4172            String resolvedType, int flags, int userId) {
4173        if (!sUserManager.exists(userId)) return Collections.emptyList();
4174        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4175                false, "query intent activity options");
4176        final String resultsAction = intent.getAction();
4177
4178        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4179                | PackageManager.GET_RESOLVED_FILTER, userId);
4180
4181        if (DEBUG_INTENT_MATCHING) {
4182            Log.v(TAG, "Query " + intent + ": " + results);
4183        }
4184
4185        int specificsPos = 0;
4186        int N;
4187
4188        // todo: note that the algorithm used here is O(N^2).  This
4189        // isn't a problem in our current environment, but if we start running
4190        // into situations where we have more than 5 or 10 matches then this
4191        // should probably be changed to something smarter...
4192
4193        // First we go through and resolve each of the specific items
4194        // that were supplied, taking care of removing any corresponding
4195        // duplicate items in the generic resolve list.
4196        if (specifics != null) {
4197            for (int i=0; i<specifics.length; i++) {
4198                final Intent sintent = specifics[i];
4199                if (sintent == null) {
4200                    continue;
4201                }
4202
4203                if (DEBUG_INTENT_MATCHING) {
4204                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4205                }
4206
4207                String action = sintent.getAction();
4208                if (resultsAction != null && resultsAction.equals(action)) {
4209                    // If this action was explicitly requested, then don't
4210                    // remove things that have it.
4211                    action = null;
4212                }
4213
4214                ResolveInfo ri = null;
4215                ActivityInfo ai = null;
4216
4217                ComponentName comp = sintent.getComponent();
4218                if (comp == null) {
4219                    ri = resolveIntent(
4220                        sintent,
4221                        specificTypes != null ? specificTypes[i] : null,
4222                            flags, userId);
4223                    if (ri == null) {
4224                        continue;
4225                    }
4226                    if (ri == mResolveInfo) {
4227                        // ACK!  Must do something better with this.
4228                    }
4229                    ai = ri.activityInfo;
4230                    comp = new ComponentName(ai.applicationInfo.packageName,
4231                            ai.name);
4232                } else {
4233                    ai = getActivityInfo(comp, flags, userId);
4234                    if (ai == null) {
4235                        continue;
4236                    }
4237                }
4238
4239                // Look for any generic query activities that are duplicates
4240                // of this specific one, and remove them from the results.
4241                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4242                N = results.size();
4243                int j;
4244                for (j=specificsPos; j<N; j++) {
4245                    ResolveInfo sri = results.get(j);
4246                    if ((sri.activityInfo.name.equals(comp.getClassName())
4247                            && sri.activityInfo.applicationInfo.packageName.equals(
4248                                    comp.getPackageName()))
4249                        || (action != null && sri.filter.matchAction(action))) {
4250                        results.remove(j);
4251                        if (DEBUG_INTENT_MATCHING) Log.v(
4252                            TAG, "Removing duplicate item from " + j
4253                            + " due to specific " + specificsPos);
4254                        if (ri == null) {
4255                            ri = sri;
4256                        }
4257                        j--;
4258                        N--;
4259                    }
4260                }
4261
4262                // Add this specific item to its proper place.
4263                if (ri == null) {
4264                    ri = new ResolveInfo();
4265                    ri.activityInfo = ai;
4266                }
4267                results.add(specificsPos, ri);
4268                ri.specificIndex = i;
4269                specificsPos++;
4270            }
4271        }
4272
4273        // Now we go through the remaining generic results and remove any
4274        // duplicate actions that are found here.
4275        N = results.size();
4276        for (int i=specificsPos; i<N-1; i++) {
4277            final ResolveInfo rii = results.get(i);
4278            if (rii.filter == null) {
4279                continue;
4280            }
4281
4282            // Iterate over all of the actions of this result's intent
4283            // filter...  typically this should be just one.
4284            final Iterator<String> it = rii.filter.actionsIterator();
4285            if (it == null) {
4286                continue;
4287            }
4288            while (it.hasNext()) {
4289                final String action = it.next();
4290                if (resultsAction != null && resultsAction.equals(action)) {
4291                    // If this action was explicitly requested, then don't
4292                    // remove things that have it.
4293                    continue;
4294                }
4295                for (int j=i+1; j<N; j++) {
4296                    final ResolveInfo rij = results.get(j);
4297                    if (rij.filter != null && rij.filter.hasAction(action)) {
4298                        results.remove(j);
4299                        if (DEBUG_INTENT_MATCHING) Log.v(
4300                            TAG, "Removing duplicate item from " + j
4301                            + " due to action " + action + " at " + i);
4302                        j--;
4303                        N--;
4304                    }
4305                }
4306            }
4307
4308            // If the caller didn't request filter information, drop it now
4309            // so we don't have to marshall/unmarshall it.
4310            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4311                rii.filter = null;
4312            }
4313        }
4314
4315        // Filter out the caller activity if so requested.
4316        if (caller != null) {
4317            N = results.size();
4318            for (int i=0; i<N; i++) {
4319                ActivityInfo ainfo = results.get(i).activityInfo;
4320                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4321                        && caller.getClassName().equals(ainfo.name)) {
4322                    results.remove(i);
4323                    break;
4324                }
4325            }
4326        }
4327
4328        // If the caller didn't request filter information,
4329        // drop them now so we don't have to
4330        // marshall/unmarshall it.
4331        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4332            N = results.size();
4333            for (int i=0; i<N; i++) {
4334                results.get(i).filter = null;
4335            }
4336        }
4337
4338        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4339        return results;
4340    }
4341
4342    @Override
4343    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4344            int userId) {
4345        if (!sUserManager.exists(userId)) return Collections.emptyList();
4346        ComponentName comp = intent.getComponent();
4347        if (comp == null) {
4348            if (intent.getSelector() != null) {
4349                intent = intent.getSelector();
4350                comp = intent.getComponent();
4351            }
4352        }
4353        if (comp != null) {
4354            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4355            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4356            if (ai != null) {
4357                ResolveInfo ri = new ResolveInfo();
4358                ri.activityInfo = ai;
4359                list.add(ri);
4360            }
4361            return list;
4362        }
4363
4364        // reader
4365        synchronized (mPackages) {
4366            String pkgName = intent.getPackage();
4367            if (pkgName == null) {
4368                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4369            }
4370            final PackageParser.Package pkg = mPackages.get(pkgName);
4371            if (pkg != null) {
4372                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4373                        userId);
4374            }
4375            return null;
4376        }
4377    }
4378
4379    @Override
4380    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4381        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4382        if (!sUserManager.exists(userId)) return null;
4383        if (query != null) {
4384            if (query.size() >= 1) {
4385                // If there is more than one service with the same priority,
4386                // just arbitrarily pick the first one.
4387                return query.get(0);
4388            }
4389        }
4390        return null;
4391    }
4392
4393    @Override
4394    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4395            int userId) {
4396        if (!sUserManager.exists(userId)) return Collections.emptyList();
4397        ComponentName comp = intent.getComponent();
4398        if (comp == null) {
4399            if (intent.getSelector() != null) {
4400                intent = intent.getSelector();
4401                comp = intent.getComponent();
4402            }
4403        }
4404        if (comp != null) {
4405            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4406            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4407            if (si != null) {
4408                final ResolveInfo ri = new ResolveInfo();
4409                ri.serviceInfo = si;
4410                list.add(ri);
4411            }
4412            return list;
4413        }
4414
4415        // reader
4416        synchronized (mPackages) {
4417            String pkgName = intent.getPackage();
4418            if (pkgName == null) {
4419                return mServices.queryIntent(intent, resolvedType, flags, userId);
4420            }
4421            final PackageParser.Package pkg = mPackages.get(pkgName);
4422            if (pkg != null) {
4423                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4424                        userId);
4425            }
4426            return null;
4427        }
4428    }
4429
4430    @Override
4431    public List<ResolveInfo> queryIntentContentProviders(
4432            Intent intent, String resolvedType, int flags, int userId) {
4433        if (!sUserManager.exists(userId)) return Collections.emptyList();
4434        ComponentName comp = intent.getComponent();
4435        if (comp == null) {
4436            if (intent.getSelector() != null) {
4437                intent = intent.getSelector();
4438                comp = intent.getComponent();
4439            }
4440        }
4441        if (comp != null) {
4442            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4443            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4444            if (pi != null) {
4445                final ResolveInfo ri = new ResolveInfo();
4446                ri.providerInfo = pi;
4447                list.add(ri);
4448            }
4449            return list;
4450        }
4451
4452        // reader
4453        synchronized (mPackages) {
4454            String pkgName = intent.getPackage();
4455            if (pkgName == null) {
4456                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4457            }
4458            final PackageParser.Package pkg = mPackages.get(pkgName);
4459            if (pkg != null) {
4460                return mProviders.queryIntentForPackage(
4461                        intent, resolvedType, flags, pkg.providers, userId);
4462            }
4463            return null;
4464        }
4465    }
4466
4467    @Override
4468    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4469        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4470
4471        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4472
4473        // writer
4474        synchronized (mPackages) {
4475            ArrayList<PackageInfo> list;
4476            if (listUninstalled) {
4477                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4478                for (PackageSetting ps : mSettings.mPackages.values()) {
4479                    PackageInfo pi;
4480                    if (ps.pkg != null) {
4481                        pi = generatePackageInfo(ps.pkg, flags, userId);
4482                    } else {
4483                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4484                    }
4485                    if (pi != null) {
4486                        list.add(pi);
4487                    }
4488                }
4489            } else {
4490                list = new ArrayList<PackageInfo>(mPackages.size());
4491                for (PackageParser.Package p : mPackages.values()) {
4492                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4493                    if (pi != null) {
4494                        list.add(pi);
4495                    }
4496                }
4497            }
4498
4499            return new ParceledListSlice<PackageInfo>(list);
4500        }
4501    }
4502
4503    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4504            String[] permissions, boolean[] tmp, int flags, int userId) {
4505        int numMatch = 0;
4506        final PermissionsState permissionsState = ps.getPermissionsState();
4507        for (int i=0; i<permissions.length; i++) {
4508            final String permission = permissions[i];
4509            if (permissionsState.hasPermission(permission, userId)) {
4510                tmp[i] = true;
4511                numMatch++;
4512            } else {
4513                tmp[i] = false;
4514            }
4515        }
4516        if (numMatch == 0) {
4517            return;
4518        }
4519        PackageInfo pi;
4520        if (ps.pkg != null) {
4521            pi = generatePackageInfo(ps.pkg, flags, userId);
4522        } else {
4523            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4524        }
4525        // The above might return null in cases of uninstalled apps or install-state
4526        // skew across users/profiles.
4527        if (pi != null) {
4528            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4529                if (numMatch == permissions.length) {
4530                    pi.requestedPermissions = permissions;
4531                } else {
4532                    pi.requestedPermissions = new String[numMatch];
4533                    numMatch = 0;
4534                    for (int i=0; i<permissions.length; i++) {
4535                        if (tmp[i]) {
4536                            pi.requestedPermissions[numMatch] = permissions[i];
4537                            numMatch++;
4538                        }
4539                    }
4540                }
4541            }
4542            list.add(pi);
4543        }
4544    }
4545
4546    @Override
4547    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4548            String[] permissions, int flags, int userId) {
4549        if (!sUserManager.exists(userId)) return null;
4550        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4551
4552        // writer
4553        synchronized (mPackages) {
4554            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4555            boolean[] tmpBools = new boolean[permissions.length];
4556            if (listUninstalled) {
4557                for (PackageSetting ps : mSettings.mPackages.values()) {
4558                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4559                }
4560            } else {
4561                for (PackageParser.Package pkg : mPackages.values()) {
4562                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4563                    if (ps != null) {
4564                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4565                                userId);
4566                    }
4567                }
4568            }
4569
4570            return new ParceledListSlice<PackageInfo>(list);
4571        }
4572    }
4573
4574    @Override
4575    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4576        if (!sUserManager.exists(userId)) return null;
4577        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4578
4579        // writer
4580        synchronized (mPackages) {
4581            ArrayList<ApplicationInfo> list;
4582            if (listUninstalled) {
4583                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4584                for (PackageSetting ps : mSettings.mPackages.values()) {
4585                    ApplicationInfo ai;
4586                    if (ps.pkg != null) {
4587                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4588                                ps.readUserState(userId), userId);
4589                    } else {
4590                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4591                    }
4592                    if (ai != null) {
4593                        list.add(ai);
4594                    }
4595                }
4596            } else {
4597                list = new ArrayList<ApplicationInfo>(mPackages.size());
4598                for (PackageParser.Package p : mPackages.values()) {
4599                    if (p.mExtras != null) {
4600                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4601                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4602                        if (ai != null) {
4603                            list.add(ai);
4604                        }
4605                    }
4606                }
4607            }
4608
4609            return new ParceledListSlice<ApplicationInfo>(list);
4610        }
4611    }
4612
4613    public List<ApplicationInfo> getPersistentApplications(int flags) {
4614        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4615
4616        // reader
4617        synchronized (mPackages) {
4618            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4619            final int userId = UserHandle.getCallingUserId();
4620            while (i.hasNext()) {
4621                final PackageParser.Package p = i.next();
4622                if (p.applicationInfo != null
4623                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4624                        && (!mSafeMode || isSystemApp(p))) {
4625                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4626                    if (ps != null) {
4627                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4628                                ps.readUserState(userId), userId);
4629                        if (ai != null) {
4630                            finalList.add(ai);
4631                        }
4632                    }
4633                }
4634            }
4635        }
4636
4637        return finalList;
4638    }
4639
4640    @Override
4641    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4642        if (!sUserManager.exists(userId)) return null;
4643        // reader
4644        synchronized (mPackages) {
4645            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4646            PackageSetting ps = provider != null
4647                    ? mSettings.mPackages.get(provider.owner.packageName)
4648                    : null;
4649            return ps != null
4650                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4651                    && (!mSafeMode || (provider.info.applicationInfo.flags
4652                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4653                    ? PackageParser.generateProviderInfo(provider, flags,
4654                            ps.readUserState(userId), userId)
4655                    : null;
4656        }
4657    }
4658
4659    /**
4660     * @deprecated
4661     */
4662    @Deprecated
4663    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4664        // reader
4665        synchronized (mPackages) {
4666            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4667                    .entrySet().iterator();
4668            final int userId = UserHandle.getCallingUserId();
4669            while (i.hasNext()) {
4670                Map.Entry<String, PackageParser.Provider> entry = i.next();
4671                PackageParser.Provider p = entry.getValue();
4672                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4673
4674                if (ps != null && p.syncable
4675                        && (!mSafeMode || (p.info.applicationInfo.flags
4676                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4677                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4678                            ps.readUserState(userId), userId);
4679                    if (info != null) {
4680                        outNames.add(entry.getKey());
4681                        outInfo.add(info);
4682                    }
4683                }
4684            }
4685        }
4686    }
4687
4688    @Override
4689    public List<ProviderInfo> queryContentProviders(String processName,
4690            int uid, int flags) {
4691        ArrayList<ProviderInfo> finalList = null;
4692        // reader
4693        synchronized (mPackages) {
4694            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4695            final int userId = processName != null ?
4696                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4697            while (i.hasNext()) {
4698                final PackageParser.Provider p = i.next();
4699                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4700                if (ps != null && p.info.authority != null
4701                        && (processName == null
4702                                || (p.info.processName.equals(processName)
4703                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4704                        && mSettings.isEnabledLPr(p.info, flags, userId)
4705                        && (!mSafeMode
4706                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4707                    if (finalList == null) {
4708                        finalList = new ArrayList<ProviderInfo>(3);
4709                    }
4710                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4711                            ps.readUserState(userId), userId);
4712                    if (info != null) {
4713                        finalList.add(info);
4714                    }
4715                }
4716            }
4717        }
4718
4719        if (finalList != null) {
4720            Collections.sort(finalList, mProviderInitOrderSorter);
4721        }
4722
4723        return finalList;
4724    }
4725
4726    @Override
4727    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4728            int flags) {
4729        // reader
4730        synchronized (mPackages) {
4731            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4732            return PackageParser.generateInstrumentationInfo(i, flags);
4733        }
4734    }
4735
4736    @Override
4737    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4738            int flags) {
4739        ArrayList<InstrumentationInfo> finalList =
4740            new ArrayList<InstrumentationInfo>();
4741
4742        // reader
4743        synchronized (mPackages) {
4744            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4745            while (i.hasNext()) {
4746                final PackageParser.Instrumentation p = i.next();
4747                if (targetPackage == null
4748                        || targetPackage.equals(p.info.targetPackage)) {
4749                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4750                            flags);
4751                    if (ii != null) {
4752                        finalList.add(ii);
4753                    }
4754                }
4755            }
4756        }
4757
4758        return finalList;
4759    }
4760
4761    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4762        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4763        if (overlays == null) {
4764            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4765            return;
4766        }
4767        for (PackageParser.Package opkg : overlays.values()) {
4768            // Not much to do if idmap fails: we already logged the error
4769            // and we certainly don't want to abort installation of pkg simply
4770            // because an overlay didn't fit properly. For these reasons,
4771            // ignore the return value of createIdmapForPackagePairLI.
4772            createIdmapForPackagePairLI(pkg, opkg);
4773        }
4774    }
4775
4776    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4777            PackageParser.Package opkg) {
4778        if (!opkg.mTrustedOverlay) {
4779            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4780                    opkg.baseCodePath + ": overlay not trusted");
4781            return false;
4782        }
4783        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4784        if (overlaySet == null) {
4785            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4786                    opkg.baseCodePath + " but target package has no known overlays");
4787            return false;
4788        }
4789        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4790        // TODO: generate idmap for split APKs
4791        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4792            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4793                    + opkg.baseCodePath);
4794            return false;
4795        }
4796        PackageParser.Package[] overlayArray =
4797            overlaySet.values().toArray(new PackageParser.Package[0]);
4798        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4799            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4800                return p1.mOverlayPriority - p2.mOverlayPriority;
4801            }
4802        };
4803        Arrays.sort(overlayArray, cmp);
4804
4805        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4806        int i = 0;
4807        for (PackageParser.Package p : overlayArray) {
4808            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4809        }
4810        return true;
4811    }
4812
4813    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4814        final File[] files = dir.listFiles();
4815        if (ArrayUtils.isEmpty(files)) {
4816            Log.d(TAG, "No files in app dir " + dir);
4817            return;
4818        }
4819
4820        if (DEBUG_PACKAGE_SCANNING) {
4821            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4822                    + " flags=0x" + Integer.toHexString(parseFlags));
4823        }
4824
4825        for (File file : files) {
4826            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4827                    && !PackageInstallerService.isStageName(file.getName());
4828            if (!isPackage) {
4829                // Ignore entries which are not packages
4830                continue;
4831            }
4832            try {
4833                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4834                        scanFlags, currentTime, null);
4835            } catch (PackageManagerException e) {
4836                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4837
4838                // Delete invalid userdata apps
4839                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4840                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4841                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4842                    if (file.isDirectory()) {
4843                        mInstaller.rmPackageDir(file.getAbsolutePath());
4844                    } else {
4845                        file.delete();
4846                    }
4847                }
4848            }
4849        }
4850    }
4851
4852    private static File getSettingsProblemFile() {
4853        File dataDir = Environment.getDataDirectory();
4854        File systemDir = new File(dataDir, "system");
4855        File fname = new File(systemDir, "uiderrors.txt");
4856        return fname;
4857    }
4858
4859    static void reportSettingsProblem(int priority, String msg) {
4860        logCriticalInfo(priority, msg);
4861    }
4862
4863    static void logCriticalInfo(int priority, String msg) {
4864        Slog.println(priority, TAG, msg);
4865        EventLogTags.writePmCriticalInfo(msg);
4866        try {
4867            File fname = getSettingsProblemFile();
4868            FileOutputStream out = new FileOutputStream(fname, true);
4869            PrintWriter pw = new FastPrintWriter(out);
4870            SimpleDateFormat formatter = new SimpleDateFormat();
4871            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4872            pw.println(dateString + ": " + msg);
4873            pw.close();
4874            FileUtils.setPermissions(
4875                    fname.toString(),
4876                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4877                    -1, -1);
4878        } catch (java.io.IOException e) {
4879        }
4880    }
4881
4882    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4883            PackageParser.Package pkg, File srcFile, int parseFlags)
4884            throws PackageManagerException {
4885        if (ps != null
4886                && ps.codePath.equals(srcFile)
4887                && ps.timeStamp == srcFile.lastModified()
4888                && !isCompatSignatureUpdateNeeded(pkg)
4889                && !isRecoverSignatureUpdateNeeded(pkg)) {
4890            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4891            if (ps.signatures.mSignatures != null
4892                    && ps.signatures.mSignatures.length != 0
4893                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4894                // Optimization: reuse the existing cached certificates
4895                // if the package appears to be unchanged.
4896                pkg.mSignatures = ps.signatures.mSignatures;
4897                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4898                synchronized (mPackages) {
4899                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4900                }
4901                return;
4902            }
4903
4904            Slog.w(TAG, "PackageSetting for " + ps.name
4905                    + " is missing signatures.  Collecting certs again to recover them.");
4906        } else {
4907            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4908        }
4909
4910        try {
4911            pp.collectCertificates(pkg, parseFlags);
4912            pp.collectManifestDigest(pkg);
4913        } catch (PackageParserException e) {
4914            throw PackageManagerException.from(e);
4915        }
4916    }
4917
4918    /*
4919     *  Scan a package and return the newly parsed package.
4920     *  Returns null in case of errors and the error code is stored in mLastScanError
4921     */
4922    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4923            long currentTime, UserHandle user) throws PackageManagerException {
4924        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4925        parseFlags |= mDefParseFlags;
4926        PackageParser pp = new PackageParser();
4927        pp.setSeparateProcesses(mSeparateProcesses);
4928        pp.setOnlyCoreApps(mOnlyCore);
4929        pp.setDisplayMetrics(mMetrics);
4930
4931        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4932            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4933        }
4934
4935        final PackageParser.Package pkg;
4936        try {
4937            pkg = pp.parsePackage(scanFile, parseFlags);
4938        } catch (PackageParserException e) {
4939            throw PackageManagerException.from(e);
4940        }
4941
4942        PackageSetting ps = null;
4943        PackageSetting updatedPkg;
4944        // reader
4945        synchronized (mPackages) {
4946            // Look to see if we already know about this package.
4947            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4948            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4949                // This package has been renamed to its original name.  Let's
4950                // use that.
4951                ps = mSettings.peekPackageLPr(oldName);
4952            }
4953            // If there was no original package, see one for the real package name.
4954            if (ps == null) {
4955                ps = mSettings.peekPackageLPr(pkg.packageName);
4956            }
4957            // Check to see if this package could be hiding/updating a system
4958            // package.  Must look for it either under the original or real
4959            // package name depending on our state.
4960            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4961            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4962        }
4963        boolean updatedPkgBetter = false;
4964        // First check if this is a system package that may involve an update
4965        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4966            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
4967            // it needs to drop FLAG_PRIVILEGED.
4968            if (locationIsPrivileged(scanFile)) {
4969                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4970            } else {
4971                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4972            }
4973
4974            if (ps != null && !ps.codePath.equals(scanFile)) {
4975                // The path has changed from what was last scanned...  check the
4976                // version of the new path against what we have stored to determine
4977                // what to do.
4978                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4979                if (pkg.mVersionCode <= ps.versionCode) {
4980                    // The system package has been updated and the code path does not match
4981                    // Ignore entry. Skip it.
4982                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
4983                            + " ignored: updated version " + ps.versionCode
4984                            + " better than this " + pkg.mVersionCode);
4985                    if (!updatedPkg.codePath.equals(scanFile)) {
4986                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4987                                + ps.name + " changing from " + updatedPkg.codePathString
4988                                + " to " + scanFile);
4989                        updatedPkg.codePath = scanFile;
4990                        updatedPkg.codePathString = scanFile.toString();
4991                        updatedPkg.resourcePath = scanFile;
4992                        updatedPkg.resourcePathString = scanFile.toString();
4993                    }
4994                    updatedPkg.pkg = pkg;
4995                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4996                } else {
4997                    // The current app on the system partition is better than
4998                    // what we have updated to on the data partition; switch
4999                    // back to the system partition version.
5000                    // At this point, its safely assumed that package installation for
5001                    // apps in system partition will go through. If not there won't be a working
5002                    // version of the app
5003                    // writer
5004                    synchronized (mPackages) {
5005                        // Just remove the loaded entries from package lists.
5006                        mPackages.remove(ps.name);
5007                    }
5008
5009                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5010                            + " reverting from " + ps.codePathString
5011                            + ": new version " + pkg.mVersionCode
5012                            + " better than installed " + ps.versionCode);
5013
5014                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5015                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
5016                            getAppDexInstructionSets(ps));
5017                    synchronized (mInstallLock) {
5018                        args.cleanUpResourcesLI();
5019                    }
5020                    synchronized (mPackages) {
5021                        mSettings.enableSystemPackageLPw(ps.name);
5022                    }
5023                    updatedPkgBetter = true;
5024                }
5025            }
5026        }
5027
5028        if (updatedPkg != null) {
5029            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5030            // initially
5031            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5032
5033            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5034            // flag set initially
5035            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5036                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5037            }
5038        }
5039
5040        // Verify certificates against what was last scanned
5041        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5042
5043        /*
5044         * A new system app appeared, but we already had a non-system one of the
5045         * same name installed earlier.
5046         */
5047        boolean shouldHideSystemApp = false;
5048        if (updatedPkg == null && ps != null
5049                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5050            /*
5051             * Check to make sure the signatures match first. If they don't,
5052             * wipe the installed application and its data.
5053             */
5054            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5055                    != PackageManager.SIGNATURE_MATCH) {
5056                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5057                        + " signatures don't match existing userdata copy; removing");
5058                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5059                ps = null;
5060            } else {
5061                /*
5062                 * If the newly-added system app is an older version than the
5063                 * already installed version, hide it. It will be scanned later
5064                 * and re-added like an update.
5065                 */
5066                if (pkg.mVersionCode <= ps.versionCode) {
5067                    shouldHideSystemApp = true;
5068                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5069                            + " but new version " + pkg.mVersionCode + " better than installed "
5070                            + ps.versionCode + "; hiding system");
5071                } else {
5072                    /*
5073                     * The newly found system app is a newer version that the
5074                     * one previously installed. Simply remove the
5075                     * already-installed application and replace it with our own
5076                     * while keeping the application data.
5077                     */
5078                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5079                            + " reverting from " + ps.codePathString + ": new version "
5080                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5081                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5082                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
5083                            getAppDexInstructionSets(ps));
5084                    synchronized (mInstallLock) {
5085                        args.cleanUpResourcesLI();
5086                    }
5087                }
5088            }
5089        }
5090
5091        // The apk is forward locked (not public) if its code and resources
5092        // are kept in different files. (except for app in either system or
5093        // vendor path).
5094        // TODO grab this value from PackageSettings
5095        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5096            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5097                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5098            }
5099        }
5100
5101        // TODO: extend to support forward-locked splits
5102        String resourcePath = null;
5103        String baseResourcePath = null;
5104        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5105            if (ps != null && ps.resourcePathString != null) {
5106                resourcePath = ps.resourcePathString;
5107                baseResourcePath = ps.resourcePathString;
5108            } else {
5109                // Should not happen at all. Just log an error.
5110                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5111            }
5112        } else {
5113            resourcePath = pkg.codePath;
5114            baseResourcePath = pkg.baseCodePath;
5115        }
5116
5117        // Set application objects path explicitly.
5118        pkg.applicationInfo.setCodePath(pkg.codePath);
5119        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5120        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5121        pkg.applicationInfo.setResourcePath(resourcePath);
5122        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5123        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5124
5125        // Note that we invoke the following method only if we are about to unpack an application
5126        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5127                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5128
5129        /*
5130         * If the system app should be overridden by a previously installed
5131         * data, hide the system app now and let the /data/app scan pick it up
5132         * again.
5133         */
5134        if (shouldHideSystemApp) {
5135            synchronized (mPackages) {
5136                /*
5137                 * We have to grant systems permissions before we hide, because
5138                 * grantPermissions will assume the package update is trying to
5139                 * expand its permissions.
5140                 */
5141                grantPermissionsLPw(pkg, true, pkg.packageName);
5142                mSettings.disableSystemPackageLPw(pkg.packageName);
5143            }
5144        }
5145
5146        return scannedPkg;
5147    }
5148
5149    private static String fixProcessName(String defProcessName,
5150            String processName, int uid) {
5151        if (processName == null) {
5152            return defProcessName;
5153        }
5154        return processName;
5155    }
5156
5157    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5158            throws PackageManagerException {
5159        if (pkgSetting.signatures.mSignatures != null) {
5160            // Already existing package. Make sure signatures match
5161            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5162                    == PackageManager.SIGNATURE_MATCH;
5163            if (!match) {
5164                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5165                        == PackageManager.SIGNATURE_MATCH;
5166            }
5167            if (!match) {
5168                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5169                        == PackageManager.SIGNATURE_MATCH;
5170            }
5171            if (!match) {
5172                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5173                        + pkg.packageName + " signatures do not match the "
5174                        + "previously installed version; ignoring!");
5175            }
5176        }
5177
5178        // Check for shared user signatures
5179        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5180            // Already existing package. Make sure signatures match
5181            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5182                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5183            if (!match) {
5184                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5185                        == PackageManager.SIGNATURE_MATCH;
5186            }
5187            if (!match) {
5188                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5189                        == PackageManager.SIGNATURE_MATCH;
5190            }
5191            if (!match) {
5192                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5193                        "Package " + pkg.packageName
5194                        + " has no signatures that match those in shared user "
5195                        + pkgSetting.sharedUser.name + "; ignoring!");
5196            }
5197        }
5198    }
5199
5200    /**
5201     * Enforces that only the system UID or root's UID can call a method exposed
5202     * via Binder.
5203     *
5204     * @param message used as message if SecurityException is thrown
5205     * @throws SecurityException if the caller is not system or root
5206     */
5207    private static final void enforceSystemOrRoot(String message) {
5208        final int uid = Binder.getCallingUid();
5209        if (uid != Process.SYSTEM_UID && uid != 0) {
5210            throw new SecurityException(message);
5211        }
5212    }
5213
5214    @Override
5215    public void performBootDexOpt() {
5216        enforceSystemOrRoot("Only the system can request dexopt be performed");
5217
5218        // Before everything else, see whether we need to fstrim.
5219        try {
5220            IMountService ms = PackageHelper.getMountService();
5221            if (ms != null) {
5222                final boolean isUpgrade = isUpgrade();
5223                boolean doTrim = isUpgrade;
5224                if (doTrim) {
5225                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5226                } else {
5227                    final long interval = android.provider.Settings.Global.getLong(
5228                            mContext.getContentResolver(),
5229                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5230                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5231                    if (interval > 0) {
5232                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5233                        if (timeSinceLast > interval) {
5234                            doTrim = true;
5235                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5236                                    + "; running immediately");
5237                        }
5238                    }
5239                }
5240                if (doTrim) {
5241                    if (!isFirstBoot()) {
5242                        try {
5243                            ActivityManagerNative.getDefault().showBootMessage(
5244                                    mContext.getResources().getString(
5245                                            R.string.android_upgrading_fstrim), true);
5246                        } catch (RemoteException e) {
5247                        }
5248                    }
5249                    ms.runMaintenance();
5250                }
5251            } else {
5252                Slog.e(TAG, "Mount service unavailable!");
5253            }
5254        } catch (RemoteException e) {
5255            // Can't happen; MountService is local
5256        }
5257
5258        final ArraySet<PackageParser.Package> pkgs;
5259        synchronized (mPackages) {
5260            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5261        }
5262
5263        if (pkgs != null) {
5264            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5265            // in case the device runs out of space.
5266            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5267            // Give priority to core apps.
5268            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5269                PackageParser.Package pkg = it.next();
5270                if (pkg.coreApp) {
5271                    if (DEBUG_DEXOPT) {
5272                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5273                    }
5274                    sortedPkgs.add(pkg);
5275                    it.remove();
5276                }
5277            }
5278            // Give priority to system apps that listen for pre boot complete.
5279            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5280            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5281            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5282                PackageParser.Package pkg = it.next();
5283                if (pkgNames.contains(pkg.packageName)) {
5284                    if (DEBUG_DEXOPT) {
5285                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5286                    }
5287                    sortedPkgs.add(pkg);
5288                    it.remove();
5289                }
5290            }
5291            // Give priority to system apps.
5292            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5293                PackageParser.Package pkg = it.next();
5294                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5295                    if (DEBUG_DEXOPT) {
5296                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5297                    }
5298                    sortedPkgs.add(pkg);
5299                    it.remove();
5300                }
5301            }
5302            // Give priority to updated system apps.
5303            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5304                PackageParser.Package pkg = it.next();
5305                if (pkg.isUpdatedSystemApp()) {
5306                    if (DEBUG_DEXOPT) {
5307                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5308                    }
5309                    sortedPkgs.add(pkg);
5310                    it.remove();
5311                }
5312            }
5313            // Give priority to apps that listen for boot complete.
5314            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5315            pkgNames = getPackageNamesForIntent(intent);
5316            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5317                PackageParser.Package pkg = it.next();
5318                if (pkgNames.contains(pkg.packageName)) {
5319                    if (DEBUG_DEXOPT) {
5320                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5321                    }
5322                    sortedPkgs.add(pkg);
5323                    it.remove();
5324                }
5325            }
5326            // Filter out packages that aren't recently used.
5327            filterRecentlyUsedApps(pkgs);
5328            // Add all remaining apps.
5329            for (PackageParser.Package pkg : pkgs) {
5330                if (DEBUG_DEXOPT) {
5331                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5332                }
5333                sortedPkgs.add(pkg);
5334            }
5335
5336            // If we want to be lazy, filter everything that wasn't recently used.
5337            if (mLazyDexOpt) {
5338                filterRecentlyUsedApps(sortedPkgs);
5339            }
5340
5341            int i = 0;
5342            int total = sortedPkgs.size();
5343            File dataDir = Environment.getDataDirectory();
5344            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5345            if (lowThreshold == 0) {
5346                throw new IllegalStateException("Invalid low memory threshold");
5347            }
5348            for (PackageParser.Package pkg : sortedPkgs) {
5349                long usableSpace = dataDir.getUsableSpace();
5350                if (usableSpace < lowThreshold) {
5351                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5352                    break;
5353                }
5354                performBootDexOpt(pkg, ++i, total);
5355            }
5356        }
5357    }
5358
5359    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5360        // Filter out packages that aren't recently used.
5361        //
5362        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5363        // should do a full dexopt.
5364        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5365            int total = pkgs.size();
5366            int skipped = 0;
5367            long now = System.currentTimeMillis();
5368            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5369                PackageParser.Package pkg = i.next();
5370                long then = pkg.mLastPackageUsageTimeInMills;
5371                if (then + mDexOptLRUThresholdInMills < now) {
5372                    if (DEBUG_DEXOPT) {
5373                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5374                              ((then == 0) ? "never" : new Date(then)));
5375                    }
5376                    i.remove();
5377                    skipped++;
5378                }
5379            }
5380            if (DEBUG_DEXOPT) {
5381                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5382            }
5383        }
5384    }
5385
5386    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5387        List<ResolveInfo> ris = null;
5388        try {
5389            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5390                    intent, null, 0, UserHandle.USER_OWNER);
5391        } catch (RemoteException e) {
5392        }
5393        ArraySet<String> pkgNames = new ArraySet<String>();
5394        if (ris != null) {
5395            for (ResolveInfo ri : ris) {
5396                pkgNames.add(ri.activityInfo.packageName);
5397            }
5398        }
5399        return pkgNames;
5400    }
5401
5402    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5403        if (DEBUG_DEXOPT) {
5404            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5405        }
5406        if (!isFirstBoot()) {
5407            try {
5408                ActivityManagerNative.getDefault().showBootMessage(
5409                        mContext.getResources().getString(R.string.android_upgrading_apk,
5410                                curr, total), true);
5411            } catch (RemoteException e) {
5412            }
5413        }
5414        PackageParser.Package p = pkg;
5415        synchronized (mInstallLock) {
5416            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5417                    false /* force dex */, false /* defer */, true /* include dependencies */);
5418        }
5419    }
5420
5421    @Override
5422    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5423        return performDexOpt(packageName, instructionSet, false);
5424    }
5425
5426    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5427        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5428        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5429        if (!dexopt && !updateUsage) {
5430            // We aren't going to dexopt or update usage, so bail early.
5431            return false;
5432        }
5433        PackageParser.Package p;
5434        final String targetInstructionSet;
5435        synchronized (mPackages) {
5436            p = mPackages.get(packageName);
5437            if (p == null) {
5438                return false;
5439            }
5440            if (updateUsage) {
5441                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5442            }
5443            mPackageUsage.write(false);
5444            if (!dexopt) {
5445                // We aren't going to dexopt, so bail early.
5446                return false;
5447            }
5448
5449            targetInstructionSet = instructionSet != null ? instructionSet :
5450                    getPrimaryInstructionSet(p.applicationInfo);
5451            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5452                return false;
5453            }
5454        }
5455
5456        synchronized (mInstallLock) {
5457            final String[] instructionSets = new String[] { targetInstructionSet };
5458            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5459                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5460            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5461        }
5462    }
5463
5464    public ArraySet<String> getPackagesThatNeedDexOpt() {
5465        ArraySet<String> pkgs = null;
5466        synchronized (mPackages) {
5467            for (PackageParser.Package p : mPackages.values()) {
5468                if (DEBUG_DEXOPT) {
5469                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5470                }
5471                if (!p.mDexOptPerformed.isEmpty()) {
5472                    continue;
5473                }
5474                if (pkgs == null) {
5475                    pkgs = new ArraySet<String>();
5476                }
5477                pkgs.add(p.packageName);
5478            }
5479        }
5480        return pkgs;
5481    }
5482
5483    public void shutdown() {
5484        mPackageUsage.write(true);
5485    }
5486
5487    @Override
5488    public void forceDexOpt(String packageName) {
5489        enforceSystemOrRoot("forceDexOpt");
5490
5491        PackageParser.Package pkg;
5492        synchronized (mPackages) {
5493            pkg = mPackages.get(packageName);
5494            if (pkg == null) {
5495                throw new IllegalArgumentException("Missing package: " + packageName);
5496            }
5497        }
5498
5499        synchronized (mInstallLock) {
5500            final String[] instructionSets = new String[] {
5501                    getPrimaryInstructionSet(pkg.applicationInfo) };
5502            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5503                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5504            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5505                throw new IllegalStateException("Failed to dexopt: " + res);
5506            }
5507        }
5508    }
5509
5510    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5511        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5512            Slog.w(TAG, "Unable to update from " + oldPkg.name
5513                    + " to " + newPkg.packageName
5514                    + ": old package not in system partition");
5515            return false;
5516        } else if (mPackages.get(oldPkg.name) != null) {
5517            Slog.w(TAG, "Unable to update from " + oldPkg.name
5518                    + " to " + newPkg.packageName
5519                    + ": old package still exists");
5520            return false;
5521        }
5522        return true;
5523    }
5524
5525    private File getDataPathForPackage(String packageName, int userId) {
5526        /*
5527         * Until we fully support multiple users, return the directory we
5528         * previously would have. The PackageManagerTests will need to be
5529         * revised when this is changed back..
5530         */
5531        if (userId == 0) {
5532            return new File(mAppDataDir, packageName);
5533        } else {
5534            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
5535                + File.separator + packageName);
5536        }
5537    }
5538
5539    private int createDataDirsLI(String packageName, int uid, String seinfo) {
5540        int[] users = sUserManager.getUserIds();
5541        int res = mInstaller.install(packageName, uid, uid, seinfo);
5542        if (res < 0) {
5543            return res;
5544        }
5545        for (int user : users) {
5546            if (user != 0) {
5547                res = mInstaller.createUserData(packageName,
5548                        UserHandle.getUid(user, uid), user, seinfo);
5549                if (res < 0) {
5550                    return res;
5551                }
5552            }
5553        }
5554        return res;
5555    }
5556
5557    private int removeDataDirsLI(String packageName) {
5558        int[] users = sUserManager.getUserIds();
5559        int res = 0;
5560        for (int user : users) {
5561            int resInner = mInstaller.remove(packageName, user);
5562            if (resInner < 0) {
5563                res = resInner;
5564            }
5565        }
5566
5567        return res;
5568    }
5569
5570    private int deleteCodeCacheDirsLI(String packageName) {
5571        int[] users = sUserManager.getUserIds();
5572        int res = 0;
5573        for (int user : users) {
5574            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
5575            if (resInner < 0) {
5576                res = resInner;
5577            }
5578        }
5579        return res;
5580    }
5581
5582    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5583            PackageParser.Package changingLib) {
5584        if (file.path != null) {
5585            usesLibraryFiles.add(file.path);
5586            return;
5587        }
5588        PackageParser.Package p = mPackages.get(file.apk);
5589        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5590            // If we are doing this while in the middle of updating a library apk,
5591            // then we need to make sure to use that new apk for determining the
5592            // dependencies here.  (We haven't yet finished committing the new apk
5593            // to the package manager state.)
5594            if (p == null || p.packageName.equals(changingLib.packageName)) {
5595                p = changingLib;
5596            }
5597        }
5598        if (p != null) {
5599            usesLibraryFiles.addAll(p.getAllCodePaths());
5600        }
5601    }
5602
5603    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5604            PackageParser.Package changingLib) throws PackageManagerException {
5605        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5606            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5607            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5608            for (int i=0; i<N; i++) {
5609                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5610                if (file == null) {
5611                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5612                            "Package " + pkg.packageName + " requires unavailable shared library "
5613                            + pkg.usesLibraries.get(i) + "; failing!");
5614                }
5615                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5616            }
5617            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5618            for (int i=0; i<N; i++) {
5619                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5620                if (file == null) {
5621                    Slog.w(TAG, "Package " + pkg.packageName
5622                            + " desires unavailable shared library "
5623                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5624                } else {
5625                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5626                }
5627            }
5628            N = usesLibraryFiles.size();
5629            if (N > 0) {
5630                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5631            } else {
5632                pkg.usesLibraryFiles = null;
5633            }
5634        }
5635    }
5636
5637    private static boolean hasString(List<String> list, List<String> which) {
5638        if (list == null) {
5639            return false;
5640        }
5641        for (int i=list.size()-1; i>=0; i--) {
5642            for (int j=which.size()-1; j>=0; j--) {
5643                if (which.get(j).equals(list.get(i))) {
5644                    return true;
5645                }
5646            }
5647        }
5648        return false;
5649    }
5650
5651    private void updateAllSharedLibrariesLPw() {
5652        for (PackageParser.Package pkg : mPackages.values()) {
5653            try {
5654                updateSharedLibrariesLPw(pkg, null);
5655            } catch (PackageManagerException e) {
5656                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5657            }
5658        }
5659    }
5660
5661    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5662            PackageParser.Package changingPkg) {
5663        ArrayList<PackageParser.Package> res = null;
5664        for (PackageParser.Package pkg : mPackages.values()) {
5665            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5666                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5667                if (res == null) {
5668                    res = new ArrayList<PackageParser.Package>();
5669                }
5670                res.add(pkg);
5671                try {
5672                    updateSharedLibrariesLPw(pkg, changingPkg);
5673                } catch (PackageManagerException e) {
5674                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5675                }
5676            }
5677        }
5678        return res;
5679    }
5680
5681    /**
5682     * Derive the value of the {@code cpuAbiOverride} based on the provided
5683     * value and an optional stored value from the package settings.
5684     */
5685    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5686        String cpuAbiOverride = null;
5687
5688        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5689            cpuAbiOverride = null;
5690        } else if (abiOverride != null) {
5691            cpuAbiOverride = abiOverride;
5692        } else if (settings != null) {
5693            cpuAbiOverride = settings.cpuAbiOverrideString;
5694        }
5695
5696        return cpuAbiOverride;
5697    }
5698
5699    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5700            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5701        boolean success = false;
5702        try {
5703            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5704                    currentTime, user);
5705            success = true;
5706            return res;
5707        } finally {
5708            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5709                removeDataDirsLI(pkg.packageName);
5710            }
5711        }
5712    }
5713
5714    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5715            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5716        final File scanFile = new File(pkg.codePath);
5717        if (pkg.applicationInfo.getCodePath() == null ||
5718                pkg.applicationInfo.getResourcePath() == null) {
5719            // Bail out. The resource and code paths haven't been set.
5720            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5721                    "Code and resource paths haven't been set correctly");
5722        }
5723
5724        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5725            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5726        } else {
5727            // Only allow system apps to be flagged as core apps.
5728            pkg.coreApp = false;
5729        }
5730
5731        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5732            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5733        }
5734
5735        if (mCustomResolverComponentName != null &&
5736                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5737            setUpCustomResolverActivity(pkg);
5738        }
5739
5740        if (pkg.packageName.equals("android")) {
5741            synchronized (mPackages) {
5742                if (mAndroidApplication != null) {
5743                    Slog.w(TAG, "*************************************************");
5744                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5745                    Slog.w(TAG, " file=" + scanFile);
5746                    Slog.w(TAG, "*************************************************");
5747                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5748                            "Core android package being redefined.  Skipping.");
5749                }
5750
5751                // Set up information for our fall-back user intent resolution activity.
5752                mPlatformPackage = pkg;
5753                pkg.mVersionCode = mSdkVersion;
5754                mAndroidApplication = pkg.applicationInfo;
5755
5756                if (!mResolverReplaced) {
5757                    mResolveActivity.applicationInfo = mAndroidApplication;
5758                    mResolveActivity.name = ResolverActivity.class.getName();
5759                    mResolveActivity.packageName = mAndroidApplication.packageName;
5760                    mResolveActivity.processName = "system:ui";
5761                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5762                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5763                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5764                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5765                    mResolveActivity.exported = true;
5766                    mResolveActivity.enabled = true;
5767                    mResolveInfo.activityInfo = mResolveActivity;
5768                    mResolveInfo.priority = 0;
5769                    mResolveInfo.preferredOrder = 0;
5770                    mResolveInfo.match = 0;
5771                    mResolveComponentName = new ComponentName(
5772                            mAndroidApplication.packageName, mResolveActivity.name);
5773                }
5774            }
5775        }
5776
5777        if (DEBUG_PACKAGE_SCANNING) {
5778            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5779                Log.d(TAG, "Scanning package " + pkg.packageName);
5780        }
5781
5782        if (mPackages.containsKey(pkg.packageName)
5783                || mSharedLibraries.containsKey(pkg.packageName)) {
5784            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5785                    "Application package " + pkg.packageName
5786                    + " already installed.  Skipping duplicate.");
5787        }
5788
5789        // If we're only installing presumed-existing packages, require that the
5790        // scanned APK is both already known and at the path previously established
5791        // for it.  Previously unknown packages we pick up normally, but if we have an
5792        // a priori expectation about this package's install presence, enforce it.
5793        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
5794            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
5795            if (known != null) {
5796                if (DEBUG_PACKAGE_SCANNING) {
5797                    Log.d(TAG, "Examining " + pkg.codePath
5798                            + " and requiring known paths " + known.codePathString
5799                            + " & " + known.resourcePathString);
5800                }
5801                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
5802                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
5803                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
5804                            "Application package " + pkg.packageName
5805                            + " found at " + pkg.applicationInfo.getCodePath()
5806                            + " but expected at " + known.codePathString + "; ignoring.");
5807                }
5808            }
5809        }
5810
5811        // Initialize package source and resource directories
5812        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5813        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5814
5815        SharedUserSetting suid = null;
5816        PackageSetting pkgSetting = null;
5817
5818        if (!isSystemApp(pkg)) {
5819            // Only system apps can use these features.
5820            pkg.mOriginalPackages = null;
5821            pkg.mRealPackage = null;
5822            pkg.mAdoptPermissions = null;
5823        }
5824
5825        // writer
5826        synchronized (mPackages) {
5827            if (pkg.mSharedUserId != null) {
5828                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5829                if (suid == null) {
5830                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5831                            "Creating application package " + pkg.packageName
5832                            + " for shared user failed");
5833                }
5834                if (DEBUG_PACKAGE_SCANNING) {
5835                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5836                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5837                                + "): packages=" + suid.packages);
5838                }
5839            }
5840
5841            // Check if we are renaming from an original package name.
5842            PackageSetting origPackage = null;
5843            String realName = null;
5844            if (pkg.mOriginalPackages != null) {
5845                // This package may need to be renamed to a previously
5846                // installed name.  Let's check on that...
5847                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5848                if (pkg.mOriginalPackages.contains(renamed)) {
5849                    // This package had originally been installed as the
5850                    // original name, and we have already taken care of
5851                    // transitioning to the new one.  Just update the new
5852                    // one to continue using the old name.
5853                    realName = pkg.mRealPackage;
5854                    if (!pkg.packageName.equals(renamed)) {
5855                        // Callers into this function may have already taken
5856                        // care of renaming the package; only do it here if
5857                        // it is not already done.
5858                        pkg.setPackageName(renamed);
5859                    }
5860
5861                } else {
5862                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5863                        if ((origPackage = mSettings.peekPackageLPr(
5864                                pkg.mOriginalPackages.get(i))) != null) {
5865                            // We do have the package already installed under its
5866                            // original name...  should we use it?
5867                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5868                                // New package is not compatible with original.
5869                                origPackage = null;
5870                                continue;
5871                            } else if (origPackage.sharedUser != null) {
5872                                // Make sure uid is compatible between packages.
5873                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5874                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5875                                            + " to " + pkg.packageName + ": old uid "
5876                                            + origPackage.sharedUser.name
5877                                            + " differs from " + pkg.mSharedUserId);
5878                                    origPackage = null;
5879                                    continue;
5880                                }
5881                            } else {
5882                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5883                                        + pkg.packageName + " to old name " + origPackage.name);
5884                            }
5885                            break;
5886                        }
5887                    }
5888                }
5889            }
5890
5891            if (mTransferedPackages.contains(pkg.packageName)) {
5892                Slog.w(TAG, "Package " + pkg.packageName
5893                        + " was transferred to another, but its .apk remains");
5894            }
5895
5896            // Just create the setting, don't add it yet. For already existing packages
5897            // the PkgSetting exists already and doesn't have to be created.
5898            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5899                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5900                    pkg.applicationInfo.primaryCpuAbi,
5901                    pkg.applicationInfo.secondaryCpuAbi,
5902                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
5903                    user, false);
5904            if (pkgSetting == null) {
5905                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5906                        "Creating application package " + pkg.packageName + " failed");
5907            }
5908
5909            if (pkgSetting.origPackage != null) {
5910                // If we are first transitioning from an original package,
5911                // fix up the new package's name now.  We need to do this after
5912                // looking up the package under its new name, so getPackageLP
5913                // can take care of fiddling things correctly.
5914                pkg.setPackageName(origPackage.name);
5915
5916                // File a report about this.
5917                String msg = "New package " + pkgSetting.realName
5918                        + " renamed to replace old package " + pkgSetting.name;
5919                reportSettingsProblem(Log.WARN, msg);
5920
5921                // Make a note of it.
5922                mTransferedPackages.add(origPackage.name);
5923
5924                // No longer need to retain this.
5925                pkgSetting.origPackage = null;
5926            }
5927
5928            if (realName != null) {
5929                // Make a note of it.
5930                mTransferedPackages.add(pkg.packageName);
5931            }
5932
5933            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5934                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5935            }
5936
5937            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5938                // Check all shared libraries and map to their actual file path.
5939                // We only do this here for apps not on a system dir, because those
5940                // are the only ones that can fail an install due to this.  We
5941                // will take care of the system apps by updating all of their
5942                // library paths after the scan is done.
5943                updateSharedLibrariesLPw(pkg, null);
5944            }
5945
5946            if (mFoundPolicyFile) {
5947                SELinuxMMAC.assignSeinfoValue(pkg);
5948            }
5949
5950            pkg.applicationInfo.uid = pkgSetting.appId;
5951            pkg.mExtras = pkgSetting;
5952            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5953                try {
5954                    verifySignaturesLP(pkgSetting, pkg);
5955                    // We just determined the app is signed correctly, so bring
5956                    // over the latest parsed certs.
5957                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5958                } catch (PackageManagerException e) {
5959                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5960                        throw e;
5961                    }
5962                    // The signature has changed, but this package is in the system
5963                    // image...  let's recover!
5964                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5965                    // However...  if this package is part of a shared user, but it
5966                    // doesn't match the signature of the shared user, let's fail.
5967                    // What this means is that you can't change the signatures
5968                    // associated with an overall shared user, which doesn't seem all
5969                    // that unreasonable.
5970                    if (pkgSetting.sharedUser != null) {
5971                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5972                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5973                            throw new PackageManagerException(
5974                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5975                                            "Signature mismatch for shared user : "
5976                                            + pkgSetting.sharedUser);
5977                        }
5978                    }
5979                    // File a report about this.
5980                    String msg = "System package " + pkg.packageName
5981                        + " signature changed; retaining data.";
5982                    reportSettingsProblem(Log.WARN, msg);
5983                }
5984            } else {
5985                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5986                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5987                            + pkg.packageName + " upgrade keys do not match the "
5988                            + "previously installed version");
5989                } else {
5990                    // We just determined the app is signed correctly, so bring
5991                    // over the latest parsed certs.
5992                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5993                }
5994            }
5995            // Verify that this new package doesn't have any content providers
5996            // that conflict with existing packages.  Only do this if the
5997            // package isn't already installed, since we don't want to break
5998            // things that are installed.
5999            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6000                final int N = pkg.providers.size();
6001                int i;
6002                for (i=0; i<N; i++) {
6003                    PackageParser.Provider p = pkg.providers.get(i);
6004                    if (p.info.authority != null) {
6005                        String names[] = p.info.authority.split(";");
6006                        for (int j = 0; j < names.length; j++) {
6007                            if (mProvidersByAuthority.containsKey(names[j])) {
6008                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6009                                final String otherPackageName =
6010                                        ((other != null && other.getComponentName() != null) ?
6011                                                other.getComponentName().getPackageName() : "?");
6012                                throw new PackageManagerException(
6013                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6014                                                "Can't install because provider name " + names[j]
6015                                                + " (in package " + pkg.applicationInfo.packageName
6016                                                + ") is already used by " + otherPackageName);
6017                            }
6018                        }
6019                    }
6020                }
6021            }
6022
6023            if (pkg.mAdoptPermissions != null) {
6024                // This package wants to adopt ownership of permissions from
6025                // another package.
6026                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6027                    final String origName = pkg.mAdoptPermissions.get(i);
6028                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6029                    if (orig != null) {
6030                        if (verifyPackageUpdateLPr(orig, pkg)) {
6031                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6032                                    + pkg.packageName);
6033                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6034                        }
6035                    }
6036                }
6037            }
6038        }
6039
6040        final String pkgName = pkg.packageName;
6041
6042        final long scanFileTime = scanFile.lastModified();
6043        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6044        pkg.applicationInfo.processName = fixProcessName(
6045                pkg.applicationInfo.packageName,
6046                pkg.applicationInfo.processName,
6047                pkg.applicationInfo.uid);
6048
6049        File dataPath;
6050        if (mPlatformPackage == pkg) {
6051            // The system package is special.
6052            dataPath = new File(Environment.getDataDirectory(), "system");
6053
6054            pkg.applicationInfo.dataDir = dataPath.getPath();
6055
6056        } else {
6057            // This is a normal package, need to make its data directory.
6058            dataPath = getDataPathForPackage(pkg.packageName, 0);
6059
6060            boolean uidError = false;
6061            if (dataPath.exists()) {
6062                int currentUid = 0;
6063                try {
6064                    StructStat stat = Os.stat(dataPath.getPath());
6065                    currentUid = stat.st_uid;
6066                } catch (ErrnoException e) {
6067                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6068                }
6069
6070                // If we have mismatched owners for the data path, we have a problem.
6071                if (currentUid != pkg.applicationInfo.uid) {
6072                    boolean recovered = false;
6073                    if (currentUid == 0) {
6074                        // The directory somehow became owned by root.  Wow.
6075                        // This is probably because the system was stopped while
6076                        // installd was in the middle of messing with its libs
6077                        // directory.  Ask installd to fix that.
6078                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
6079                                pkg.applicationInfo.uid);
6080                        if (ret >= 0) {
6081                            recovered = true;
6082                            String msg = "Package " + pkg.packageName
6083                                    + " unexpectedly changed to uid 0; recovered to " +
6084                                    + pkg.applicationInfo.uid;
6085                            reportSettingsProblem(Log.WARN, msg);
6086                        }
6087                    }
6088                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6089                            || (scanFlags&SCAN_BOOTING) != 0)) {
6090                        // If this is a system app, we can at least delete its
6091                        // current data so the application will still work.
6092                        int ret = removeDataDirsLI(pkgName);
6093                        if (ret >= 0) {
6094                            // TODO: Kill the processes first
6095                            // Old data gone!
6096                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6097                                    ? "System package " : "Third party package ";
6098                            String msg = prefix + pkg.packageName
6099                                    + " has changed from uid: "
6100                                    + currentUid + " to "
6101                                    + pkg.applicationInfo.uid + "; old data erased";
6102                            reportSettingsProblem(Log.WARN, msg);
6103                            recovered = true;
6104
6105                            // And now re-install the app.
6106                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
6107                                                   pkg.applicationInfo.seinfo);
6108                            if (ret == -1) {
6109                                // Ack should not happen!
6110                                msg = prefix + pkg.packageName
6111                                        + " could not have data directory re-created after delete.";
6112                                reportSettingsProblem(Log.WARN, msg);
6113                                throw new PackageManagerException(
6114                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6115                            }
6116                        }
6117                        if (!recovered) {
6118                            mHasSystemUidErrors = true;
6119                        }
6120                    } else if (!recovered) {
6121                        // If we allow this install to proceed, we will be broken.
6122                        // Abort, abort!
6123                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6124                                "scanPackageLI");
6125                    }
6126                    if (!recovered) {
6127                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6128                            + pkg.applicationInfo.uid + "/fs_"
6129                            + currentUid;
6130                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6131                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6132                        String msg = "Package " + pkg.packageName
6133                                + " has mismatched uid: "
6134                                + currentUid + " on disk, "
6135                                + pkg.applicationInfo.uid + " in settings";
6136                        // writer
6137                        synchronized (mPackages) {
6138                            mSettings.mReadMessages.append(msg);
6139                            mSettings.mReadMessages.append('\n');
6140                            uidError = true;
6141                            if (!pkgSetting.uidError) {
6142                                reportSettingsProblem(Log.ERROR, msg);
6143                            }
6144                        }
6145                    }
6146                }
6147                pkg.applicationInfo.dataDir = dataPath.getPath();
6148                if (mShouldRestoreconData) {
6149                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6150                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
6151                                pkg.applicationInfo.uid);
6152                }
6153            } else {
6154                if (DEBUG_PACKAGE_SCANNING) {
6155                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6156                        Log.v(TAG, "Want this data dir: " + dataPath);
6157                }
6158                //invoke installer to do the actual installation
6159                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
6160                                           pkg.applicationInfo.seinfo);
6161                if (ret < 0) {
6162                    // Error from installer
6163                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6164                            "Unable to create data dirs [errorCode=" + ret + "]");
6165                }
6166
6167                if (dataPath.exists()) {
6168                    pkg.applicationInfo.dataDir = dataPath.getPath();
6169                } else {
6170                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6171                    pkg.applicationInfo.dataDir = null;
6172                }
6173            }
6174
6175            pkgSetting.uidError = uidError;
6176        }
6177
6178        final String path = scanFile.getPath();
6179        final String codePath = pkg.applicationInfo.getCodePath();
6180        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6181        if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6182            setBundledAppAbisAndRoots(pkg, pkgSetting);
6183
6184            // If we haven't found any native libraries for the app, check if it has
6185            // renderscript code. We'll need to force the app to 32 bit if it has
6186            // renderscript bitcode.
6187            if (pkg.applicationInfo.primaryCpuAbi == null
6188                    && pkg.applicationInfo.secondaryCpuAbi == null
6189                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
6190                NativeLibraryHelper.Handle handle = null;
6191                try {
6192                    handle = NativeLibraryHelper.Handle.create(scanFile);
6193                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6194                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6195                    }
6196                } catch (IOException ioe) {
6197                    Slog.w(TAG, "Error scanning system app : " + ioe);
6198                } finally {
6199                    IoUtils.closeQuietly(handle);
6200                }
6201            }
6202
6203            setNativeLibraryPaths(pkg);
6204        } else {
6205            // TODO: We can probably be smarter about this stuff. For installed apps,
6206            // we can calculate this information at install time once and for all. For
6207            // system apps, we can probably assume that this information doesn't change
6208            // after the first boot scan. As things stand, we do lots of unnecessary work.
6209
6210            // Give ourselves some initial paths; we'll come back for another
6211            // pass once we've determined ABI below.
6212            setNativeLibraryPaths(pkg);
6213
6214            final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg);
6215            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6216            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6217
6218            NativeLibraryHelper.Handle handle = null;
6219            try {
6220                handle = NativeLibraryHelper.Handle.create(scanFile);
6221                // TODO(multiArch): This can be null for apps that didn't go through the
6222                // usual installation process. We can calculate it again, like we
6223                // do during install time.
6224                //
6225                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6226                // unnecessary.
6227                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6228
6229                // Null out the abis so that they can be recalculated.
6230                pkg.applicationInfo.primaryCpuAbi = null;
6231                pkg.applicationInfo.secondaryCpuAbi = null;
6232                if (isMultiArch(pkg.applicationInfo)) {
6233                    // Warn if we've set an abiOverride for multi-lib packages..
6234                    // By definition, we need to copy both 32 and 64 bit libraries for
6235                    // such packages.
6236                    if (pkg.cpuAbiOverride != null
6237                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
6238                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
6239                    }
6240
6241                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
6242                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
6243                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
6244                        if (isAsec) {
6245                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
6246                        } else {
6247                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6248                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
6249                                    useIsaSpecificSubdirs);
6250                        }
6251                    }
6252
6253                    maybeThrowExceptionForMultiArchCopy(
6254                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
6255
6256                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
6257                        if (isAsec) {
6258                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
6259                        } else {
6260                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6261                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
6262                                    useIsaSpecificSubdirs);
6263                        }
6264                    }
6265
6266                    maybeThrowExceptionForMultiArchCopy(
6267                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
6268
6269                    if (abi64 >= 0) {
6270                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
6271                    }
6272
6273                    if (abi32 >= 0) {
6274                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
6275                        if (abi64 >= 0) {
6276                            pkg.applicationInfo.secondaryCpuAbi = abi;
6277                        } else {
6278                            pkg.applicationInfo.primaryCpuAbi = abi;
6279                        }
6280                    }
6281                } else {
6282                    String[] abiList = (cpuAbiOverride != null) ?
6283                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
6284
6285                    // Enable gross and lame hacks for apps that are built with old
6286                    // SDK tools. We must scan their APKs for renderscript bitcode and
6287                    // not launch them if it's present. Don't bother checking on devices
6288                    // that don't have 64 bit support.
6289                    boolean needsRenderScriptOverride = false;
6290                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
6291                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6292                        abiList = Build.SUPPORTED_32_BIT_ABIS;
6293                        needsRenderScriptOverride = true;
6294                    }
6295
6296                    final int copyRet;
6297                    if (isAsec) {
6298                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6299                    } else {
6300                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6301                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
6302                    }
6303
6304                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
6305                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6306                                "Error unpackaging native libs for app, errorCode=" + copyRet);
6307                    }
6308
6309                    if (copyRet >= 0) {
6310                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
6311                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
6312                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
6313                    } else if (needsRenderScriptOverride) {
6314                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
6315                    }
6316                }
6317            } catch (IOException ioe) {
6318                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
6319            } finally {
6320                IoUtils.closeQuietly(handle);
6321            }
6322
6323            // Now that we've calculated the ABIs and determined if it's an internal app,
6324            // we will go ahead and populate the nativeLibraryPath.
6325            setNativeLibraryPaths(pkg);
6326
6327            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6328            final int[] userIds = sUserManager.getUserIds();
6329            synchronized (mInstallLock) {
6330                // Create a native library symlink only if we have native libraries
6331                // and if the native libraries are 32 bit libraries. We do not provide
6332                // this symlink for 64 bit libraries.
6333                if (pkg.applicationInfo.primaryCpuAbi != null &&
6334                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6335                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6336                    for (int userId : userIds) {
6337                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
6338                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6339                                    "Failed linking native library dir (user=" + userId + ")");
6340                        }
6341                    }
6342                }
6343            }
6344        }
6345
6346        // This is a special case for the "system" package, where the ABI is
6347        // dictated by the zygote configuration (and init.rc). We should keep track
6348        // of this ABI so that we can deal with "normal" applications that run under
6349        // the same UID correctly.
6350        if (mPlatformPackage == pkg) {
6351            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6352                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6353        }
6354
6355        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6356        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6357        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6358        // Copy the derived override back to the parsed package, so that we can
6359        // update the package settings accordingly.
6360        pkg.cpuAbiOverride = cpuAbiOverride;
6361
6362        if (DEBUG_ABI_SELECTION) {
6363            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6364                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6365                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6366        }
6367
6368        // Push the derived path down into PackageSettings so we know what to
6369        // clean up at uninstall time.
6370        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6371
6372        if (DEBUG_ABI_SELECTION) {
6373            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6374                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6375                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6376        }
6377
6378        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6379            // We don't do this here during boot because we can do it all
6380            // at once after scanning all existing packages.
6381            //
6382            // We also do this *before* we perform dexopt on this package, so that
6383            // we can avoid redundant dexopts, and also to make sure we've got the
6384            // code and package path correct.
6385            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6386                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6387        }
6388
6389        if ((scanFlags & SCAN_NO_DEX) == 0) {
6390            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6391                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6392            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6393                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6394            }
6395        }
6396        if (mFactoryTest && pkg.requestedPermissions.contains(
6397                android.Manifest.permission.FACTORY_TEST)) {
6398            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6399        }
6400
6401        ArrayList<PackageParser.Package> clientLibPkgs = null;
6402
6403        // writer
6404        synchronized (mPackages) {
6405            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6406                // Only system apps can add new shared libraries.
6407                if (pkg.libraryNames != null) {
6408                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6409                        String name = pkg.libraryNames.get(i);
6410                        boolean allowed = false;
6411                        if (pkg.isUpdatedSystemApp()) {
6412                            // New library entries can only be added through the
6413                            // system image.  This is important to get rid of a lot
6414                            // of nasty edge cases: for example if we allowed a non-
6415                            // system update of the app to add a library, then uninstalling
6416                            // the update would make the library go away, and assumptions
6417                            // we made such as through app install filtering would now
6418                            // have allowed apps on the device which aren't compatible
6419                            // with it.  Better to just have the restriction here, be
6420                            // conservative, and create many fewer cases that can negatively
6421                            // impact the user experience.
6422                            final PackageSetting sysPs = mSettings
6423                                    .getDisabledSystemPkgLPr(pkg.packageName);
6424                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6425                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6426                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6427                                        allowed = true;
6428                                        allowed = true;
6429                                        break;
6430                                    }
6431                                }
6432                            }
6433                        } else {
6434                            allowed = true;
6435                        }
6436                        if (allowed) {
6437                            if (!mSharedLibraries.containsKey(name)) {
6438                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6439                            } else if (!name.equals(pkg.packageName)) {
6440                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6441                                        + name + " already exists; skipping");
6442                            }
6443                        } else {
6444                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6445                                    + name + " that is not declared on system image; skipping");
6446                        }
6447                    }
6448                    if ((scanFlags&SCAN_BOOTING) == 0) {
6449                        // If we are not booting, we need to update any applications
6450                        // that are clients of our shared library.  If we are booting,
6451                        // this will all be done once the scan is complete.
6452                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6453                    }
6454                }
6455            }
6456        }
6457
6458        // We also need to dexopt any apps that are dependent on this library.  Note that
6459        // if these fail, we should abort the install since installing the library will
6460        // result in some apps being broken.
6461        if (clientLibPkgs != null) {
6462            if ((scanFlags & SCAN_NO_DEX) == 0) {
6463                for (int i = 0; i < clientLibPkgs.size(); i++) {
6464                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6465                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6466                            null /* instruction sets */, forceDex,
6467                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6468                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6469                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6470                                "scanPackageLI failed to dexopt clientLibPkgs");
6471                    }
6472                }
6473            }
6474        }
6475
6476        // Request the ActivityManager to kill the process(only for existing packages)
6477        // so that we do not end up in a confused state while the user is still using the older
6478        // version of the application while the new one gets installed.
6479        if ((scanFlags & SCAN_REPLACING) != 0) {
6480            killApplication(pkg.applicationInfo.packageName,
6481                        pkg.applicationInfo.uid, "update pkg");
6482        }
6483
6484        // Also need to kill any apps that are dependent on the library.
6485        if (clientLibPkgs != null) {
6486            for (int i=0; i<clientLibPkgs.size(); i++) {
6487                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6488                killApplication(clientPkg.applicationInfo.packageName,
6489                        clientPkg.applicationInfo.uid, "update lib");
6490            }
6491        }
6492
6493        // writer
6494        synchronized (mPackages) {
6495            // We don't expect installation to fail beyond this point
6496
6497            // Add the new setting to mSettings
6498            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6499            // Add the new setting to mPackages
6500            mPackages.put(pkg.applicationInfo.packageName, pkg);
6501            // Make sure we don't accidentally delete its data.
6502            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6503            while (iter.hasNext()) {
6504                PackageCleanItem item = iter.next();
6505                if (pkgName.equals(item.packageName)) {
6506                    iter.remove();
6507                }
6508            }
6509
6510            // Take care of first install / last update times.
6511            if (currentTime != 0) {
6512                if (pkgSetting.firstInstallTime == 0) {
6513                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6514                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6515                    pkgSetting.lastUpdateTime = currentTime;
6516                }
6517            } else if (pkgSetting.firstInstallTime == 0) {
6518                // We need *something*.  Take time time stamp of the file.
6519                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6520            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6521                if (scanFileTime != pkgSetting.timeStamp) {
6522                    // A package on the system image has changed; consider this
6523                    // to be an update.
6524                    pkgSetting.lastUpdateTime = scanFileTime;
6525                }
6526            }
6527
6528            // Add the package's KeySets to the global KeySetManagerService
6529            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6530            try {
6531                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6532                if (pkg.mKeySetMapping != null) {
6533                    ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping);
6534                    if (pkg.mUpgradeKeySets != null) {
6535                        ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets);
6536                    }
6537                }
6538            } catch (NullPointerException e) {
6539                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6540            } catch (IllegalArgumentException e) {
6541                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6542            }
6543
6544            int N = pkg.providers.size();
6545            StringBuilder r = null;
6546            int i;
6547            for (i=0; i<N; i++) {
6548                PackageParser.Provider p = pkg.providers.get(i);
6549                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6550                        p.info.processName, pkg.applicationInfo.uid);
6551                mProviders.addProvider(p);
6552                p.syncable = p.info.isSyncable;
6553                if (p.info.authority != null) {
6554                    String names[] = p.info.authority.split(";");
6555                    p.info.authority = null;
6556                    for (int j = 0; j < names.length; j++) {
6557                        if (j == 1 && p.syncable) {
6558                            // We only want the first authority for a provider to possibly be
6559                            // syncable, so if we already added this provider using a different
6560                            // authority clear the syncable flag. We copy the provider before
6561                            // changing it because the mProviders object contains a reference
6562                            // to a provider that we don't want to change.
6563                            // Only do this for the second authority since the resulting provider
6564                            // object can be the same for all future authorities for this provider.
6565                            p = new PackageParser.Provider(p);
6566                            p.syncable = false;
6567                        }
6568                        if (!mProvidersByAuthority.containsKey(names[j])) {
6569                            mProvidersByAuthority.put(names[j], p);
6570                            if (p.info.authority == null) {
6571                                p.info.authority = names[j];
6572                            } else {
6573                                p.info.authority = p.info.authority + ";" + names[j];
6574                            }
6575                            if (DEBUG_PACKAGE_SCANNING) {
6576                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6577                                    Log.d(TAG, "Registered content provider: " + names[j]
6578                                            + ", className = " + p.info.name + ", isSyncable = "
6579                                            + p.info.isSyncable);
6580                            }
6581                        } else {
6582                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6583                            Slog.w(TAG, "Skipping provider name " + names[j] +
6584                                    " (in package " + pkg.applicationInfo.packageName +
6585                                    "): name already used by "
6586                                    + ((other != null && other.getComponentName() != null)
6587                                            ? other.getComponentName().getPackageName() : "?"));
6588                        }
6589                    }
6590                }
6591                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6592                    if (r == null) {
6593                        r = new StringBuilder(256);
6594                    } else {
6595                        r.append(' ');
6596                    }
6597                    r.append(p.info.name);
6598                }
6599            }
6600            if (r != null) {
6601                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6602            }
6603
6604            N = pkg.services.size();
6605            r = null;
6606            for (i=0; i<N; i++) {
6607                PackageParser.Service s = pkg.services.get(i);
6608                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6609                        s.info.processName, pkg.applicationInfo.uid);
6610                mServices.addService(s);
6611                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6612                    if (r == null) {
6613                        r = new StringBuilder(256);
6614                    } else {
6615                        r.append(' ');
6616                    }
6617                    r.append(s.info.name);
6618                }
6619            }
6620            if (r != null) {
6621                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6622            }
6623
6624            N = pkg.receivers.size();
6625            r = null;
6626            for (i=0; i<N; i++) {
6627                PackageParser.Activity a = pkg.receivers.get(i);
6628                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6629                        a.info.processName, pkg.applicationInfo.uid);
6630                mReceivers.addActivity(a, "receiver");
6631                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6632                    if (r == null) {
6633                        r = new StringBuilder(256);
6634                    } else {
6635                        r.append(' ');
6636                    }
6637                    r.append(a.info.name);
6638                }
6639            }
6640            if (r != null) {
6641                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6642            }
6643
6644            N = pkg.activities.size();
6645            r = null;
6646            for (i=0; i<N; i++) {
6647                PackageParser.Activity a = pkg.activities.get(i);
6648                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6649                        a.info.processName, pkg.applicationInfo.uid);
6650                mActivities.addActivity(a, "activity");
6651                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6652                    if (r == null) {
6653                        r = new StringBuilder(256);
6654                    } else {
6655                        r.append(' ');
6656                    }
6657                    r.append(a.info.name);
6658                }
6659            }
6660            if (r != null) {
6661                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6662            }
6663
6664            N = pkg.permissionGroups.size();
6665            r = null;
6666            for (i=0; i<N; i++) {
6667                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6668                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6669                if (cur == null) {
6670                    mPermissionGroups.put(pg.info.name, pg);
6671                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6672                        if (r == null) {
6673                            r = new StringBuilder(256);
6674                        } else {
6675                            r.append(' ');
6676                        }
6677                        r.append(pg.info.name);
6678                    }
6679                } else {
6680                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6681                            + pg.info.packageName + " ignored: original from "
6682                            + cur.info.packageName);
6683                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6684                        if (r == null) {
6685                            r = new StringBuilder(256);
6686                        } else {
6687                            r.append(' ');
6688                        }
6689                        r.append("DUP:");
6690                        r.append(pg.info.name);
6691                    }
6692                }
6693            }
6694            if (r != null) {
6695                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6696            }
6697
6698            N = pkg.permissions.size();
6699            r = null;
6700            for (i=0; i<N; i++) {
6701                PackageParser.Permission p = pkg.permissions.get(i);
6702                ArrayMap<String, BasePermission> permissionMap =
6703                        p.tree ? mSettings.mPermissionTrees
6704                        : mSettings.mPermissions;
6705                p.group = mPermissionGroups.get(p.info.group);
6706                if (p.info.group == null || p.group != null) {
6707                    BasePermission bp = permissionMap.get(p.info.name);
6708
6709                    // Allow system apps to redefine non-system permissions
6710                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6711                        final boolean currentOwnerIsSystem = (bp.perm != null
6712                                && isSystemApp(bp.perm.owner));
6713                        if (isSystemApp(p.owner)) {
6714                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6715                                // It's a built-in permission and no owner, take ownership now
6716                                bp.packageSetting = pkgSetting;
6717                                bp.perm = p;
6718                                bp.uid = pkg.applicationInfo.uid;
6719                                bp.sourcePackage = p.info.packageName;
6720                            } else if (!currentOwnerIsSystem) {
6721                                String msg = "New decl " + p.owner + " of permission  "
6722                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6723                                reportSettingsProblem(Log.WARN, msg);
6724                                bp = null;
6725                            }
6726                        }
6727                    }
6728
6729                    if (bp == null) {
6730                        bp = new BasePermission(p.info.name, p.info.packageName,
6731                                BasePermission.TYPE_NORMAL);
6732                        permissionMap.put(p.info.name, bp);
6733                    }
6734
6735                    if (bp.perm == null) {
6736                        if (bp.sourcePackage == null
6737                                || bp.sourcePackage.equals(p.info.packageName)) {
6738                            BasePermission tree = findPermissionTreeLP(p.info.name);
6739                            if (tree == null
6740                                    || tree.sourcePackage.equals(p.info.packageName)) {
6741                                bp.packageSetting = pkgSetting;
6742                                bp.perm = p;
6743                                bp.uid = pkg.applicationInfo.uid;
6744                                bp.sourcePackage = p.info.packageName;
6745                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6746                                    if (r == null) {
6747                                        r = new StringBuilder(256);
6748                                    } else {
6749                                        r.append(' ');
6750                                    }
6751                                    r.append(p.info.name);
6752                                }
6753                            } else {
6754                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6755                                        + p.info.packageName + " ignored: base tree "
6756                                        + tree.name + " is from package "
6757                                        + tree.sourcePackage);
6758                            }
6759                        } else {
6760                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6761                                    + p.info.packageName + " ignored: original from "
6762                                    + bp.sourcePackage);
6763                        }
6764                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6765                        if (r == null) {
6766                            r = new StringBuilder(256);
6767                        } else {
6768                            r.append(' ');
6769                        }
6770                        r.append("DUP:");
6771                        r.append(p.info.name);
6772                    }
6773                    if (bp.perm == p) {
6774                        bp.protectionLevel = p.info.protectionLevel;
6775                    }
6776                } else {
6777                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6778                            + p.info.packageName + " ignored: no group "
6779                            + p.group);
6780                }
6781            }
6782            if (r != null) {
6783                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6784            }
6785
6786            N = pkg.instrumentation.size();
6787            r = null;
6788            for (i=0; i<N; i++) {
6789                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6790                a.info.packageName = pkg.applicationInfo.packageName;
6791                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6792                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6793                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6794                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6795                a.info.dataDir = pkg.applicationInfo.dataDir;
6796
6797                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6798                // need other information about the application, like the ABI and what not ?
6799                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6800                mInstrumentation.put(a.getComponentName(), a);
6801                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6802                    if (r == null) {
6803                        r = new StringBuilder(256);
6804                    } else {
6805                        r.append(' ');
6806                    }
6807                    r.append(a.info.name);
6808                }
6809            }
6810            if (r != null) {
6811                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6812            }
6813
6814            if (pkg.protectedBroadcasts != null) {
6815                N = pkg.protectedBroadcasts.size();
6816                for (i=0; i<N; i++) {
6817                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6818                }
6819            }
6820
6821            pkgSetting.setTimeStamp(scanFileTime);
6822
6823            // Create idmap files for pairs of (packages, overlay packages).
6824            // Note: "android", ie framework-res.apk, is handled by native layers.
6825            if (pkg.mOverlayTarget != null) {
6826                // This is an overlay package.
6827                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6828                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6829                        mOverlays.put(pkg.mOverlayTarget,
6830                                new ArrayMap<String, PackageParser.Package>());
6831                    }
6832                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6833                    map.put(pkg.packageName, pkg);
6834                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6835                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6836                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6837                                "scanPackageLI failed to createIdmap");
6838                    }
6839                }
6840            } else if (mOverlays.containsKey(pkg.packageName) &&
6841                    !pkg.packageName.equals("android")) {
6842                // This is a regular package, with one or more known overlay packages.
6843                createIdmapsForPackageLI(pkg);
6844            }
6845        }
6846
6847        return pkg;
6848    }
6849
6850    /**
6851     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6852     * i.e, so that all packages can be run inside a single process if required.
6853     *
6854     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6855     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6856     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6857     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6858     * updating a package that belongs to a shared user.
6859     *
6860     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6861     * adds unnecessary complexity.
6862     */
6863    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6864            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6865        String requiredInstructionSet = null;
6866        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6867            requiredInstructionSet = VMRuntime.getInstructionSet(
6868                     scannedPackage.applicationInfo.primaryCpuAbi);
6869        }
6870
6871        PackageSetting requirer = null;
6872        for (PackageSetting ps : packagesForUser) {
6873            // If packagesForUser contains scannedPackage, we skip it. This will happen
6874            // when scannedPackage is an update of an existing package. Without this check,
6875            // we will never be able to change the ABI of any package belonging to a shared
6876            // user, even if it's compatible with other packages.
6877            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6878                if (ps.primaryCpuAbiString == null) {
6879                    continue;
6880                }
6881
6882                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6883                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6884                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6885                    // this but there's not much we can do.
6886                    String errorMessage = "Instruction set mismatch, "
6887                            + ((requirer == null) ? "[caller]" : requirer)
6888                            + " requires " + requiredInstructionSet + " whereas " + ps
6889                            + " requires " + instructionSet;
6890                    Slog.w(TAG, errorMessage);
6891                }
6892
6893                if (requiredInstructionSet == null) {
6894                    requiredInstructionSet = instructionSet;
6895                    requirer = ps;
6896                }
6897            }
6898        }
6899
6900        if (requiredInstructionSet != null) {
6901            String adjustedAbi;
6902            if (requirer != null) {
6903                // requirer != null implies that either scannedPackage was null or that scannedPackage
6904                // did not require an ABI, in which case we have to adjust scannedPackage to match
6905                // the ABI of the set (which is the same as requirer's ABI)
6906                adjustedAbi = requirer.primaryCpuAbiString;
6907                if (scannedPackage != null) {
6908                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6909                }
6910            } else {
6911                // requirer == null implies that we're updating all ABIs in the set to
6912                // match scannedPackage.
6913                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6914            }
6915
6916            for (PackageSetting ps : packagesForUser) {
6917                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6918                    if (ps.primaryCpuAbiString != null) {
6919                        continue;
6920                    }
6921
6922                    ps.primaryCpuAbiString = adjustedAbi;
6923                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6924                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6925                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6926
6927                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
6928                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
6929                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6930                            ps.primaryCpuAbiString = null;
6931                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6932                            return;
6933                        } else {
6934                            mInstaller.rmdex(ps.codePathString,
6935                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
6936                        }
6937                    }
6938                }
6939            }
6940        }
6941    }
6942
6943    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6944        synchronized (mPackages) {
6945            mResolverReplaced = true;
6946            // Set up information for custom user intent resolution activity.
6947            mResolveActivity.applicationInfo = pkg.applicationInfo;
6948            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6949            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6950            mResolveActivity.processName = pkg.applicationInfo.packageName;
6951            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6952            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6953                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6954            mResolveActivity.theme = 0;
6955            mResolveActivity.exported = true;
6956            mResolveActivity.enabled = true;
6957            mResolveInfo.activityInfo = mResolveActivity;
6958            mResolveInfo.priority = 0;
6959            mResolveInfo.preferredOrder = 0;
6960            mResolveInfo.match = 0;
6961            mResolveComponentName = mCustomResolverComponentName;
6962            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6963                    mResolveComponentName);
6964        }
6965    }
6966
6967    private static String calculateBundledApkRoot(final String codePathString) {
6968        final File codePath = new File(codePathString);
6969        final File codeRoot;
6970        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6971            codeRoot = Environment.getRootDirectory();
6972        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6973            codeRoot = Environment.getOemDirectory();
6974        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6975            codeRoot = Environment.getVendorDirectory();
6976        } else {
6977            // Unrecognized code path; take its top real segment as the apk root:
6978            // e.g. /something/app/blah.apk => /something
6979            try {
6980                File f = codePath.getCanonicalFile();
6981                File parent = f.getParentFile();    // non-null because codePath is a file
6982                File tmp;
6983                while ((tmp = parent.getParentFile()) != null) {
6984                    f = parent;
6985                    parent = tmp;
6986                }
6987                codeRoot = f;
6988                Slog.w(TAG, "Unrecognized code path "
6989                        + codePath + " - using " + codeRoot);
6990            } catch (IOException e) {
6991                // Can't canonicalize the code path -- shenanigans?
6992                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6993                return Environment.getRootDirectory().getPath();
6994            }
6995        }
6996        return codeRoot.getPath();
6997    }
6998
6999    /**
7000     * Derive and set the location of native libraries for the given package,
7001     * which varies depending on where and how the package was installed.
7002     */
7003    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7004        final ApplicationInfo info = pkg.applicationInfo;
7005        final String codePath = pkg.codePath;
7006        final File codeFile = new File(codePath);
7007        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7008        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7009
7010        info.nativeLibraryRootDir = null;
7011        info.nativeLibraryRootRequiresIsa = false;
7012        info.nativeLibraryDir = null;
7013        info.secondaryNativeLibraryDir = null;
7014
7015        if (isApkFile(codeFile)) {
7016            // Monolithic install
7017            if (bundledApp) {
7018                // If "/system/lib64/apkname" exists, assume that is the per-package
7019                // native library directory to use; otherwise use "/system/lib/apkname".
7020                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7021                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7022                        getPrimaryInstructionSet(info));
7023
7024                // This is a bundled system app so choose the path based on the ABI.
7025                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7026                // is just the default path.
7027                final String apkName = deriveCodePathName(codePath);
7028                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7029                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7030                        apkName).getAbsolutePath();
7031
7032                if (info.secondaryCpuAbi != null) {
7033                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7034                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7035                            secondaryLibDir, apkName).getAbsolutePath();
7036                }
7037            } else if (asecApp) {
7038                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7039                        .getAbsolutePath();
7040            } else {
7041                final String apkName = deriveCodePathName(codePath);
7042                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7043                        .getAbsolutePath();
7044            }
7045
7046            info.nativeLibraryRootRequiresIsa = false;
7047            info.nativeLibraryDir = info.nativeLibraryRootDir;
7048        } else {
7049            // Cluster install
7050            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7051            info.nativeLibraryRootRequiresIsa = true;
7052
7053            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7054                    getPrimaryInstructionSet(info)).getAbsolutePath();
7055
7056            if (info.secondaryCpuAbi != null) {
7057                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7058                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7059            }
7060        }
7061    }
7062
7063    /**
7064     * Calculate the abis and roots for a bundled app. These can uniquely
7065     * be determined from the contents of the system partition, i.e whether
7066     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7067     * of this information, and instead assume that the system was built
7068     * sensibly.
7069     */
7070    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7071                                           PackageSetting pkgSetting) {
7072        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7073
7074        // If "/system/lib64/apkname" exists, assume that is the per-package
7075        // native library directory to use; otherwise use "/system/lib/apkname".
7076        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7077        setBundledAppAbi(pkg, apkRoot, apkName);
7078        // pkgSetting might be null during rescan following uninstall of updates
7079        // to a bundled app, so accommodate that possibility.  The settings in
7080        // that case will be established later from the parsed package.
7081        //
7082        // If the settings aren't null, sync them up with what we've just derived.
7083        // note that apkRoot isn't stored in the package settings.
7084        if (pkgSetting != null) {
7085            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7086            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7087        }
7088    }
7089
7090    /**
7091     * Deduces the ABI of a bundled app and sets the relevant fields on the
7092     * parsed pkg object.
7093     *
7094     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7095     *        under which system libraries are installed.
7096     * @param apkName the name of the installed package.
7097     */
7098    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7099        final File codeFile = new File(pkg.codePath);
7100
7101        final boolean has64BitLibs;
7102        final boolean has32BitLibs;
7103        if (isApkFile(codeFile)) {
7104            // Monolithic install
7105            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7106            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7107        } else {
7108            // Cluster install
7109            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7110            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7111                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7112                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7113                has64BitLibs = (new File(rootDir, isa)).exists();
7114            } else {
7115                has64BitLibs = false;
7116            }
7117            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7118                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7119                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7120                has32BitLibs = (new File(rootDir, isa)).exists();
7121            } else {
7122                has32BitLibs = false;
7123            }
7124        }
7125
7126        if (has64BitLibs && !has32BitLibs) {
7127            // The package has 64 bit libs, but not 32 bit libs. Its primary
7128            // ABI should be 64 bit. We can safely assume here that the bundled
7129            // native libraries correspond to the most preferred ABI in the list.
7130
7131            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7132            pkg.applicationInfo.secondaryCpuAbi = null;
7133        } else if (has32BitLibs && !has64BitLibs) {
7134            // The package has 32 bit libs but not 64 bit libs. Its primary
7135            // ABI should be 32 bit.
7136
7137            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7138            pkg.applicationInfo.secondaryCpuAbi = null;
7139        } else if (has32BitLibs && has64BitLibs) {
7140            // The application has both 64 and 32 bit bundled libraries. We check
7141            // here that the app declares multiArch support, and warn if it doesn't.
7142            //
7143            // We will be lenient here and record both ABIs. The primary will be the
7144            // ABI that's higher on the list, i.e, a device that's configured to prefer
7145            // 64 bit apps will see a 64 bit primary ABI,
7146
7147            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7148                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7149            }
7150
7151            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7152                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7153                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7154            } else {
7155                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7156                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7157            }
7158        } else {
7159            pkg.applicationInfo.primaryCpuAbi = null;
7160            pkg.applicationInfo.secondaryCpuAbi = null;
7161        }
7162    }
7163
7164    private void killApplication(String pkgName, int appId, String reason) {
7165        // Request the ActivityManager to kill the process(only for existing packages)
7166        // so that we do not end up in a confused state while the user is still using the older
7167        // version of the application while the new one gets installed.
7168        IActivityManager am = ActivityManagerNative.getDefault();
7169        if (am != null) {
7170            try {
7171                am.killApplicationWithAppId(pkgName, appId, reason);
7172            } catch (RemoteException e) {
7173            }
7174        }
7175    }
7176
7177    void removePackageLI(PackageSetting ps, boolean chatty) {
7178        if (DEBUG_INSTALL) {
7179            if (chatty)
7180                Log.d(TAG, "Removing package " + ps.name);
7181        }
7182
7183        // writer
7184        synchronized (mPackages) {
7185            mPackages.remove(ps.name);
7186            final PackageParser.Package pkg = ps.pkg;
7187            if (pkg != null) {
7188                cleanPackageDataStructuresLILPw(pkg, chatty);
7189            }
7190        }
7191    }
7192
7193    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7194        if (DEBUG_INSTALL) {
7195            if (chatty)
7196                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7197        }
7198
7199        // writer
7200        synchronized (mPackages) {
7201            mPackages.remove(pkg.applicationInfo.packageName);
7202            cleanPackageDataStructuresLILPw(pkg, chatty);
7203        }
7204    }
7205
7206    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7207        int N = pkg.providers.size();
7208        StringBuilder r = null;
7209        int i;
7210        for (i=0; i<N; i++) {
7211            PackageParser.Provider p = pkg.providers.get(i);
7212            mProviders.removeProvider(p);
7213            if (p.info.authority == null) {
7214
7215                /* There was another ContentProvider with this authority when
7216                 * this app was installed so this authority is null,
7217                 * Ignore it as we don't have to unregister the provider.
7218                 */
7219                continue;
7220            }
7221            String names[] = p.info.authority.split(";");
7222            for (int j = 0; j < names.length; j++) {
7223                if (mProvidersByAuthority.get(names[j]) == p) {
7224                    mProvidersByAuthority.remove(names[j]);
7225                    if (DEBUG_REMOVE) {
7226                        if (chatty)
7227                            Log.d(TAG, "Unregistered content provider: " + names[j]
7228                                    + ", className = " + p.info.name + ", isSyncable = "
7229                                    + p.info.isSyncable);
7230                    }
7231                }
7232            }
7233            if (DEBUG_REMOVE && chatty) {
7234                if (r == null) {
7235                    r = new StringBuilder(256);
7236                } else {
7237                    r.append(' ');
7238                }
7239                r.append(p.info.name);
7240            }
7241        }
7242        if (r != null) {
7243            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7244        }
7245
7246        N = pkg.services.size();
7247        r = null;
7248        for (i=0; i<N; i++) {
7249            PackageParser.Service s = pkg.services.get(i);
7250            mServices.removeService(s);
7251            if (chatty) {
7252                if (r == null) {
7253                    r = new StringBuilder(256);
7254                } else {
7255                    r.append(' ');
7256                }
7257                r.append(s.info.name);
7258            }
7259        }
7260        if (r != null) {
7261            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7262        }
7263
7264        N = pkg.receivers.size();
7265        r = null;
7266        for (i=0; i<N; i++) {
7267            PackageParser.Activity a = pkg.receivers.get(i);
7268            mReceivers.removeActivity(a, "receiver");
7269            if (DEBUG_REMOVE && chatty) {
7270                if (r == null) {
7271                    r = new StringBuilder(256);
7272                } else {
7273                    r.append(' ');
7274                }
7275                r.append(a.info.name);
7276            }
7277        }
7278        if (r != null) {
7279            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7280        }
7281
7282        N = pkg.activities.size();
7283        r = null;
7284        for (i=0; i<N; i++) {
7285            PackageParser.Activity a = pkg.activities.get(i);
7286            mActivities.removeActivity(a, "activity");
7287            if (DEBUG_REMOVE && chatty) {
7288                if (r == null) {
7289                    r = new StringBuilder(256);
7290                } else {
7291                    r.append(' ');
7292                }
7293                r.append(a.info.name);
7294            }
7295        }
7296        if (r != null) {
7297            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7298        }
7299
7300        N = pkg.permissions.size();
7301        r = null;
7302        for (i=0; i<N; i++) {
7303            PackageParser.Permission p = pkg.permissions.get(i);
7304            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7305            if (bp == null) {
7306                bp = mSettings.mPermissionTrees.get(p.info.name);
7307            }
7308            if (bp != null && bp.perm == p) {
7309                bp.perm = null;
7310                if (DEBUG_REMOVE && chatty) {
7311                    if (r == null) {
7312                        r = new StringBuilder(256);
7313                    } else {
7314                        r.append(' ');
7315                    }
7316                    r.append(p.info.name);
7317                }
7318            }
7319            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7320                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7321                if (appOpPerms != null) {
7322                    appOpPerms.remove(pkg.packageName);
7323                }
7324            }
7325        }
7326        if (r != null) {
7327            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7328        }
7329
7330        N = pkg.requestedPermissions.size();
7331        r = null;
7332        for (i=0; i<N; i++) {
7333            String perm = pkg.requestedPermissions.get(i);
7334            BasePermission bp = mSettings.mPermissions.get(perm);
7335            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7336                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7337                if (appOpPerms != null) {
7338                    appOpPerms.remove(pkg.packageName);
7339                    if (appOpPerms.isEmpty()) {
7340                        mAppOpPermissionPackages.remove(perm);
7341                    }
7342                }
7343            }
7344        }
7345        if (r != null) {
7346            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7347        }
7348
7349        N = pkg.instrumentation.size();
7350        r = null;
7351        for (i=0; i<N; i++) {
7352            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7353            mInstrumentation.remove(a.getComponentName());
7354            if (DEBUG_REMOVE && chatty) {
7355                if (r == null) {
7356                    r = new StringBuilder(256);
7357                } else {
7358                    r.append(' ');
7359                }
7360                r.append(a.info.name);
7361            }
7362        }
7363        if (r != null) {
7364            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7365        }
7366
7367        r = null;
7368        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7369            // Only system apps can hold shared libraries.
7370            if (pkg.libraryNames != null) {
7371                for (i=0; i<pkg.libraryNames.size(); i++) {
7372                    String name = pkg.libraryNames.get(i);
7373                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7374                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7375                        mSharedLibraries.remove(name);
7376                        if (DEBUG_REMOVE && chatty) {
7377                            if (r == null) {
7378                                r = new StringBuilder(256);
7379                            } else {
7380                                r.append(' ');
7381                            }
7382                            r.append(name);
7383                        }
7384                    }
7385                }
7386            }
7387        }
7388        if (r != null) {
7389            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7390        }
7391    }
7392
7393    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7394        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7395            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7396                return true;
7397            }
7398        }
7399        return false;
7400    }
7401
7402    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7403    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7404    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7405
7406    private void updatePermissionsLPw(String changingPkg,
7407            PackageParser.Package pkgInfo, int flags) {
7408        // Make sure there are no dangling permission trees.
7409        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7410        while (it.hasNext()) {
7411            final BasePermission bp = it.next();
7412            if (bp.packageSetting == null) {
7413                // We may not yet have parsed the package, so just see if
7414                // we still know about its settings.
7415                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7416            }
7417            if (bp.packageSetting == null) {
7418                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7419                        + " from package " + bp.sourcePackage);
7420                it.remove();
7421            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7422                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7423                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7424                            + " from package " + bp.sourcePackage);
7425                    flags |= UPDATE_PERMISSIONS_ALL;
7426                    it.remove();
7427                }
7428            }
7429        }
7430
7431        // Make sure all dynamic permissions have been assigned to a package,
7432        // and make sure there are no dangling permissions.
7433        it = mSettings.mPermissions.values().iterator();
7434        while (it.hasNext()) {
7435            final BasePermission bp = it.next();
7436            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7437                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7438                        + bp.name + " pkg=" + bp.sourcePackage
7439                        + " info=" + bp.pendingInfo);
7440                if (bp.packageSetting == null && bp.pendingInfo != null) {
7441                    final BasePermission tree = findPermissionTreeLP(bp.name);
7442                    if (tree != null && tree.perm != null) {
7443                        bp.packageSetting = tree.packageSetting;
7444                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7445                                new PermissionInfo(bp.pendingInfo));
7446                        bp.perm.info.packageName = tree.perm.info.packageName;
7447                        bp.perm.info.name = bp.name;
7448                        bp.uid = tree.uid;
7449                    }
7450                }
7451            }
7452            if (bp.packageSetting == null) {
7453                // We may not yet have parsed the package, so just see if
7454                // we still know about its settings.
7455                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7456            }
7457            if (bp.packageSetting == null) {
7458                Slog.w(TAG, "Removing dangling permission: " + bp.name
7459                        + " from package " + bp.sourcePackage);
7460                it.remove();
7461            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7462                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7463                    Slog.i(TAG, "Removing old permission: " + bp.name
7464                            + " from package " + bp.sourcePackage);
7465                    flags |= UPDATE_PERMISSIONS_ALL;
7466                    it.remove();
7467                }
7468            }
7469        }
7470
7471        // Now update the permissions for all packages, in particular
7472        // replace the granted permissions of the system packages.
7473        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7474            for (PackageParser.Package pkg : mPackages.values()) {
7475                if (pkg != pkgInfo) {
7476                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7477                            changingPkg);
7478                }
7479            }
7480        }
7481
7482        if (pkgInfo != null) {
7483            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7484        }
7485    }
7486
7487    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7488            String packageOfInterest) {
7489        // IMPORTANT: There are two types of permissions: install and runtime.
7490        // Install time permissions are granted when the app is installed to
7491        // all device users and users added in the future. Runtime permissions
7492        // are granted at runtime explicitly to specific users. Normal and signature
7493        // protected permissions are install time permissions. Dangerous permissions
7494        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7495        // otherwise they are runtime permissions. This function does not manage
7496        // runtime permissions except for the case an app targeting Lollipop MR1
7497        // being upgraded to target a newer SDK, in which case dangerous permissions
7498        // are transformed from install time to runtime ones.
7499
7500        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7501        if (ps == null) {
7502            return;
7503        }
7504
7505        PermissionsState permissionsState = ps.getPermissionsState();
7506        PermissionsState origPermissions = permissionsState;
7507
7508        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7509
7510        int[] upgradeUserIds = PermissionsState.USERS_NONE;
7511        int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE;
7512
7513        boolean changedInstallPermission = false;
7514
7515        if (replace) {
7516            ps.installPermissionsFixed = false;
7517            if (!ps.isSharedUser()) {
7518                origPermissions = new PermissionsState(permissionsState);
7519                permissionsState.reset();
7520            }
7521        }
7522
7523        permissionsState.setGlobalGids(mGlobalGids);
7524
7525        final int N = pkg.requestedPermissions.size();
7526        for (int i=0; i<N; i++) {
7527            final String name = pkg.requestedPermissions.get(i);
7528            final BasePermission bp = mSettings.mPermissions.get(name);
7529
7530            if (DEBUG_INSTALL) {
7531                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7532            }
7533
7534            if (bp == null || bp.packageSetting == null) {
7535                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7536                    Slog.w(TAG, "Unknown permission " + name
7537                            + " in package " + pkg.packageName);
7538                }
7539                continue;
7540            }
7541
7542            final String perm = bp.name;
7543            boolean allowedSig = false;
7544            int grant = GRANT_DENIED;
7545
7546            // Keep track of app op permissions.
7547            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7548                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7549                if (pkgs == null) {
7550                    pkgs = new ArraySet<>();
7551                    mAppOpPermissionPackages.put(bp.name, pkgs);
7552                }
7553                pkgs.add(pkg.packageName);
7554            }
7555
7556            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7557            switch (level) {
7558                case PermissionInfo.PROTECTION_NORMAL: {
7559                    // For all apps normal permissions are install time ones.
7560                    grant = GRANT_INSTALL;
7561                } break;
7562
7563                case PermissionInfo.PROTECTION_DANGEROUS: {
7564                    if (!RUNTIME_PERMISSIONS_ENABLED
7565                            || pkg.applicationInfo.targetSdkVersion
7566                                    <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7567                        // For legacy apps dangerous permissions are install time ones.
7568                        grant = GRANT_INSTALL;
7569                    } else if (ps.isSystem()) {
7570                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7571                        if (origPermissions.hasInstallPermission(bp.name)) {
7572                            // If a system app had an install permission, then the app was
7573                            // upgraded and we grant the permissions as runtime to all users.
7574                            grant = GRANT_UPGRADE;
7575                            upgradeUserIds = currentUserIds;
7576                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7577                            // If users changed since the last permissions update for a
7578                            // system app, we grant the permission as runtime to the new users.
7579                            grant = GRANT_UPGRADE;
7580                            upgradeUserIds = currentUserIds;
7581                            for (int userId : updatedUserIds) {
7582                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7583                            }
7584                        } else {
7585                            // Otherwise, we grant the permission as runtime if the app
7586                            // already had it, i.e. we preserve runtime permissions.
7587                            grant = GRANT_RUNTIME;
7588                        }
7589                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7590                        // For legacy apps that became modern, install becomes runtime.
7591                        grant = GRANT_UPGRADE;
7592                        upgradeUserIds = currentUserIds;
7593                    } else if (replace) {
7594                        // For upgraded modern apps keep runtime permissions unchanged.
7595                        grant = GRANT_RUNTIME;
7596                    }
7597                } break;
7598
7599                case PermissionInfo.PROTECTION_SIGNATURE: {
7600                    // For all apps signature permissions are install time ones.
7601                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7602                    if (allowedSig) {
7603                        grant = GRANT_INSTALL;
7604                    }
7605                } break;
7606            }
7607
7608            if (DEBUG_INSTALL) {
7609                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7610            }
7611
7612            if (grant != GRANT_DENIED) {
7613                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7614                    // If this is an existing, non-system package, then
7615                    // we can't add any new permissions to it.
7616                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7617                        // Except...  if this is a permission that was added
7618                        // to the platform (note: need to only do this when
7619                        // updating the platform).
7620                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7621                            grant = GRANT_DENIED;
7622                        }
7623                    }
7624                }
7625
7626                switch (grant) {
7627                    case GRANT_INSTALL: {
7628                        // Grant an install permission.
7629                        if (permissionsState.grantInstallPermission(bp) !=
7630                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7631                            changedInstallPermission = true;
7632                        }
7633                    } break;
7634
7635                    case GRANT_RUNTIME: {
7636                        // Grant previously granted runtime permissions.
7637                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7638                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7639                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7640                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7641                                    // If we cannot put the permission as it was, we have to write.
7642                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7643                                            changedRuntimePermissionUserIds, userId);
7644                                }
7645                            }
7646                        }
7647                    } break;
7648
7649                    case GRANT_UPGRADE: {
7650                        // Grant runtime permissions for a previously held install permission.
7651                        permissionsState.revokeInstallPermission(bp);
7652                        for (int userId : upgradeUserIds) {
7653                            if (permissionsState.grantRuntimePermission(bp, userId) !=
7654                                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
7655                                // If we granted the permission, we have to write.
7656                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7657                                        changedRuntimePermissionUserIds, userId);
7658                            }
7659                        }
7660                    } break;
7661
7662                    default: {
7663                        if (packageOfInterest == null
7664                                || packageOfInterest.equals(pkg.packageName)) {
7665                            Slog.w(TAG, "Not granting permission " + perm
7666                                    + " to package " + pkg.packageName
7667                                    + " because it was previously installed without");
7668                        }
7669                    } break;
7670                }
7671            } else {
7672                if (permissionsState.revokeInstallPermission(bp) !=
7673                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7674                    changedInstallPermission = true;
7675                    Slog.i(TAG, "Un-granting permission " + perm
7676                            + " from package " + pkg.packageName
7677                            + " (protectionLevel=" + bp.protectionLevel
7678                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7679                            + ")");
7680                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7681                    // Don't print warning for app op permissions, since it is fine for them
7682                    // not to be granted, there is a UI for the user to decide.
7683                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7684                        Slog.w(TAG, "Not granting permission " + perm
7685                                + " to package " + pkg.packageName
7686                                + " (protectionLevel=" + bp.protectionLevel
7687                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7688                                + ")");
7689                    }
7690                }
7691            }
7692        }
7693
7694        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7695                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7696            // This is the first that we have heard about this package, so the
7697            // permissions we have now selected are fixed until explicitly
7698            // changed.
7699            ps.installPermissionsFixed = true;
7700        }
7701
7702        ps.setPermissionsUpdatedForUserIds(currentUserIds);
7703
7704        // Persist the runtime permissions state for users with changes.
7705        if (RUNTIME_PERMISSIONS_ENABLED) {
7706            for (int userId : changedRuntimePermissionUserIds) {
7707                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
7708            }
7709        }
7710    }
7711
7712    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7713        boolean allowed = false;
7714        final int NP = PackageParser.NEW_PERMISSIONS.length;
7715        for (int ip=0; ip<NP; ip++) {
7716            final PackageParser.NewPermissionInfo npi
7717                    = PackageParser.NEW_PERMISSIONS[ip];
7718            if (npi.name.equals(perm)
7719                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7720                allowed = true;
7721                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7722                        + pkg.packageName);
7723                break;
7724            }
7725        }
7726        return allowed;
7727    }
7728
7729    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7730            BasePermission bp, PermissionsState origPermissions) {
7731        boolean allowed;
7732        allowed = (compareSignatures(
7733                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7734                        == PackageManager.SIGNATURE_MATCH)
7735                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7736                        == PackageManager.SIGNATURE_MATCH);
7737        if (!allowed && (bp.protectionLevel
7738                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7739            if (isSystemApp(pkg)) {
7740                // For updated system applications, a system permission
7741                // is granted only if it had been defined by the original application.
7742                if (pkg.isUpdatedSystemApp()) {
7743                    final PackageSetting sysPs = mSettings
7744                            .getDisabledSystemPkgLPr(pkg.packageName);
7745                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
7746                        // If the original was granted this permission, we take
7747                        // that grant decision as read and propagate it to the
7748                        // update.
7749                        if (sysPs.isPrivileged()) {
7750                            allowed = true;
7751                        }
7752                    } else {
7753                        // The system apk may have been updated with an older
7754                        // version of the one on the data partition, but which
7755                        // granted a new system permission that it didn't have
7756                        // before.  In this case we do want to allow the app to
7757                        // now get the new permission if the ancestral apk is
7758                        // privileged to get it.
7759                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7760                            for (int j=0;
7761                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7762                                if (perm.equals(
7763                                        sysPs.pkg.requestedPermissions.get(j))) {
7764                                    allowed = true;
7765                                    break;
7766                                }
7767                            }
7768                        }
7769                    }
7770                } else {
7771                    allowed = isPrivilegedApp(pkg);
7772                }
7773            }
7774        }
7775        if (!allowed && (bp.protectionLevel
7776                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7777            // For development permissions, a development permission
7778            // is granted only if it was already granted.
7779            allowed = origPermissions.hasInstallPermission(perm);
7780        }
7781        return allowed;
7782    }
7783
7784    final class ActivityIntentResolver
7785            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7786        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7787                boolean defaultOnly, int userId) {
7788            if (!sUserManager.exists(userId)) return null;
7789            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7790            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7791        }
7792
7793        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7794                int userId) {
7795            if (!sUserManager.exists(userId)) return null;
7796            mFlags = flags;
7797            return super.queryIntent(intent, resolvedType,
7798                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7799        }
7800
7801        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7802                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7803            if (!sUserManager.exists(userId)) return null;
7804            if (packageActivities == null) {
7805                return null;
7806            }
7807            mFlags = flags;
7808            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7809            final int N = packageActivities.size();
7810            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7811                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7812
7813            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7814            for (int i = 0; i < N; ++i) {
7815                intentFilters = packageActivities.get(i).intents;
7816                if (intentFilters != null && intentFilters.size() > 0) {
7817                    PackageParser.ActivityIntentInfo[] array =
7818                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7819                    intentFilters.toArray(array);
7820                    listCut.add(array);
7821                }
7822            }
7823            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7824        }
7825
7826        public final void addActivity(PackageParser.Activity a, String type) {
7827            final boolean systemApp = a.info.applicationInfo.isSystemApp();
7828            mActivities.put(a.getComponentName(), a);
7829            if (DEBUG_SHOW_INFO)
7830                Log.v(
7831                TAG, "  " + type + " " +
7832                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7833            if (DEBUG_SHOW_INFO)
7834                Log.v(TAG, "    Class=" + a.info.name);
7835            final int NI = a.intents.size();
7836            for (int j=0; j<NI; j++) {
7837                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7838                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7839                    intent.setPriority(0);
7840                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7841                            + a.className + " with priority > 0, forcing to 0");
7842                }
7843                if (DEBUG_SHOW_INFO) {
7844                    Log.v(TAG, "    IntentFilter:");
7845                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7846                }
7847                if (!intent.debugCheck()) {
7848                    Log.w(TAG, "==> For Activity " + a.info.name);
7849                }
7850                addFilter(intent);
7851            }
7852        }
7853
7854        public final void removeActivity(PackageParser.Activity a, String type) {
7855            mActivities.remove(a.getComponentName());
7856            if (DEBUG_SHOW_INFO) {
7857                Log.v(TAG, "  " + type + " "
7858                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7859                                : a.info.name) + ":");
7860                Log.v(TAG, "    Class=" + a.info.name);
7861            }
7862            final int NI = a.intents.size();
7863            for (int j=0; j<NI; j++) {
7864                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7865                if (DEBUG_SHOW_INFO) {
7866                    Log.v(TAG, "    IntentFilter:");
7867                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7868                }
7869                removeFilter(intent);
7870            }
7871        }
7872
7873        @Override
7874        protected boolean allowFilterResult(
7875                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7876            ActivityInfo filterAi = filter.activity.info;
7877            for (int i=dest.size()-1; i>=0; i--) {
7878                ActivityInfo destAi = dest.get(i).activityInfo;
7879                if (destAi.name == filterAi.name
7880                        && destAi.packageName == filterAi.packageName) {
7881                    return false;
7882                }
7883            }
7884            return true;
7885        }
7886
7887        @Override
7888        protected ActivityIntentInfo[] newArray(int size) {
7889            return new ActivityIntentInfo[size];
7890        }
7891
7892        @Override
7893        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7894            if (!sUserManager.exists(userId)) return true;
7895            PackageParser.Package p = filter.activity.owner;
7896            if (p != null) {
7897                PackageSetting ps = (PackageSetting)p.mExtras;
7898                if (ps != null) {
7899                    // System apps are never considered stopped for purposes of
7900                    // filtering, because there may be no way for the user to
7901                    // actually re-launch them.
7902                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7903                            && ps.getStopped(userId);
7904                }
7905            }
7906            return false;
7907        }
7908
7909        @Override
7910        protected boolean isPackageForFilter(String packageName,
7911                PackageParser.ActivityIntentInfo info) {
7912            return packageName.equals(info.activity.owner.packageName);
7913        }
7914
7915        @Override
7916        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7917                int match, int userId) {
7918            if (!sUserManager.exists(userId)) return null;
7919            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7920                return null;
7921            }
7922            final PackageParser.Activity activity = info.activity;
7923            if (mSafeMode && (activity.info.applicationInfo.flags
7924                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7925                return null;
7926            }
7927            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7928            if (ps == null) {
7929                return null;
7930            }
7931            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7932                    ps.readUserState(userId), userId);
7933            if (ai == null) {
7934                return null;
7935            }
7936            final ResolveInfo res = new ResolveInfo();
7937            res.activityInfo = ai;
7938            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7939                res.filter = info;
7940            }
7941            if (info != null) {
7942                res.handleAllWebDataURI = info.handleAllWebDataURI();
7943            }
7944            res.priority = info.getPriority();
7945            res.preferredOrder = activity.owner.mPreferredOrder;
7946            //System.out.println("Result: " + res.activityInfo.className +
7947            //                   " = " + res.priority);
7948            res.match = match;
7949            res.isDefault = info.hasDefault;
7950            res.labelRes = info.labelRes;
7951            res.nonLocalizedLabel = info.nonLocalizedLabel;
7952            if (userNeedsBadging(userId)) {
7953                res.noResourceId = true;
7954            } else {
7955                res.icon = info.icon;
7956            }
7957            res.system = res.activityInfo.applicationInfo.isSystemApp();
7958            return res;
7959        }
7960
7961        @Override
7962        protected void sortResults(List<ResolveInfo> results) {
7963            Collections.sort(results, mResolvePrioritySorter);
7964        }
7965
7966        @Override
7967        protected void dumpFilter(PrintWriter out, String prefix,
7968                PackageParser.ActivityIntentInfo filter) {
7969            out.print(prefix); out.print(
7970                    Integer.toHexString(System.identityHashCode(filter.activity)));
7971                    out.print(' ');
7972                    filter.activity.printComponentShortName(out);
7973                    out.print(" filter ");
7974                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7975        }
7976
7977        @Override
7978        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
7979            return filter.activity;
7980        }
7981
7982        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7983            PackageParser.Activity activity = (PackageParser.Activity)label;
7984            out.print(prefix); out.print(
7985                    Integer.toHexString(System.identityHashCode(activity)));
7986                    out.print(' ');
7987                    activity.printComponentShortName(out);
7988            if (count > 1) {
7989                out.print(" ("); out.print(count); out.print(" filters)");
7990            }
7991            out.println();
7992        }
7993
7994//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7995//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7996//            final List<ResolveInfo> retList = Lists.newArrayList();
7997//            while (i.hasNext()) {
7998//                final ResolveInfo resolveInfo = i.next();
7999//                if (isEnabledLP(resolveInfo.activityInfo)) {
8000//                    retList.add(resolveInfo);
8001//                }
8002//            }
8003//            return retList;
8004//        }
8005
8006        // Keys are String (activity class name), values are Activity.
8007        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8008                = new ArrayMap<ComponentName, PackageParser.Activity>();
8009        private int mFlags;
8010    }
8011
8012    private final class ServiceIntentResolver
8013            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8014        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8015                boolean defaultOnly, int userId) {
8016            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8017            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8018        }
8019
8020        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8021                int userId) {
8022            if (!sUserManager.exists(userId)) return null;
8023            mFlags = flags;
8024            return super.queryIntent(intent, resolvedType,
8025                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8026        }
8027
8028        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8029                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8030            if (!sUserManager.exists(userId)) return null;
8031            if (packageServices == null) {
8032                return null;
8033            }
8034            mFlags = flags;
8035            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8036            final int N = packageServices.size();
8037            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8038                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8039
8040            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8041            for (int i = 0; i < N; ++i) {
8042                intentFilters = packageServices.get(i).intents;
8043                if (intentFilters != null && intentFilters.size() > 0) {
8044                    PackageParser.ServiceIntentInfo[] array =
8045                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8046                    intentFilters.toArray(array);
8047                    listCut.add(array);
8048                }
8049            }
8050            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8051        }
8052
8053        public final void addService(PackageParser.Service s) {
8054            mServices.put(s.getComponentName(), s);
8055            if (DEBUG_SHOW_INFO) {
8056                Log.v(TAG, "  "
8057                        + (s.info.nonLocalizedLabel != null
8058                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8059                Log.v(TAG, "    Class=" + s.info.name);
8060            }
8061            final int NI = s.intents.size();
8062            int j;
8063            for (j=0; j<NI; j++) {
8064                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8065                if (DEBUG_SHOW_INFO) {
8066                    Log.v(TAG, "    IntentFilter:");
8067                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8068                }
8069                if (!intent.debugCheck()) {
8070                    Log.w(TAG, "==> For Service " + s.info.name);
8071                }
8072                addFilter(intent);
8073            }
8074        }
8075
8076        public final void removeService(PackageParser.Service s) {
8077            mServices.remove(s.getComponentName());
8078            if (DEBUG_SHOW_INFO) {
8079                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8080                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8081                Log.v(TAG, "    Class=" + s.info.name);
8082            }
8083            final int NI = s.intents.size();
8084            int j;
8085            for (j=0; j<NI; j++) {
8086                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8087                if (DEBUG_SHOW_INFO) {
8088                    Log.v(TAG, "    IntentFilter:");
8089                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8090                }
8091                removeFilter(intent);
8092            }
8093        }
8094
8095        @Override
8096        protected boolean allowFilterResult(
8097                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8098            ServiceInfo filterSi = filter.service.info;
8099            for (int i=dest.size()-1; i>=0; i--) {
8100                ServiceInfo destAi = dest.get(i).serviceInfo;
8101                if (destAi.name == filterSi.name
8102                        && destAi.packageName == filterSi.packageName) {
8103                    return false;
8104                }
8105            }
8106            return true;
8107        }
8108
8109        @Override
8110        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8111            return new PackageParser.ServiceIntentInfo[size];
8112        }
8113
8114        @Override
8115        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8116            if (!sUserManager.exists(userId)) return true;
8117            PackageParser.Package p = filter.service.owner;
8118            if (p != null) {
8119                PackageSetting ps = (PackageSetting)p.mExtras;
8120                if (ps != null) {
8121                    // System apps are never considered stopped for purposes of
8122                    // filtering, because there may be no way for the user to
8123                    // actually re-launch them.
8124                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8125                            && ps.getStopped(userId);
8126                }
8127            }
8128            return false;
8129        }
8130
8131        @Override
8132        protected boolean isPackageForFilter(String packageName,
8133                PackageParser.ServiceIntentInfo info) {
8134            return packageName.equals(info.service.owner.packageName);
8135        }
8136
8137        @Override
8138        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8139                int match, int userId) {
8140            if (!sUserManager.exists(userId)) return null;
8141            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8142            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8143                return null;
8144            }
8145            final PackageParser.Service service = info.service;
8146            if (mSafeMode && (service.info.applicationInfo.flags
8147                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8148                return null;
8149            }
8150            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8151            if (ps == null) {
8152                return null;
8153            }
8154            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8155                    ps.readUserState(userId), userId);
8156            if (si == null) {
8157                return null;
8158            }
8159            final ResolveInfo res = new ResolveInfo();
8160            res.serviceInfo = si;
8161            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8162                res.filter = filter;
8163            }
8164            res.priority = info.getPriority();
8165            res.preferredOrder = service.owner.mPreferredOrder;
8166            res.match = match;
8167            res.isDefault = info.hasDefault;
8168            res.labelRes = info.labelRes;
8169            res.nonLocalizedLabel = info.nonLocalizedLabel;
8170            res.icon = info.icon;
8171            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8172            return res;
8173        }
8174
8175        @Override
8176        protected void sortResults(List<ResolveInfo> results) {
8177            Collections.sort(results, mResolvePrioritySorter);
8178        }
8179
8180        @Override
8181        protected void dumpFilter(PrintWriter out, String prefix,
8182                PackageParser.ServiceIntentInfo filter) {
8183            out.print(prefix); out.print(
8184                    Integer.toHexString(System.identityHashCode(filter.service)));
8185                    out.print(' ');
8186                    filter.service.printComponentShortName(out);
8187                    out.print(" filter ");
8188                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8189        }
8190
8191        @Override
8192        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8193            return filter.service;
8194        }
8195
8196        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8197            PackageParser.Service service = (PackageParser.Service)label;
8198            out.print(prefix); out.print(
8199                    Integer.toHexString(System.identityHashCode(service)));
8200                    out.print(' ');
8201                    service.printComponentShortName(out);
8202            if (count > 1) {
8203                out.print(" ("); out.print(count); out.print(" filters)");
8204            }
8205            out.println();
8206        }
8207
8208//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8209//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8210//            final List<ResolveInfo> retList = Lists.newArrayList();
8211//            while (i.hasNext()) {
8212//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8213//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8214//                    retList.add(resolveInfo);
8215//                }
8216//            }
8217//            return retList;
8218//        }
8219
8220        // Keys are String (activity class name), values are Activity.
8221        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8222                = new ArrayMap<ComponentName, PackageParser.Service>();
8223        private int mFlags;
8224    };
8225
8226    private final class ProviderIntentResolver
8227            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8228        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8229                boolean defaultOnly, int userId) {
8230            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8231            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8232        }
8233
8234        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8235                int userId) {
8236            if (!sUserManager.exists(userId))
8237                return null;
8238            mFlags = flags;
8239            return super.queryIntent(intent, resolvedType,
8240                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8241        }
8242
8243        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8244                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8245            if (!sUserManager.exists(userId))
8246                return null;
8247            if (packageProviders == null) {
8248                return null;
8249            }
8250            mFlags = flags;
8251            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8252            final int N = packageProviders.size();
8253            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8254                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8255
8256            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8257            for (int i = 0; i < N; ++i) {
8258                intentFilters = packageProviders.get(i).intents;
8259                if (intentFilters != null && intentFilters.size() > 0) {
8260                    PackageParser.ProviderIntentInfo[] array =
8261                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8262                    intentFilters.toArray(array);
8263                    listCut.add(array);
8264                }
8265            }
8266            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8267        }
8268
8269        public final void addProvider(PackageParser.Provider p) {
8270            if (mProviders.containsKey(p.getComponentName())) {
8271                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8272                return;
8273            }
8274
8275            mProviders.put(p.getComponentName(), p);
8276            if (DEBUG_SHOW_INFO) {
8277                Log.v(TAG, "  "
8278                        + (p.info.nonLocalizedLabel != null
8279                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8280                Log.v(TAG, "    Class=" + p.info.name);
8281            }
8282            final int NI = p.intents.size();
8283            int j;
8284            for (j = 0; j < NI; j++) {
8285                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8286                if (DEBUG_SHOW_INFO) {
8287                    Log.v(TAG, "    IntentFilter:");
8288                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8289                }
8290                if (!intent.debugCheck()) {
8291                    Log.w(TAG, "==> For Provider " + p.info.name);
8292                }
8293                addFilter(intent);
8294            }
8295        }
8296
8297        public final void removeProvider(PackageParser.Provider p) {
8298            mProviders.remove(p.getComponentName());
8299            if (DEBUG_SHOW_INFO) {
8300                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8301                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8302                Log.v(TAG, "    Class=" + p.info.name);
8303            }
8304            final int NI = p.intents.size();
8305            int j;
8306            for (j = 0; j < NI; j++) {
8307                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8308                if (DEBUG_SHOW_INFO) {
8309                    Log.v(TAG, "    IntentFilter:");
8310                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8311                }
8312                removeFilter(intent);
8313            }
8314        }
8315
8316        @Override
8317        protected boolean allowFilterResult(
8318                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8319            ProviderInfo filterPi = filter.provider.info;
8320            for (int i = dest.size() - 1; i >= 0; i--) {
8321                ProviderInfo destPi = dest.get(i).providerInfo;
8322                if (destPi.name == filterPi.name
8323                        && destPi.packageName == filterPi.packageName) {
8324                    return false;
8325                }
8326            }
8327            return true;
8328        }
8329
8330        @Override
8331        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8332            return new PackageParser.ProviderIntentInfo[size];
8333        }
8334
8335        @Override
8336        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8337            if (!sUserManager.exists(userId))
8338                return true;
8339            PackageParser.Package p = filter.provider.owner;
8340            if (p != null) {
8341                PackageSetting ps = (PackageSetting) p.mExtras;
8342                if (ps != null) {
8343                    // System apps are never considered stopped for purposes of
8344                    // filtering, because there may be no way for the user to
8345                    // actually re-launch them.
8346                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8347                            && ps.getStopped(userId);
8348                }
8349            }
8350            return false;
8351        }
8352
8353        @Override
8354        protected boolean isPackageForFilter(String packageName,
8355                PackageParser.ProviderIntentInfo info) {
8356            return packageName.equals(info.provider.owner.packageName);
8357        }
8358
8359        @Override
8360        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8361                int match, int userId) {
8362            if (!sUserManager.exists(userId))
8363                return null;
8364            final PackageParser.ProviderIntentInfo info = filter;
8365            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8366                return null;
8367            }
8368            final PackageParser.Provider provider = info.provider;
8369            if (mSafeMode && (provider.info.applicationInfo.flags
8370                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8371                return null;
8372            }
8373            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8374            if (ps == null) {
8375                return null;
8376            }
8377            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8378                    ps.readUserState(userId), userId);
8379            if (pi == null) {
8380                return null;
8381            }
8382            final ResolveInfo res = new ResolveInfo();
8383            res.providerInfo = pi;
8384            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8385                res.filter = filter;
8386            }
8387            res.priority = info.getPriority();
8388            res.preferredOrder = provider.owner.mPreferredOrder;
8389            res.match = match;
8390            res.isDefault = info.hasDefault;
8391            res.labelRes = info.labelRes;
8392            res.nonLocalizedLabel = info.nonLocalizedLabel;
8393            res.icon = info.icon;
8394            res.system = res.providerInfo.applicationInfo.isSystemApp();
8395            return res;
8396        }
8397
8398        @Override
8399        protected void sortResults(List<ResolveInfo> results) {
8400            Collections.sort(results, mResolvePrioritySorter);
8401        }
8402
8403        @Override
8404        protected void dumpFilter(PrintWriter out, String prefix,
8405                PackageParser.ProviderIntentInfo filter) {
8406            out.print(prefix);
8407            out.print(
8408                    Integer.toHexString(System.identityHashCode(filter.provider)));
8409            out.print(' ');
8410            filter.provider.printComponentShortName(out);
8411            out.print(" filter ");
8412            out.println(Integer.toHexString(System.identityHashCode(filter)));
8413        }
8414
8415        @Override
8416        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8417            return filter.provider;
8418        }
8419
8420        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8421            PackageParser.Provider provider = (PackageParser.Provider)label;
8422            out.print(prefix); out.print(
8423                    Integer.toHexString(System.identityHashCode(provider)));
8424                    out.print(' ');
8425                    provider.printComponentShortName(out);
8426            if (count > 1) {
8427                out.print(" ("); out.print(count); out.print(" filters)");
8428            }
8429            out.println();
8430        }
8431
8432        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8433                = new ArrayMap<ComponentName, PackageParser.Provider>();
8434        private int mFlags;
8435    };
8436
8437    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8438            new Comparator<ResolveInfo>() {
8439        public int compare(ResolveInfo r1, ResolveInfo r2) {
8440            int v1 = r1.priority;
8441            int v2 = r2.priority;
8442            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8443            if (v1 != v2) {
8444                return (v1 > v2) ? -1 : 1;
8445            }
8446            v1 = r1.preferredOrder;
8447            v2 = r2.preferredOrder;
8448            if (v1 != v2) {
8449                return (v1 > v2) ? -1 : 1;
8450            }
8451            if (r1.isDefault != r2.isDefault) {
8452                return r1.isDefault ? -1 : 1;
8453            }
8454            v1 = r1.match;
8455            v2 = r2.match;
8456            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8457            if (v1 != v2) {
8458                return (v1 > v2) ? -1 : 1;
8459            }
8460            if (r1.system != r2.system) {
8461                return r1.system ? -1 : 1;
8462            }
8463            return 0;
8464        }
8465    };
8466
8467    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8468            new Comparator<ProviderInfo>() {
8469        public int compare(ProviderInfo p1, ProviderInfo p2) {
8470            final int v1 = p1.initOrder;
8471            final int v2 = p2.initOrder;
8472            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8473        }
8474    };
8475
8476    static final void sendPackageBroadcast(String action, String pkg,
8477            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
8478            int[] userIds) {
8479        IActivityManager am = ActivityManagerNative.getDefault();
8480        if (am != null) {
8481            try {
8482                if (userIds == null) {
8483                    userIds = am.getRunningUserIds();
8484                }
8485                for (int id : userIds) {
8486                    final Intent intent = new Intent(action,
8487                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
8488                    if (extras != null) {
8489                        intent.putExtras(extras);
8490                    }
8491                    if (targetPkg != null) {
8492                        intent.setPackage(targetPkg);
8493                    }
8494                    // Modify the UID when posting to other users
8495                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8496                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
8497                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8498                        intent.putExtra(Intent.EXTRA_UID, uid);
8499                    }
8500                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8501                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8502                    if (DEBUG_BROADCASTS) {
8503                        RuntimeException here = new RuntimeException("here");
8504                        here.fillInStackTrace();
8505                        Slog.d(TAG, "Sending to user " + id + ": "
8506                                + intent.toShortString(false, true, false, false)
8507                                + " " + intent.getExtras(), here);
8508                    }
8509                    am.broadcastIntent(null, intent, null, finishedReceiver,
8510                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
8511                            finishedReceiver != null, false, id);
8512                }
8513            } catch (RemoteException ex) {
8514            }
8515        }
8516    }
8517
8518    /**
8519     * Check if the external storage media is available. This is true if there
8520     * is a mounted external storage medium or if the external storage is
8521     * emulated.
8522     */
8523    private boolean isExternalMediaAvailable() {
8524        return mMediaMounted || Environment.isExternalStorageEmulated();
8525    }
8526
8527    @Override
8528    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8529        // writer
8530        synchronized (mPackages) {
8531            if (!isExternalMediaAvailable()) {
8532                // If the external storage is no longer mounted at this point,
8533                // the caller may not have been able to delete all of this
8534                // packages files and can not delete any more.  Bail.
8535                return null;
8536            }
8537            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8538            if (lastPackage != null) {
8539                pkgs.remove(lastPackage);
8540            }
8541            if (pkgs.size() > 0) {
8542                return pkgs.get(0);
8543            }
8544        }
8545        return null;
8546    }
8547
8548    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8549        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8550                userId, andCode ? 1 : 0, packageName);
8551        if (mSystemReady) {
8552            msg.sendToTarget();
8553        } else {
8554            if (mPostSystemReadyMessages == null) {
8555                mPostSystemReadyMessages = new ArrayList<>();
8556            }
8557            mPostSystemReadyMessages.add(msg);
8558        }
8559    }
8560
8561    void startCleaningPackages() {
8562        // reader
8563        synchronized (mPackages) {
8564            if (!isExternalMediaAvailable()) {
8565                return;
8566            }
8567            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8568                return;
8569            }
8570        }
8571        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8572        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8573        IActivityManager am = ActivityManagerNative.getDefault();
8574        if (am != null) {
8575            try {
8576                am.startService(null, intent, null, UserHandle.USER_OWNER);
8577            } catch (RemoteException e) {
8578            }
8579        }
8580    }
8581
8582    @Override
8583    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8584            int installFlags, String installerPackageName, VerificationParams verificationParams,
8585            String packageAbiOverride) {
8586        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8587                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8588    }
8589
8590    @Override
8591    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8592            int installFlags, String installerPackageName, VerificationParams verificationParams,
8593            String packageAbiOverride, int userId) {
8594        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8595
8596        final int callingUid = Binder.getCallingUid();
8597        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8598
8599        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8600            try {
8601                if (observer != null) {
8602                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8603                }
8604            } catch (RemoteException re) {
8605            }
8606            return;
8607        }
8608
8609        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8610            installFlags |= PackageManager.INSTALL_FROM_ADB;
8611
8612        } else {
8613            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8614            // about installerPackageName.
8615
8616            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8617            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8618        }
8619
8620        UserHandle user;
8621        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8622            user = UserHandle.ALL;
8623        } else {
8624            user = new UserHandle(userId);
8625        }
8626
8627        verificationParams.setInstallerUid(callingUid);
8628
8629        final File originFile = new File(originPath);
8630        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8631
8632        final Message msg = mHandler.obtainMessage(INIT_COPY);
8633        msg.obj = new InstallParams(origin, observer, installFlags,
8634                installerPackageName, null, verificationParams, user, packageAbiOverride);
8635        mHandler.sendMessage(msg);
8636    }
8637
8638    void installStage(String packageName, File stagedDir, String stagedCid,
8639            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8640            String installerPackageName, int installerUid, UserHandle user) {
8641        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8642                params.referrerUri, installerUid, null);
8643
8644        final OriginInfo origin;
8645        if (stagedDir != null) {
8646            origin = OriginInfo.fromStagedFile(stagedDir);
8647        } else {
8648            origin = OriginInfo.fromStagedContainer(stagedCid);
8649        }
8650
8651        final Message msg = mHandler.obtainMessage(INIT_COPY);
8652        msg.obj = new InstallParams(origin, observer, params.installFlags,
8653                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8654        mHandler.sendMessage(msg);
8655    }
8656
8657    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8658        Bundle extras = new Bundle(1);
8659        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8660
8661        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8662                packageName, extras, null, null, new int[] {userId});
8663        try {
8664            IActivityManager am = ActivityManagerNative.getDefault();
8665            final boolean isSystem =
8666                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8667            if (isSystem && am.isUserRunning(userId, false)) {
8668                // The just-installed/enabled app is bundled on the system, so presumed
8669                // to be able to run automatically without needing an explicit launch.
8670                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8671                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8672                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8673                        .setPackage(packageName);
8674                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8675                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8676            }
8677        } catch (RemoteException e) {
8678            // shouldn't happen
8679            Slog.w(TAG, "Unable to bootstrap installed package", e);
8680        }
8681    }
8682
8683    @Override
8684    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8685            int userId) {
8686        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8687        PackageSetting pkgSetting;
8688        final int uid = Binder.getCallingUid();
8689        enforceCrossUserPermission(uid, userId, true, true,
8690                "setApplicationHiddenSetting for user " + userId);
8691
8692        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8693            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8694            return false;
8695        }
8696
8697        long callingId = Binder.clearCallingIdentity();
8698        try {
8699            boolean sendAdded = false;
8700            boolean sendRemoved = false;
8701            // writer
8702            synchronized (mPackages) {
8703                pkgSetting = mSettings.mPackages.get(packageName);
8704                if (pkgSetting == null) {
8705                    return false;
8706                }
8707                if (pkgSetting.getHidden(userId) != hidden) {
8708                    pkgSetting.setHidden(hidden, userId);
8709                    mSettings.writePackageRestrictionsLPr(userId);
8710                    if (hidden) {
8711                        sendRemoved = true;
8712                    } else {
8713                        sendAdded = true;
8714                    }
8715                }
8716            }
8717            if (sendAdded) {
8718                sendPackageAddedForUser(packageName, pkgSetting, userId);
8719                return true;
8720            }
8721            if (sendRemoved) {
8722                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8723                        "hiding pkg");
8724                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8725            }
8726        } finally {
8727            Binder.restoreCallingIdentity(callingId);
8728        }
8729        return false;
8730    }
8731
8732    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8733            int userId) {
8734        final PackageRemovedInfo info = new PackageRemovedInfo();
8735        info.removedPackage = packageName;
8736        info.removedUsers = new int[] {userId};
8737        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8738        info.sendBroadcast(false, false, false);
8739    }
8740
8741    /**
8742     * Returns true if application is not found or there was an error. Otherwise it returns
8743     * the hidden state of the package for the given user.
8744     */
8745    @Override
8746    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8747        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8748        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8749                false, "getApplicationHidden for user " + userId);
8750        PackageSetting pkgSetting;
8751        long callingId = Binder.clearCallingIdentity();
8752        try {
8753            // writer
8754            synchronized (mPackages) {
8755                pkgSetting = mSettings.mPackages.get(packageName);
8756                if (pkgSetting == null) {
8757                    return true;
8758                }
8759                return pkgSetting.getHidden(userId);
8760            }
8761        } finally {
8762            Binder.restoreCallingIdentity(callingId);
8763        }
8764    }
8765
8766    /**
8767     * @hide
8768     */
8769    @Override
8770    public int installExistingPackageAsUser(String packageName, int userId) {
8771        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8772                null);
8773        PackageSetting pkgSetting;
8774        final int uid = Binder.getCallingUid();
8775        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8776                + userId);
8777        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8778            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8779        }
8780
8781        long callingId = Binder.clearCallingIdentity();
8782        try {
8783            boolean sendAdded = false;
8784            Bundle extras = new Bundle(1);
8785
8786            // writer
8787            synchronized (mPackages) {
8788                pkgSetting = mSettings.mPackages.get(packageName);
8789                if (pkgSetting == null) {
8790                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8791                }
8792                if (!pkgSetting.getInstalled(userId)) {
8793                    pkgSetting.setInstalled(true, userId);
8794                    pkgSetting.setHidden(false, userId);
8795                    mSettings.writePackageRestrictionsLPr(userId);
8796                    sendAdded = true;
8797                }
8798            }
8799
8800            if (sendAdded) {
8801                sendPackageAddedForUser(packageName, pkgSetting, userId);
8802            }
8803        } finally {
8804            Binder.restoreCallingIdentity(callingId);
8805        }
8806
8807        return PackageManager.INSTALL_SUCCEEDED;
8808    }
8809
8810    boolean isUserRestricted(int userId, String restrictionKey) {
8811        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8812        if (restrictions.getBoolean(restrictionKey, false)) {
8813            Log.w(TAG, "User is restricted: " + restrictionKey);
8814            return true;
8815        }
8816        return false;
8817    }
8818
8819    @Override
8820    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8821        mContext.enforceCallingOrSelfPermission(
8822                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8823                "Only package verification agents can verify applications");
8824
8825        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8826        final PackageVerificationResponse response = new PackageVerificationResponse(
8827                verificationCode, Binder.getCallingUid());
8828        msg.arg1 = id;
8829        msg.obj = response;
8830        mHandler.sendMessage(msg);
8831    }
8832
8833    @Override
8834    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8835            long millisecondsToDelay) {
8836        mContext.enforceCallingOrSelfPermission(
8837                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8838                "Only package verification agents can extend verification timeouts");
8839
8840        final PackageVerificationState state = mPendingVerification.get(id);
8841        final PackageVerificationResponse response = new PackageVerificationResponse(
8842                verificationCodeAtTimeout, Binder.getCallingUid());
8843
8844        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8845            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8846        }
8847        if (millisecondsToDelay < 0) {
8848            millisecondsToDelay = 0;
8849        }
8850        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8851                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8852            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8853        }
8854
8855        if ((state != null) && !state.timeoutExtended()) {
8856            state.extendTimeout();
8857
8858            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8859            msg.arg1 = id;
8860            msg.obj = response;
8861            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8862        }
8863    }
8864
8865    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8866            int verificationCode, UserHandle user) {
8867        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8868        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8869        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8870        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8871        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8872
8873        mContext.sendBroadcastAsUser(intent, user,
8874                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8875    }
8876
8877    private ComponentName matchComponentForVerifier(String packageName,
8878            List<ResolveInfo> receivers) {
8879        ActivityInfo targetReceiver = null;
8880
8881        final int NR = receivers.size();
8882        for (int i = 0; i < NR; i++) {
8883            final ResolveInfo info = receivers.get(i);
8884            if (info.activityInfo == null) {
8885                continue;
8886            }
8887
8888            if (packageName.equals(info.activityInfo.packageName)) {
8889                targetReceiver = info.activityInfo;
8890                break;
8891            }
8892        }
8893
8894        if (targetReceiver == null) {
8895            return null;
8896        }
8897
8898        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8899    }
8900
8901    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8902            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8903        if (pkgInfo.verifiers.length == 0) {
8904            return null;
8905        }
8906
8907        final int N = pkgInfo.verifiers.length;
8908        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8909        for (int i = 0; i < N; i++) {
8910            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8911
8912            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8913                    receivers);
8914            if (comp == null) {
8915                continue;
8916            }
8917
8918            final int verifierUid = getUidForVerifier(verifierInfo);
8919            if (verifierUid == -1) {
8920                continue;
8921            }
8922
8923            if (DEBUG_VERIFY) {
8924                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8925                        + " with the correct signature");
8926            }
8927            sufficientVerifiers.add(comp);
8928            verificationState.addSufficientVerifier(verifierUid);
8929        }
8930
8931        return sufficientVerifiers;
8932    }
8933
8934    private int getUidForVerifier(VerifierInfo verifierInfo) {
8935        synchronized (mPackages) {
8936            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8937            if (pkg == null) {
8938                return -1;
8939            } else if (pkg.mSignatures.length != 1) {
8940                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8941                        + " has more than one signature; ignoring");
8942                return -1;
8943            }
8944
8945            /*
8946             * If the public key of the package's signature does not match
8947             * our expected public key, then this is a different package and
8948             * we should skip.
8949             */
8950
8951            final byte[] expectedPublicKey;
8952            try {
8953                final Signature verifierSig = pkg.mSignatures[0];
8954                final PublicKey publicKey = verifierSig.getPublicKey();
8955                expectedPublicKey = publicKey.getEncoded();
8956            } catch (CertificateException e) {
8957                return -1;
8958            }
8959
8960            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8961
8962            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8963                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8964                        + " does not have the expected public key; ignoring");
8965                return -1;
8966            }
8967
8968            return pkg.applicationInfo.uid;
8969        }
8970    }
8971
8972    @Override
8973    public void finishPackageInstall(int token) {
8974        enforceSystemOrRoot("Only the system is allowed to finish installs");
8975
8976        if (DEBUG_INSTALL) {
8977            Slog.v(TAG, "BM finishing package install for " + token);
8978        }
8979
8980        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8981        mHandler.sendMessage(msg);
8982    }
8983
8984    /**
8985     * Get the verification agent timeout.
8986     *
8987     * @return verification timeout in milliseconds
8988     */
8989    private long getVerificationTimeout() {
8990        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8991                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8992                DEFAULT_VERIFICATION_TIMEOUT);
8993    }
8994
8995    /**
8996     * Get the default verification agent response code.
8997     *
8998     * @return default verification response code
8999     */
9000    private int getDefaultVerificationResponse() {
9001        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9002                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9003                DEFAULT_VERIFICATION_RESPONSE);
9004    }
9005
9006    /**
9007     * Check whether or not package verification has been enabled.
9008     *
9009     * @return true if verification should be performed
9010     */
9011    private boolean isVerificationEnabled(int userId, int installFlags) {
9012        if (!DEFAULT_VERIFY_ENABLE) {
9013            return false;
9014        }
9015
9016        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9017
9018        // Check if installing from ADB
9019        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9020            // Do not run verification in a test harness environment
9021            if (ActivityManager.isRunningInTestHarness()) {
9022                return false;
9023            }
9024            if (ensureVerifyAppsEnabled) {
9025                return true;
9026            }
9027            // Check if the developer does not want package verification for ADB installs
9028            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9029                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9030                return false;
9031            }
9032        }
9033
9034        if (ensureVerifyAppsEnabled) {
9035            return true;
9036        }
9037
9038        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9039                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9040    }
9041
9042    @Override
9043    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9044            throws RemoteException {
9045        mContext.enforceCallingOrSelfPermission(
9046                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9047                "Only intentfilter verification agents can verify applications");
9048
9049        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9050        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9051                Binder.getCallingUid(), verificationCode, failedDomains);
9052        msg.arg1 = id;
9053        msg.obj = response;
9054        mHandler.sendMessage(msg);
9055    }
9056
9057    @Override
9058    public int getIntentVerificationStatus(String packageName, int userId) {
9059        synchronized (mPackages) {
9060            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9061        }
9062    }
9063
9064    @Override
9065    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9066        boolean result = false;
9067        synchronized (mPackages) {
9068            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9069        }
9070        scheduleWritePackageRestrictionsLocked(userId);
9071        return result;
9072    }
9073
9074    @Override
9075    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9076        synchronized (mPackages) {
9077            return mSettings.getIntentFilterVerificationsLPr(packageName);
9078        }
9079    }
9080
9081    @Override
9082    public List<IntentFilter> getAllIntentFilters(String packageName) {
9083        if (TextUtils.isEmpty(packageName)) {
9084            return Collections.<IntentFilter>emptyList();
9085        }
9086        synchronized (mPackages) {
9087            PackageParser.Package pkg = mPackages.get(packageName);
9088            if (pkg == null || pkg.activities == null) {
9089                return Collections.<IntentFilter>emptyList();
9090            }
9091            final int count = pkg.activities.size();
9092            ArrayList<IntentFilter> result = new ArrayList<>();
9093            for (int n=0; n<count; n++) {
9094                PackageParser.Activity activity = pkg.activities.get(n);
9095                if (activity.intents != null || activity.intents.size() > 0) {
9096                    result.addAll(activity.intents);
9097                }
9098            }
9099            return result;
9100        }
9101    }
9102
9103    /**
9104     * Get the "allow unknown sources" setting.
9105     *
9106     * @return the current "allow unknown sources" setting
9107     */
9108    private int getUnknownSourcesSettings() {
9109        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9110                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9111                -1);
9112    }
9113
9114    @Override
9115    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9116        final int uid = Binder.getCallingUid();
9117        // writer
9118        synchronized (mPackages) {
9119            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9120            if (targetPackageSetting == null) {
9121                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9122            }
9123
9124            PackageSetting installerPackageSetting;
9125            if (installerPackageName != null) {
9126                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9127                if (installerPackageSetting == null) {
9128                    throw new IllegalArgumentException("Unknown installer package: "
9129                            + installerPackageName);
9130                }
9131            } else {
9132                installerPackageSetting = null;
9133            }
9134
9135            Signature[] callerSignature;
9136            Object obj = mSettings.getUserIdLPr(uid);
9137            if (obj != null) {
9138                if (obj instanceof SharedUserSetting) {
9139                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9140                } else if (obj instanceof PackageSetting) {
9141                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9142                } else {
9143                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9144                }
9145            } else {
9146                throw new SecurityException("Unknown calling uid " + uid);
9147            }
9148
9149            // Verify: can't set installerPackageName to a package that is
9150            // not signed with the same cert as the caller.
9151            if (installerPackageSetting != null) {
9152                if (compareSignatures(callerSignature,
9153                        installerPackageSetting.signatures.mSignatures)
9154                        != PackageManager.SIGNATURE_MATCH) {
9155                    throw new SecurityException(
9156                            "Caller does not have same cert as new installer package "
9157                            + installerPackageName);
9158                }
9159            }
9160
9161            // Verify: if target already has an installer package, it must
9162            // be signed with the same cert as the caller.
9163            if (targetPackageSetting.installerPackageName != null) {
9164                PackageSetting setting = mSettings.mPackages.get(
9165                        targetPackageSetting.installerPackageName);
9166                // If the currently set package isn't valid, then it's always
9167                // okay to change it.
9168                if (setting != null) {
9169                    if (compareSignatures(callerSignature,
9170                            setting.signatures.mSignatures)
9171                            != PackageManager.SIGNATURE_MATCH) {
9172                        throw new SecurityException(
9173                                "Caller does not have same cert as old installer package "
9174                                + targetPackageSetting.installerPackageName);
9175                    }
9176                }
9177            }
9178
9179            // Okay!
9180            targetPackageSetting.installerPackageName = installerPackageName;
9181            scheduleWriteSettingsLocked();
9182        }
9183    }
9184
9185    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9186        // Queue up an async operation since the package installation may take a little while.
9187        mHandler.post(new Runnable() {
9188            public void run() {
9189                mHandler.removeCallbacks(this);
9190                 // Result object to be returned
9191                PackageInstalledInfo res = new PackageInstalledInfo();
9192                res.returnCode = currentStatus;
9193                res.uid = -1;
9194                res.pkg = null;
9195                res.removedInfo = new PackageRemovedInfo();
9196                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9197                    args.doPreInstall(res.returnCode);
9198                    synchronized (mInstallLock) {
9199                        installPackageLI(args, res);
9200                    }
9201                    args.doPostInstall(res.returnCode, res.uid);
9202                }
9203
9204                // A restore should be performed at this point if (a) the install
9205                // succeeded, (b) the operation is not an update, and (c) the new
9206                // package has not opted out of backup participation.
9207                final boolean update = res.removedInfo.removedPackage != null;
9208                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9209                boolean doRestore = !update
9210                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9211
9212                // Set up the post-install work request bookkeeping.  This will be used
9213                // and cleaned up by the post-install event handling regardless of whether
9214                // there's a restore pass performed.  Token values are >= 1.
9215                int token;
9216                if (mNextInstallToken < 0) mNextInstallToken = 1;
9217                token = mNextInstallToken++;
9218
9219                PostInstallData data = new PostInstallData(args, res);
9220                mRunningInstalls.put(token, data);
9221                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9222
9223                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9224                    // Pass responsibility to the Backup Manager.  It will perform a
9225                    // restore if appropriate, then pass responsibility back to the
9226                    // Package Manager to run the post-install observer callbacks
9227                    // and broadcasts.
9228                    IBackupManager bm = IBackupManager.Stub.asInterface(
9229                            ServiceManager.getService(Context.BACKUP_SERVICE));
9230                    if (bm != null) {
9231                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9232                                + " to BM for possible restore");
9233                        try {
9234                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9235                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9236                            } else {
9237                                doRestore = false;
9238                            }
9239                        } catch (RemoteException e) {
9240                            // can't happen; the backup manager is local
9241                        } catch (Exception e) {
9242                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9243                            doRestore = false;
9244                        }
9245                    } else {
9246                        Slog.e(TAG, "Backup Manager not found!");
9247                        doRestore = false;
9248                    }
9249                }
9250
9251                if (!doRestore) {
9252                    // No restore possible, or the Backup Manager was mysteriously not
9253                    // available -- just fire the post-install work request directly.
9254                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9255                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9256                    mHandler.sendMessage(msg);
9257                }
9258            }
9259        });
9260    }
9261
9262    private abstract class HandlerParams {
9263        private static final int MAX_RETRIES = 4;
9264
9265        /**
9266         * Number of times startCopy() has been attempted and had a non-fatal
9267         * error.
9268         */
9269        private int mRetries = 0;
9270
9271        /** User handle for the user requesting the information or installation. */
9272        private final UserHandle mUser;
9273
9274        HandlerParams(UserHandle user) {
9275            mUser = user;
9276        }
9277
9278        UserHandle getUser() {
9279            return mUser;
9280        }
9281
9282        final boolean startCopy() {
9283            boolean res;
9284            try {
9285                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9286
9287                if (++mRetries > MAX_RETRIES) {
9288                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9289                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9290                    handleServiceError();
9291                    return false;
9292                } else {
9293                    handleStartCopy();
9294                    res = true;
9295                }
9296            } catch (RemoteException e) {
9297                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9298                mHandler.sendEmptyMessage(MCS_RECONNECT);
9299                res = false;
9300            }
9301            handleReturnCode();
9302            return res;
9303        }
9304
9305        final void serviceError() {
9306            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9307            handleServiceError();
9308            handleReturnCode();
9309        }
9310
9311        abstract void handleStartCopy() throws RemoteException;
9312        abstract void handleServiceError();
9313        abstract void handleReturnCode();
9314    }
9315
9316    class MeasureParams extends HandlerParams {
9317        private final PackageStats mStats;
9318        private boolean mSuccess;
9319
9320        private final IPackageStatsObserver mObserver;
9321
9322        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9323            super(new UserHandle(stats.userHandle));
9324            mObserver = observer;
9325            mStats = stats;
9326        }
9327
9328        @Override
9329        public String toString() {
9330            return "MeasureParams{"
9331                + Integer.toHexString(System.identityHashCode(this))
9332                + " " + mStats.packageName + "}";
9333        }
9334
9335        @Override
9336        void handleStartCopy() throws RemoteException {
9337            synchronized (mInstallLock) {
9338                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9339            }
9340
9341            if (mSuccess) {
9342                final boolean mounted;
9343                if (Environment.isExternalStorageEmulated()) {
9344                    mounted = true;
9345                } else {
9346                    final String status = Environment.getExternalStorageState();
9347                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9348                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9349                }
9350
9351                if (mounted) {
9352                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9353
9354                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9355                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9356
9357                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9358                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9359
9360                    // Always subtract cache size, since it's a subdirectory
9361                    mStats.externalDataSize -= mStats.externalCacheSize;
9362
9363                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9364                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9365
9366                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9367                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9368                }
9369            }
9370        }
9371
9372        @Override
9373        void handleReturnCode() {
9374            if (mObserver != null) {
9375                try {
9376                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9377                } catch (RemoteException e) {
9378                    Slog.i(TAG, "Observer no longer exists.");
9379                }
9380            }
9381        }
9382
9383        @Override
9384        void handleServiceError() {
9385            Slog.e(TAG, "Could not measure application " + mStats.packageName
9386                            + " external storage");
9387        }
9388    }
9389
9390    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9391            throws RemoteException {
9392        long result = 0;
9393        for (File path : paths) {
9394            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9395        }
9396        return result;
9397    }
9398
9399    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9400        for (File path : paths) {
9401            try {
9402                mcs.clearDirectory(path.getAbsolutePath());
9403            } catch (RemoteException e) {
9404            }
9405        }
9406    }
9407
9408    static class OriginInfo {
9409        /**
9410         * Location where install is coming from, before it has been
9411         * copied/renamed into place. This could be a single monolithic APK
9412         * file, or a cluster directory. This location may be untrusted.
9413         */
9414        final File file;
9415        final String cid;
9416
9417        /**
9418         * Flag indicating that {@link #file} or {@link #cid} has already been
9419         * staged, meaning downstream users don't need to defensively copy the
9420         * contents.
9421         */
9422        final boolean staged;
9423
9424        /**
9425         * Flag indicating that {@link #file} or {@link #cid} is an already
9426         * installed app that is being moved.
9427         */
9428        final boolean existing;
9429
9430        final String resolvedPath;
9431        final File resolvedFile;
9432
9433        static OriginInfo fromNothing() {
9434            return new OriginInfo(null, null, false, false);
9435        }
9436
9437        static OriginInfo fromUntrustedFile(File file) {
9438            return new OriginInfo(file, null, false, false);
9439        }
9440
9441        static OriginInfo fromExistingFile(File file) {
9442            return new OriginInfo(file, null, false, true);
9443        }
9444
9445        static OriginInfo fromStagedFile(File file) {
9446            return new OriginInfo(file, null, true, false);
9447        }
9448
9449        static OriginInfo fromStagedContainer(String cid) {
9450            return new OriginInfo(null, cid, true, false);
9451        }
9452
9453        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9454            this.file = file;
9455            this.cid = cid;
9456            this.staged = staged;
9457            this.existing = existing;
9458
9459            if (cid != null) {
9460                resolvedPath = PackageHelper.getSdDir(cid);
9461                resolvedFile = new File(resolvedPath);
9462            } else if (file != null) {
9463                resolvedPath = file.getAbsolutePath();
9464                resolvedFile = file;
9465            } else {
9466                resolvedPath = null;
9467                resolvedFile = null;
9468            }
9469        }
9470    }
9471
9472    class InstallParams extends HandlerParams {
9473        final OriginInfo origin;
9474        final IPackageInstallObserver2 observer;
9475        int installFlags;
9476        final String installerPackageName;
9477        final String volumeUuid;
9478        final VerificationParams verificationParams;
9479        private InstallArgs mArgs;
9480        private int mRet;
9481        final String packageAbiOverride;
9482
9483        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9484                String installerPackageName, String volumeUuid,
9485                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9486            super(user);
9487            this.origin = origin;
9488            this.observer = observer;
9489            this.installFlags = installFlags;
9490            this.installerPackageName = installerPackageName;
9491            this.volumeUuid = volumeUuid;
9492            this.verificationParams = verificationParams;
9493            this.packageAbiOverride = packageAbiOverride;
9494        }
9495
9496        @Override
9497        public String toString() {
9498            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9499                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9500        }
9501
9502        public ManifestDigest getManifestDigest() {
9503            if (verificationParams == null) {
9504                return null;
9505            }
9506            return verificationParams.getManifestDigest();
9507        }
9508
9509        private int installLocationPolicy(PackageInfoLite pkgLite) {
9510            String packageName = pkgLite.packageName;
9511            int installLocation = pkgLite.installLocation;
9512            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9513            // reader
9514            synchronized (mPackages) {
9515                PackageParser.Package pkg = mPackages.get(packageName);
9516                if (pkg != null) {
9517                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9518                        // Check for downgrading.
9519                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9520                            try {
9521                                checkDowngrade(pkg, pkgLite);
9522                            } catch (PackageManagerException e) {
9523                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9524                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9525                            }
9526                        }
9527                        // Check for updated system application.
9528                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9529                            if (onSd) {
9530                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9531                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9532                            }
9533                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9534                        } else {
9535                            if (onSd) {
9536                                // Install flag overrides everything.
9537                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9538                            }
9539                            // If current upgrade specifies particular preference
9540                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9541                                // Application explicitly specified internal.
9542                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9543                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9544                                // App explictly prefers external. Let policy decide
9545                            } else {
9546                                // Prefer previous location
9547                                if (isExternal(pkg)) {
9548                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9549                                }
9550                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9551                            }
9552                        }
9553                    } else {
9554                        // Invalid install. Return error code
9555                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9556                    }
9557                }
9558            }
9559            // All the special cases have been taken care of.
9560            // Return result based on recommended install location.
9561            if (onSd) {
9562                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9563            }
9564            return pkgLite.recommendedInstallLocation;
9565        }
9566
9567        /*
9568         * Invoke remote method to get package information and install
9569         * location values. Override install location based on default
9570         * policy if needed and then create install arguments based
9571         * on the install location.
9572         */
9573        public void handleStartCopy() throws RemoteException {
9574            int ret = PackageManager.INSTALL_SUCCEEDED;
9575
9576            // If we're already staged, we've firmly committed to an install location
9577            if (origin.staged) {
9578                if (origin.file != null) {
9579                    installFlags |= PackageManager.INSTALL_INTERNAL;
9580                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9581                } else if (origin.cid != null) {
9582                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9583                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9584                } else {
9585                    throw new IllegalStateException("Invalid stage location");
9586                }
9587            }
9588
9589            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9590            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9591
9592            PackageInfoLite pkgLite = null;
9593
9594            if (onInt && onSd) {
9595                // Check if both bits are set.
9596                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9597                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9598            } else {
9599                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9600                        packageAbiOverride);
9601
9602                /*
9603                 * If we have too little free space, try to free cache
9604                 * before giving up.
9605                 */
9606                if (!origin.staged && pkgLite.recommendedInstallLocation
9607                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9608                    // TODO: focus freeing disk space on the target device
9609                    final StorageManager storage = StorageManager.from(mContext);
9610                    final long lowThreshold = storage.getStorageLowBytes(
9611                            Environment.getDataDirectory());
9612
9613                    final long sizeBytes = mContainerService.calculateInstalledSize(
9614                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9615
9616                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
9617                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9618                                installFlags, packageAbiOverride);
9619                    }
9620
9621                    /*
9622                     * The cache free must have deleted the file we
9623                     * downloaded to install.
9624                     *
9625                     * TODO: fix the "freeCache" call to not delete
9626                     *       the file we care about.
9627                     */
9628                    if (pkgLite.recommendedInstallLocation
9629                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9630                        pkgLite.recommendedInstallLocation
9631                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9632                    }
9633                }
9634            }
9635
9636            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9637                int loc = pkgLite.recommendedInstallLocation;
9638                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9639                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9640                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9641                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9642                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9643                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9644                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9645                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9646                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9647                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9648                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9649                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9650                } else {
9651                    // Override with defaults if needed.
9652                    loc = installLocationPolicy(pkgLite);
9653                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9654                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9655                    } else if (!onSd && !onInt) {
9656                        // Override install location with flags
9657                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9658                            // Set the flag to install on external media.
9659                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9660                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9661                        } else {
9662                            // Make sure the flag for installing on external
9663                            // media is unset
9664                            installFlags |= PackageManager.INSTALL_INTERNAL;
9665                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9666                        }
9667                    }
9668                }
9669            }
9670
9671            final InstallArgs args = createInstallArgs(this);
9672            mArgs = args;
9673
9674            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9675                 /*
9676                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9677                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9678                 */
9679                int userIdentifier = getUser().getIdentifier();
9680                if (userIdentifier == UserHandle.USER_ALL
9681                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9682                    userIdentifier = UserHandle.USER_OWNER;
9683                }
9684
9685                /*
9686                 * Determine if we have any installed package verifiers. If we
9687                 * do, then we'll defer to them to verify the packages.
9688                 */
9689                final int requiredUid = mRequiredVerifierPackage == null ? -1
9690                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9691                if (!origin.existing && requiredUid != -1
9692                        && isVerificationEnabled(userIdentifier, installFlags)) {
9693                    final Intent verification = new Intent(
9694                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9695                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9696                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9697                            PACKAGE_MIME_TYPE);
9698                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9699
9700                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9701                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9702                            0 /* TODO: Which userId? */);
9703
9704                    if (DEBUG_VERIFY) {
9705                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9706                                + verification.toString() + " with " + pkgLite.verifiers.length
9707                                + " optional verifiers");
9708                    }
9709
9710                    final int verificationId = mPendingVerificationToken++;
9711
9712                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9713
9714                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9715                            installerPackageName);
9716
9717                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9718                            installFlags);
9719
9720                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9721                            pkgLite.packageName);
9722
9723                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9724                            pkgLite.versionCode);
9725
9726                    if (verificationParams != null) {
9727                        if (verificationParams.getVerificationURI() != null) {
9728                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9729                                 verificationParams.getVerificationURI());
9730                        }
9731                        if (verificationParams.getOriginatingURI() != null) {
9732                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9733                                  verificationParams.getOriginatingURI());
9734                        }
9735                        if (verificationParams.getReferrer() != null) {
9736                            verification.putExtra(Intent.EXTRA_REFERRER,
9737                                  verificationParams.getReferrer());
9738                        }
9739                        if (verificationParams.getOriginatingUid() >= 0) {
9740                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9741                                  verificationParams.getOriginatingUid());
9742                        }
9743                        if (verificationParams.getInstallerUid() >= 0) {
9744                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9745                                  verificationParams.getInstallerUid());
9746                        }
9747                    }
9748
9749                    final PackageVerificationState verificationState = new PackageVerificationState(
9750                            requiredUid, args);
9751
9752                    mPendingVerification.append(verificationId, verificationState);
9753
9754                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9755                            receivers, verificationState);
9756
9757                    /*
9758                     * If any sufficient verifiers were listed in the package
9759                     * manifest, attempt to ask them.
9760                     */
9761                    if (sufficientVerifiers != null) {
9762                        final int N = sufficientVerifiers.size();
9763                        if (N == 0) {
9764                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9765                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9766                        } else {
9767                            for (int i = 0; i < N; i++) {
9768                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9769
9770                                final Intent sufficientIntent = new Intent(verification);
9771                                sufficientIntent.setComponent(verifierComponent);
9772
9773                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9774                            }
9775                        }
9776                    }
9777
9778                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9779                            mRequiredVerifierPackage, receivers);
9780                    if (ret == PackageManager.INSTALL_SUCCEEDED
9781                            && mRequiredVerifierPackage != null) {
9782                        /*
9783                         * Send the intent to the required verification agent,
9784                         * but only start the verification timeout after the
9785                         * target BroadcastReceivers have run.
9786                         */
9787                        verification.setComponent(requiredVerifierComponent);
9788                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9789                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9790                                new BroadcastReceiver() {
9791                                    @Override
9792                                    public void onReceive(Context context, Intent intent) {
9793                                        final Message msg = mHandler
9794                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9795                                        msg.arg1 = verificationId;
9796                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9797                                    }
9798                                }, null, 0, null, null);
9799
9800                        /*
9801                         * We don't want the copy to proceed until verification
9802                         * succeeds, so null out this field.
9803                         */
9804                        mArgs = null;
9805                    }
9806                } else {
9807                    /*
9808                     * No package verification is enabled, so immediately start
9809                     * the remote call to initiate copy using temporary file.
9810                     */
9811                    ret = args.copyApk(mContainerService, true);
9812                }
9813            }
9814
9815            mRet = ret;
9816        }
9817
9818        @Override
9819        void handleReturnCode() {
9820            // If mArgs is null, then MCS couldn't be reached. When it
9821            // reconnects, it will try again to install. At that point, this
9822            // will succeed.
9823            if (mArgs != null) {
9824                processPendingInstall(mArgs, mRet);
9825            }
9826        }
9827
9828        @Override
9829        void handleServiceError() {
9830            mArgs = createInstallArgs(this);
9831            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9832        }
9833
9834        public boolean isForwardLocked() {
9835            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9836        }
9837    }
9838
9839    /**
9840     * Used during creation of InstallArgs
9841     *
9842     * @param installFlags package installation flags
9843     * @return true if should be installed on external storage
9844     */
9845    private static boolean installOnExternalAsec(int installFlags) {
9846        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9847            return false;
9848        }
9849        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9850            return true;
9851        }
9852        return false;
9853    }
9854
9855    /**
9856     * Used during creation of InstallArgs
9857     *
9858     * @param installFlags package installation flags
9859     * @return true if should be installed as forward locked
9860     */
9861    private static boolean installForwardLocked(int installFlags) {
9862        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9863    }
9864
9865    private InstallArgs createInstallArgs(InstallParams params) {
9866        if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
9867            return new AsecInstallArgs(params);
9868        } else {
9869            return new FileInstallArgs(params);
9870        }
9871    }
9872
9873    /**
9874     * Create args that describe an existing installed package. Typically used
9875     * when cleaning up old installs, or used as a move source.
9876     */
9877    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9878            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9879        final boolean isInAsec;
9880        if (installOnExternalAsec(installFlags)) {
9881            /* Apps on SD card are always in ASEC containers. */
9882            isInAsec = true;
9883        } else if (installForwardLocked(installFlags)
9884                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9885            /*
9886             * Forward-locked apps are only in ASEC containers if they're the
9887             * new style
9888             */
9889            isInAsec = true;
9890        } else {
9891            isInAsec = false;
9892        }
9893
9894        if (isInAsec) {
9895            return new AsecInstallArgs(codePath, instructionSets,
9896                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
9897        } else {
9898            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9899                    instructionSets);
9900        }
9901    }
9902
9903    static abstract class InstallArgs {
9904        /** @see InstallParams#origin */
9905        final OriginInfo origin;
9906
9907        final IPackageInstallObserver2 observer;
9908        // Always refers to PackageManager flags only
9909        final int installFlags;
9910        final String installerPackageName;
9911        final String volumeUuid;
9912        final ManifestDigest manifestDigest;
9913        final UserHandle user;
9914        final String abiOverride;
9915
9916        // The list of instruction sets supported by this app. This is currently
9917        // only used during the rmdex() phase to clean up resources. We can get rid of this
9918        // if we move dex files under the common app path.
9919        /* nullable */ String[] instructionSets;
9920
9921        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9922                String installerPackageName, String volumeUuid, ManifestDigest manifestDigest,
9923                UserHandle user, String[] instructionSets, String abiOverride) {
9924            this.origin = origin;
9925            this.installFlags = installFlags;
9926            this.observer = observer;
9927            this.installerPackageName = installerPackageName;
9928            this.volumeUuid = volumeUuid;
9929            this.manifestDigest = manifestDigest;
9930            this.user = user;
9931            this.instructionSets = instructionSets;
9932            this.abiOverride = abiOverride;
9933        }
9934
9935        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9936        abstract int doPreInstall(int status);
9937
9938        /**
9939         * Rename package into final resting place. All paths on the given
9940         * scanned package should be updated to reflect the rename.
9941         */
9942        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9943        abstract int doPostInstall(int status, int uid);
9944
9945        /** @see PackageSettingBase#codePathString */
9946        abstract String getCodePath();
9947        /** @see PackageSettingBase#resourcePathString */
9948        abstract String getResourcePath();
9949        abstract String getLegacyNativeLibraryPath();
9950
9951        // Need installer lock especially for dex file removal.
9952        abstract void cleanUpResourcesLI();
9953        abstract boolean doPostDeleteLI(boolean delete);
9954        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9955
9956        /**
9957         * Called before the source arguments are copied. This is used mostly
9958         * for MoveParams when it needs to read the source file to put it in the
9959         * destination.
9960         */
9961        int doPreCopy() {
9962            return PackageManager.INSTALL_SUCCEEDED;
9963        }
9964
9965        /**
9966         * Called after the source arguments are copied. This is used mostly for
9967         * MoveParams when it needs to read the source file to put it in the
9968         * destination.
9969         *
9970         * @return
9971         */
9972        int doPostCopy(int uid) {
9973            return PackageManager.INSTALL_SUCCEEDED;
9974        }
9975
9976        protected boolean isFwdLocked() {
9977            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9978        }
9979
9980        protected boolean isExternalAsec() {
9981            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9982        }
9983
9984        UserHandle getUser() {
9985            return user;
9986        }
9987    }
9988
9989    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
9990        if (!allCodePaths.isEmpty()) {
9991            if (instructionSets == null) {
9992                throw new IllegalStateException("instructionSet == null");
9993            }
9994            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9995            for (String codePath : allCodePaths) {
9996                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9997                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9998                    if (retCode < 0) {
9999                        Slog.w(TAG, "Couldn't remove dex file for package: "
10000                                + " at location " + codePath + ", retcode=" + retCode);
10001                        // we don't consider this to be a failure of the core package deletion
10002                    }
10003                }
10004            }
10005        }
10006    }
10007
10008    /**
10009     * Logic to handle installation of non-ASEC applications, including copying
10010     * and renaming logic.
10011     */
10012    class FileInstallArgs extends InstallArgs {
10013        private File codeFile;
10014        private File resourceFile;
10015        private File legacyNativeLibraryPath;
10016
10017        // Example topology:
10018        // /data/app/com.example/base.apk
10019        // /data/app/com.example/split_foo.apk
10020        // /data/app/com.example/lib/arm/libfoo.so
10021        // /data/app/com.example/lib/arm64/libfoo.so
10022        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10023
10024        /** New install */
10025        FileInstallArgs(InstallParams params) {
10026            super(params.origin, params.observer, params.installFlags,
10027                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10028                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10029            if (isFwdLocked()) {
10030                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10031            }
10032        }
10033
10034        /** Existing install */
10035        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
10036                String[] instructionSets) {
10037            super(OriginInfo.fromNothing(), null, 0, null, null, null, null, instructionSets, null);
10038            this.codeFile = (codePath != null) ? new File(codePath) : null;
10039            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10040            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
10041                    new File(legacyNativeLibraryPath) : null;
10042        }
10043
10044        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
10045            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
10046                    isFwdLocked(), abiOverride);
10047
10048            final StorageManager storage = StorageManager.from(mContext);
10049            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
10050        }
10051
10052        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10053            if (origin.staged) {
10054                Slog.d(TAG, origin.file + " already staged; skipping copy");
10055                codeFile = origin.file;
10056                resourceFile = origin.file;
10057                return PackageManager.INSTALL_SUCCEEDED;
10058            }
10059
10060            try {
10061                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10062                codeFile = tempDir;
10063                resourceFile = tempDir;
10064            } catch (IOException e) {
10065                Slog.w(TAG, "Failed to create copy file: " + e);
10066                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10067            }
10068
10069            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10070                @Override
10071                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10072                    if (!FileUtils.isValidExtFilename(name)) {
10073                        throw new IllegalArgumentException("Invalid filename: " + name);
10074                    }
10075                    try {
10076                        final File file = new File(codeFile, name);
10077                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10078                                O_RDWR | O_CREAT, 0644);
10079                        Os.chmod(file.getAbsolutePath(), 0644);
10080                        return new ParcelFileDescriptor(fd);
10081                    } catch (ErrnoException e) {
10082                        throw new RemoteException("Failed to open: " + e.getMessage());
10083                    }
10084                }
10085            };
10086
10087            int ret = PackageManager.INSTALL_SUCCEEDED;
10088            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10089            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10090                Slog.e(TAG, "Failed to copy package");
10091                return ret;
10092            }
10093
10094            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10095            NativeLibraryHelper.Handle handle = null;
10096            try {
10097                handle = NativeLibraryHelper.Handle.create(codeFile);
10098                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10099                        abiOverride);
10100            } catch (IOException e) {
10101                Slog.e(TAG, "Copying native libraries failed", e);
10102                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10103            } finally {
10104                IoUtils.closeQuietly(handle);
10105            }
10106
10107            return ret;
10108        }
10109
10110        int doPreInstall(int status) {
10111            if (status != PackageManager.INSTALL_SUCCEEDED) {
10112                cleanUp();
10113            }
10114            return status;
10115        }
10116
10117        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10118            if (status != PackageManager.INSTALL_SUCCEEDED) {
10119                cleanUp();
10120                return false;
10121            } else {
10122                final File targetDir = codeFile.getParentFile();
10123                final File beforeCodeFile = codeFile;
10124                final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10125
10126                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10127                try {
10128                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10129                } catch (ErrnoException e) {
10130                    Slog.d(TAG, "Failed to rename", e);
10131                    return false;
10132                }
10133
10134                if (!SELinux.restoreconRecursive(afterCodeFile)) {
10135                    Slog.d(TAG, "Failed to restorecon");
10136                    return false;
10137                }
10138
10139                // Reflect the rename internally
10140                codeFile = afterCodeFile;
10141                resourceFile = afterCodeFile;
10142
10143                // Reflect the rename in scanned details
10144                pkg.codePath = afterCodeFile.getAbsolutePath();
10145                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10146                        pkg.baseCodePath);
10147                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10148                        pkg.splitCodePaths);
10149
10150                // Reflect the rename in app info
10151                pkg.applicationInfo.setCodePath(pkg.codePath);
10152                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10153                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10154                pkg.applicationInfo.setResourcePath(pkg.codePath);
10155                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10156                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10157
10158                return true;
10159            }
10160        }
10161
10162        int doPostInstall(int status, int uid) {
10163            if (status != PackageManager.INSTALL_SUCCEEDED) {
10164                cleanUp();
10165            }
10166            return status;
10167        }
10168
10169        @Override
10170        String getCodePath() {
10171            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10172        }
10173
10174        @Override
10175        String getResourcePath() {
10176            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10177        }
10178
10179        @Override
10180        String getLegacyNativeLibraryPath() {
10181            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
10182        }
10183
10184        private boolean cleanUp() {
10185            if (codeFile == null || !codeFile.exists()) {
10186                return false;
10187            }
10188
10189            if (codeFile.isDirectory()) {
10190                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10191            } else {
10192                codeFile.delete();
10193            }
10194
10195            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10196                resourceFile.delete();
10197            }
10198
10199            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
10200                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
10201                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
10202                }
10203                legacyNativeLibraryPath.delete();
10204            }
10205
10206            return true;
10207        }
10208
10209        void cleanUpResourcesLI() {
10210            // Try enumerating all code paths before deleting
10211            List<String> allCodePaths = Collections.EMPTY_LIST;
10212            if (codeFile != null && codeFile.exists()) {
10213                try {
10214                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10215                    allCodePaths = pkg.getAllCodePaths();
10216                } catch (PackageParserException e) {
10217                    // Ignored; we tried our best
10218                }
10219            }
10220
10221            cleanUp();
10222            removeDexFiles(allCodePaths, instructionSets);
10223        }
10224
10225        boolean doPostDeleteLI(boolean delete) {
10226            // XXX err, shouldn't we respect the delete flag?
10227            cleanUpResourcesLI();
10228            return true;
10229        }
10230    }
10231
10232    private boolean isAsecExternal(String cid) {
10233        final String asecPath = PackageHelper.getSdFilesystem(cid);
10234        return !asecPath.startsWith(mAsecInternalPath);
10235    }
10236
10237    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10238            PackageManagerException {
10239        if (copyRet < 0) {
10240            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10241                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10242                throw new PackageManagerException(copyRet, message);
10243            }
10244        }
10245    }
10246
10247    /**
10248     * Extract the MountService "container ID" from the full code path of an
10249     * .apk.
10250     */
10251    static String cidFromCodePath(String fullCodePath) {
10252        int eidx = fullCodePath.lastIndexOf("/");
10253        String subStr1 = fullCodePath.substring(0, eidx);
10254        int sidx = subStr1.lastIndexOf("/");
10255        return subStr1.substring(sidx+1, eidx);
10256    }
10257
10258    /**
10259     * Logic to handle installation of ASEC applications, including copying and
10260     * renaming logic.
10261     */
10262    class AsecInstallArgs extends InstallArgs {
10263        static final String RES_FILE_NAME = "pkg.apk";
10264        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10265
10266        String cid;
10267        String packagePath;
10268        String resourcePath;
10269        String legacyNativeLibraryDir;
10270
10271        /** New install */
10272        AsecInstallArgs(InstallParams params) {
10273            super(params.origin, params.observer, params.installFlags,
10274                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10275                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10276        }
10277
10278        /** Existing install */
10279        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10280                        boolean isExternal, boolean isForwardLocked) {
10281            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
10282                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10283                    instructionSets, null);
10284            // Hackily pretend we're still looking at a full code path
10285            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10286                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10287            }
10288
10289            // Extract cid from fullCodePath
10290            int eidx = fullCodePath.lastIndexOf("/");
10291            String subStr1 = fullCodePath.substring(0, eidx);
10292            int sidx = subStr1.lastIndexOf("/");
10293            cid = subStr1.substring(sidx+1, eidx);
10294            setMountPath(subStr1);
10295        }
10296
10297        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10298            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10299                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10300                    instructionSets, null);
10301            this.cid = cid;
10302            setMountPath(PackageHelper.getSdDir(cid));
10303        }
10304
10305        void createCopyFile() {
10306            cid = mInstallerService.allocateExternalStageCidLegacy();
10307        }
10308
10309        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
10310            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
10311                    abiOverride);
10312
10313            final File target;
10314            if (isExternalAsec()) {
10315                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
10316            } else {
10317                target = Environment.getDataDirectory();
10318            }
10319
10320            final StorageManager storage = StorageManager.from(mContext);
10321            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
10322        }
10323
10324        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10325            if (origin.staged) {
10326                Slog.d(TAG, origin.cid + " already staged; skipping copy");
10327                cid = origin.cid;
10328                setMountPath(PackageHelper.getSdDir(cid));
10329                return PackageManager.INSTALL_SUCCEEDED;
10330            }
10331
10332            if (temp) {
10333                createCopyFile();
10334            } else {
10335                /*
10336                 * Pre-emptively destroy the container since it's destroyed if
10337                 * copying fails due to it existing anyway.
10338                 */
10339                PackageHelper.destroySdDir(cid);
10340            }
10341
10342            final String newMountPath = imcs.copyPackageToContainer(
10343                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10344                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10345
10346            if (newMountPath != null) {
10347                setMountPath(newMountPath);
10348                return PackageManager.INSTALL_SUCCEEDED;
10349            } else {
10350                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10351            }
10352        }
10353
10354        @Override
10355        String getCodePath() {
10356            return packagePath;
10357        }
10358
10359        @Override
10360        String getResourcePath() {
10361            return resourcePath;
10362        }
10363
10364        @Override
10365        String getLegacyNativeLibraryPath() {
10366            return legacyNativeLibraryDir;
10367        }
10368
10369        int doPreInstall(int status) {
10370            if (status != PackageManager.INSTALL_SUCCEEDED) {
10371                // Destroy container
10372                PackageHelper.destroySdDir(cid);
10373            } else {
10374                boolean mounted = PackageHelper.isContainerMounted(cid);
10375                if (!mounted) {
10376                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10377                            Process.SYSTEM_UID);
10378                    if (newMountPath != null) {
10379                        setMountPath(newMountPath);
10380                    } else {
10381                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10382                    }
10383                }
10384            }
10385            return status;
10386        }
10387
10388        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10389            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10390            String newMountPath = null;
10391            if (PackageHelper.isContainerMounted(cid)) {
10392                // Unmount the container
10393                if (!PackageHelper.unMountSdDir(cid)) {
10394                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10395                    return false;
10396                }
10397            }
10398            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10399                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10400                        " which might be stale. Will try to clean up.");
10401                // Clean up the stale container and proceed to recreate.
10402                if (!PackageHelper.destroySdDir(newCacheId)) {
10403                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10404                    return false;
10405                }
10406                // Successfully cleaned up stale container. Try to rename again.
10407                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10408                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10409                            + " inspite of cleaning it up.");
10410                    return false;
10411                }
10412            }
10413            if (!PackageHelper.isContainerMounted(newCacheId)) {
10414                Slog.w(TAG, "Mounting container " + newCacheId);
10415                newMountPath = PackageHelper.mountSdDir(newCacheId,
10416                        getEncryptKey(), Process.SYSTEM_UID);
10417            } else {
10418                newMountPath = PackageHelper.getSdDir(newCacheId);
10419            }
10420            if (newMountPath == null) {
10421                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10422                return false;
10423            }
10424            Log.i(TAG, "Succesfully renamed " + cid +
10425                    " to " + newCacheId +
10426                    " at new path: " + newMountPath);
10427            cid = newCacheId;
10428
10429            final File beforeCodeFile = new File(packagePath);
10430            setMountPath(newMountPath);
10431            final File afterCodeFile = new File(packagePath);
10432
10433            // Reflect the rename in scanned details
10434            pkg.codePath = afterCodeFile.getAbsolutePath();
10435            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10436                    pkg.baseCodePath);
10437            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10438                    pkg.splitCodePaths);
10439
10440            // Reflect the rename in app info
10441            pkg.applicationInfo.setCodePath(pkg.codePath);
10442            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10443            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10444            pkg.applicationInfo.setResourcePath(pkg.codePath);
10445            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10446            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10447
10448            return true;
10449        }
10450
10451        private void setMountPath(String mountPath) {
10452            final File mountFile = new File(mountPath);
10453
10454            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10455            if (monolithicFile.exists()) {
10456                packagePath = monolithicFile.getAbsolutePath();
10457                if (isFwdLocked()) {
10458                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10459                } else {
10460                    resourcePath = packagePath;
10461                }
10462            } else {
10463                packagePath = mountFile.getAbsolutePath();
10464                resourcePath = packagePath;
10465            }
10466
10467            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
10468        }
10469
10470        int doPostInstall(int status, int uid) {
10471            if (status != PackageManager.INSTALL_SUCCEEDED) {
10472                cleanUp();
10473            } else {
10474                final int groupOwner;
10475                final String protectedFile;
10476                if (isFwdLocked()) {
10477                    groupOwner = UserHandle.getSharedAppGid(uid);
10478                    protectedFile = RES_FILE_NAME;
10479                } else {
10480                    groupOwner = -1;
10481                    protectedFile = null;
10482                }
10483
10484                if (uid < Process.FIRST_APPLICATION_UID
10485                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10486                    Slog.e(TAG, "Failed to finalize " + cid);
10487                    PackageHelper.destroySdDir(cid);
10488                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10489                }
10490
10491                boolean mounted = PackageHelper.isContainerMounted(cid);
10492                if (!mounted) {
10493                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10494                }
10495            }
10496            return status;
10497        }
10498
10499        private void cleanUp() {
10500            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10501
10502            // Destroy secure container
10503            PackageHelper.destroySdDir(cid);
10504        }
10505
10506        private List<String> getAllCodePaths() {
10507            final File codeFile = new File(getCodePath());
10508            if (codeFile != null && codeFile.exists()) {
10509                try {
10510                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10511                    return pkg.getAllCodePaths();
10512                } catch (PackageParserException e) {
10513                    // Ignored; we tried our best
10514                }
10515            }
10516            return Collections.EMPTY_LIST;
10517        }
10518
10519        void cleanUpResourcesLI() {
10520            // Enumerate all code paths before deleting
10521            cleanUpResourcesLI(getAllCodePaths());
10522        }
10523
10524        private void cleanUpResourcesLI(List<String> allCodePaths) {
10525            cleanUp();
10526            removeDexFiles(allCodePaths, instructionSets);
10527        }
10528
10529
10530
10531        String getPackageName() {
10532            return getAsecPackageName(cid);
10533        }
10534
10535        boolean doPostDeleteLI(boolean delete) {
10536            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10537            final List<String> allCodePaths = getAllCodePaths();
10538            boolean mounted = PackageHelper.isContainerMounted(cid);
10539            if (mounted) {
10540                // Unmount first
10541                if (PackageHelper.unMountSdDir(cid)) {
10542                    mounted = false;
10543                }
10544            }
10545            if (!mounted && delete) {
10546                cleanUpResourcesLI(allCodePaths);
10547            }
10548            return !mounted;
10549        }
10550
10551        @Override
10552        int doPreCopy() {
10553            if (isFwdLocked()) {
10554                if (!PackageHelper.fixSdPermissions(cid,
10555                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10556                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10557                }
10558            }
10559
10560            return PackageManager.INSTALL_SUCCEEDED;
10561        }
10562
10563        @Override
10564        int doPostCopy(int uid) {
10565            if (isFwdLocked()) {
10566                if (uid < Process.FIRST_APPLICATION_UID
10567                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10568                                RES_FILE_NAME)) {
10569                    Slog.e(TAG, "Failed to finalize " + cid);
10570                    PackageHelper.destroySdDir(cid);
10571                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10572                }
10573            }
10574
10575            return PackageManager.INSTALL_SUCCEEDED;
10576        }
10577    }
10578
10579    static String getAsecPackageName(String packageCid) {
10580        int idx = packageCid.lastIndexOf("-");
10581        if (idx == -1) {
10582            return packageCid;
10583        }
10584        return packageCid.substring(0, idx);
10585    }
10586
10587    // Utility method used to create code paths based on package name and available index.
10588    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
10589        String idxStr = "";
10590        int idx = 1;
10591        // Fall back to default value of idx=1 if prefix is not
10592        // part of oldCodePath
10593        if (oldCodePath != null) {
10594            String subStr = oldCodePath;
10595            // Drop the suffix right away
10596            if (suffix != null && subStr.endsWith(suffix)) {
10597                subStr = subStr.substring(0, subStr.length() - suffix.length());
10598            }
10599            // If oldCodePath already contains prefix find out the
10600            // ending index to either increment or decrement.
10601            int sidx = subStr.lastIndexOf(prefix);
10602            if (sidx != -1) {
10603                subStr = subStr.substring(sidx + prefix.length());
10604                if (subStr != null) {
10605                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10606                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10607                    }
10608                    try {
10609                        idx = Integer.parseInt(subStr);
10610                        if (idx <= 1) {
10611                            idx++;
10612                        } else {
10613                            idx--;
10614                        }
10615                    } catch(NumberFormatException e) {
10616                    }
10617                }
10618            }
10619        }
10620        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10621        return prefix + idxStr;
10622    }
10623
10624    private File getNextCodePath(File targetDir, String packageName) {
10625        int suffix = 1;
10626        File result;
10627        do {
10628            result = new File(targetDir, packageName + "-" + suffix);
10629            suffix++;
10630        } while (result.exists());
10631        return result;
10632    }
10633
10634    // Utility method that returns the relative package path with respect
10635    // to the installation directory. Like say for /data/data/com.test-1.apk
10636    // string com.test-1 is returned.
10637    static String deriveCodePathName(String codePath) {
10638        if (codePath == null) {
10639            return null;
10640        }
10641        final File codeFile = new File(codePath);
10642        final String name = codeFile.getName();
10643        if (codeFile.isDirectory()) {
10644            return name;
10645        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10646            final int lastDot = name.lastIndexOf('.');
10647            return name.substring(0, lastDot);
10648        } else {
10649            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10650            return null;
10651        }
10652    }
10653
10654    class PackageInstalledInfo {
10655        String name;
10656        int uid;
10657        // The set of users that originally had this package installed.
10658        int[] origUsers;
10659        // The set of users that now have this package installed.
10660        int[] newUsers;
10661        PackageParser.Package pkg;
10662        int returnCode;
10663        String returnMsg;
10664        PackageRemovedInfo removedInfo;
10665
10666        public void setError(int code, String msg) {
10667            returnCode = code;
10668            returnMsg = msg;
10669            Slog.w(TAG, msg);
10670        }
10671
10672        public void setError(String msg, PackageParserException e) {
10673            returnCode = e.error;
10674            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10675            Slog.w(TAG, msg, e);
10676        }
10677
10678        public void setError(String msg, PackageManagerException e) {
10679            returnCode = e.error;
10680            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10681            Slog.w(TAG, msg, e);
10682        }
10683
10684        // In some error cases we want to convey more info back to the observer
10685        String origPackage;
10686        String origPermission;
10687    }
10688
10689    /*
10690     * Install a non-existing package.
10691     */
10692    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
10693            UserHandle user, String installerPackageName, String volumeUuid,
10694            PackageInstalledInfo res) {
10695        // Remember this for later, in case we need to rollback this install
10696        String pkgName = pkg.packageName;
10697
10698        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10699        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
10700        synchronized(mPackages) {
10701            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10702                // A package with the same name is already installed, though
10703                // it has been renamed to an older name.  The package we
10704                // are trying to install should be installed as an update to
10705                // the existing one, but that has not been requested, so bail.
10706                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10707                        + " without first uninstalling package running as "
10708                        + mSettings.mRenamedPackages.get(pkgName));
10709                return;
10710            }
10711            if (mPackages.containsKey(pkgName)) {
10712                // Don't allow installation over an existing package with the same name.
10713                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10714                        + " without first uninstalling.");
10715                return;
10716            }
10717        }
10718
10719        try {
10720            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10721                    System.currentTimeMillis(), user);
10722
10723            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
10724            // delete the partially installed application. the data directory will have to be
10725            // restored if it was already existing
10726            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10727                // remove package from internal structures.  Note that we want deletePackageX to
10728                // delete the package data and cache directories that it created in
10729                // scanPackageLocked, unless those directories existed before we even tried to
10730                // install.
10731                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10732                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10733                                res.removedInfo, true);
10734            }
10735
10736        } catch (PackageManagerException e) {
10737            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10738        }
10739    }
10740
10741    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10742        // Upgrade keysets are being used.  Determine if new package has a superset of the
10743        // required keys.
10744        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10745        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10746        for (int i = 0; i < upgradeKeySets.length; i++) {
10747            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10748            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10749                return true;
10750            }
10751        }
10752        return false;
10753    }
10754
10755    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
10756            UserHandle user, String installerPackageName, String volumeUuid,
10757            PackageInstalledInfo res) {
10758        PackageParser.Package oldPackage;
10759        String pkgName = pkg.packageName;
10760        int[] allUsers;
10761        boolean[] perUserInstalled;
10762
10763        // First find the old package info and check signatures
10764        synchronized(mPackages) {
10765            oldPackage = mPackages.get(pkgName);
10766            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10767            PackageSetting ps = mSettings.mPackages.get(pkgName);
10768            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10769                // default to original signature matching
10770                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10771                    != PackageManager.SIGNATURE_MATCH) {
10772                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10773                            "New package has a different signature: " + pkgName);
10774                    return;
10775                }
10776            } else {
10777                if(!checkUpgradeKeySetLP(ps, pkg)) {
10778                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10779                            "New package not signed by keys specified by upgrade-keysets: "
10780                            + pkgName);
10781                    return;
10782                }
10783            }
10784
10785            // In case of rollback, remember per-user/profile install state
10786            allUsers = sUserManager.getUserIds();
10787            perUserInstalled = new boolean[allUsers.length];
10788            for (int i = 0; i < allUsers.length; i++) {
10789                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10790            }
10791        }
10792
10793        boolean sysPkg = (isSystemApp(oldPackage));
10794        if (sysPkg) {
10795            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10796                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
10797        } else {
10798            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10799                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
10800        }
10801    }
10802
10803    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10804            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10805            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
10806            String volumeUuid, PackageInstalledInfo res) {
10807        String pkgName = deletedPackage.packageName;
10808        boolean deletedPkg = true;
10809        boolean updatedSettings = false;
10810
10811        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10812                + deletedPackage);
10813        long origUpdateTime;
10814        if (pkg.mExtras != null) {
10815            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10816        } else {
10817            origUpdateTime = 0;
10818        }
10819
10820        // First delete the existing package while retaining the data directory
10821        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10822                res.removedInfo, true)) {
10823            // If the existing package wasn't successfully deleted
10824            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10825            deletedPkg = false;
10826        } else {
10827            // Successfully deleted the old package; proceed with replace.
10828
10829            // If deleted package lived in a container, give users a chance to
10830            // relinquish resources before killing.
10831            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
10832                if (DEBUG_INSTALL) {
10833                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10834                }
10835                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10836                final ArrayList<String> pkgList = new ArrayList<String>(1);
10837                pkgList.add(deletedPackage.applicationInfo.packageName);
10838                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10839            }
10840
10841            deleteCodeCacheDirsLI(pkgName);
10842            try {
10843                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10844                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10845                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
10846                        perUserInstalled, res, user);
10847                updatedSettings = true;
10848            } catch (PackageManagerException e) {
10849                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10850            }
10851        }
10852
10853        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10854            // remove package from internal structures.  Note that we want deletePackageX to
10855            // delete the package data and cache directories that it created in
10856            // scanPackageLocked, unless those directories existed before we even tried to
10857            // install.
10858            if(updatedSettings) {
10859                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10860                deletePackageLI(
10861                        pkgName, null, true, allUsers, perUserInstalled,
10862                        PackageManager.DELETE_KEEP_DATA,
10863                                res.removedInfo, true);
10864            }
10865            // Since we failed to install the new package we need to restore the old
10866            // package that we deleted.
10867            if (deletedPkg) {
10868                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10869                File restoreFile = new File(deletedPackage.codePath);
10870                // Parse old package
10871                boolean oldExternal = isExternal(deletedPackage);
10872                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10873                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10874                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
10875                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10876                try {
10877                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10878                } catch (PackageManagerException e) {
10879                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10880                            + e.getMessage());
10881                    return;
10882                }
10883                // Restore of old package succeeded. Update permissions.
10884                // writer
10885                synchronized (mPackages) {
10886                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10887                            UPDATE_PERMISSIONS_ALL);
10888                    // can downgrade to reader
10889                    mSettings.writeLPr();
10890                }
10891                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10892            }
10893        }
10894    }
10895
10896    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10897            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10898            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
10899            String volumeUuid, PackageInstalledInfo res) {
10900        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10901                + ", old=" + deletedPackage);
10902        boolean disabledSystem = false;
10903        boolean updatedSettings = false;
10904        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10905        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
10906                != 0) {
10907            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10908        }
10909        String packageName = deletedPackage.packageName;
10910        if (packageName == null) {
10911            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10912                    "Attempt to delete null packageName.");
10913            return;
10914        }
10915        PackageParser.Package oldPkg;
10916        PackageSetting oldPkgSetting;
10917        // reader
10918        synchronized (mPackages) {
10919            oldPkg = mPackages.get(packageName);
10920            oldPkgSetting = mSettings.mPackages.get(packageName);
10921            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10922                    (oldPkgSetting == null)) {
10923                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10924                        "Couldn't find package:" + packageName + " information");
10925                return;
10926            }
10927        }
10928
10929        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10930
10931        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10932        res.removedInfo.removedPackage = packageName;
10933        // Remove existing system package
10934        removePackageLI(oldPkgSetting, true);
10935        // writer
10936        synchronized (mPackages) {
10937            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10938            if (!disabledSystem && deletedPackage != null) {
10939                // We didn't need to disable the .apk as a current system package,
10940                // which means we are replacing another update that is already
10941                // installed.  We need to make sure to delete the older one's .apk.
10942                res.removedInfo.args = createInstallArgsForExisting(0,
10943                        deletedPackage.applicationInfo.getCodePath(),
10944                        deletedPackage.applicationInfo.getResourcePath(),
10945                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10946                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10947            } else {
10948                res.removedInfo.args = null;
10949            }
10950        }
10951
10952        // Successfully disabled the old package. Now proceed with re-installation
10953        deleteCodeCacheDirsLI(packageName);
10954
10955        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10956        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10957
10958        PackageParser.Package newPackage = null;
10959        try {
10960            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10961            if (newPackage.mExtras != null) {
10962                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10963                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10964                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10965
10966                // is the update attempting to change shared user? that isn't going to work...
10967                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10968                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10969                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10970                            + " to " + newPkgSetting.sharedUser);
10971                    updatedSettings = true;
10972                }
10973            }
10974
10975            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10976                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
10977                        perUserInstalled, res, user);
10978                updatedSettings = true;
10979            }
10980
10981        } catch (PackageManagerException e) {
10982            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10983        }
10984
10985        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10986            // Re installation failed. Restore old information
10987            // Remove new pkg information
10988            if (newPackage != null) {
10989                removeInstalledPackageLI(newPackage, true);
10990            }
10991            // Add back the old system package
10992            try {
10993                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10994            } catch (PackageManagerException e) {
10995                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10996            }
10997            // Restore the old system information in Settings
10998            synchronized (mPackages) {
10999                if (disabledSystem) {
11000                    mSettings.enableSystemPackageLPw(packageName);
11001                }
11002                if (updatedSettings) {
11003                    mSettings.setInstallerPackageName(packageName,
11004                            oldPkgSetting.installerPackageName);
11005                }
11006                mSettings.writeLPr();
11007            }
11008        }
11009    }
11010
11011    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11012            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11013            UserHandle user) {
11014        String pkgName = newPackage.packageName;
11015        synchronized (mPackages) {
11016            //write settings. the installStatus will be incomplete at this stage.
11017            //note that the new package setting would have already been
11018            //added to mPackages. It hasn't been persisted yet.
11019            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11020            mSettings.writeLPr();
11021        }
11022
11023        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11024
11025        synchronized (mPackages) {
11026            updatePermissionsLPw(newPackage.packageName, newPackage,
11027                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11028                            ? UPDATE_PERMISSIONS_ALL : 0));
11029            // For system-bundled packages, we assume that installing an upgraded version
11030            // of the package implies that the user actually wants to run that new code,
11031            // so we enable the package.
11032            PackageSetting ps = mSettings.mPackages.get(pkgName);
11033            if (ps != null) {
11034                if (isSystemApp(newPackage)) {
11035                    // NB: implicit assumption that system package upgrades apply to all users
11036                    if (DEBUG_INSTALL) {
11037                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11038                    }
11039                    if (res.origUsers != null) {
11040                        for (int userHandle : res.origUsers) {
11041                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11042                                    userHandle, installerPackageName);
11043                        }
11044                    }
11045                    // Also convey the prior install/uninstall state
11046                    if (allUsers != null && perUserInstalled != null) {
11047                        for (int i = 0; i < allUsers.length; i++) {
11048                            if (DEBUG_INSTALL) {
11049                                Slog.d(TAG, "    user " + allUsers[i]
11050                                        + " => " + perUserInstalled[i]);
11051                            }
11052                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11053                        }
11054                        // these install state changes will be persisted in the
11055                        // upcoming call to mSettings.writeLPr().
11056                    }
11057                }
11058                // It's implied that when a user requests installation, they want the app to be
11059                // installed and enabled.
11060                int userId = user.getIdentifier();
11061                if (userId != UserHandle.USER_ALL) {
11062                    ps.setInstalled(true, userId);
11063                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11064                }
11065            }
11066            res.name = pkgName;
11067            res.uid = newPackage.applicationInfo.uid;
11068            res.pkg = newPackage;
11069            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11070            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11071            mSettings.setVolumeUuid(pkgName, volumeUuid);
11072            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11073            //to update install status
11074            mSettings.writeLPr();
11075        }
11076    }
11077
11078    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11079        final int installFlags = args.installFlags;
11080        final String installerPackageName = args.installerPackageName;
11081        final String volumeUuid = args.volumeUuid;
11082        final File tmpPackageFile = new File(args.getCodePath());
11083        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11084        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11085                || (args.volumeUuid != null));
11086        boolean replace = false;
11087        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
11088        // Result object to be returned
11089        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11090
11091        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11092        // Retrieve PackageSettings and parse package
11093        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11094                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11095                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11096        PackageParser pp = new PackageParser();
11097        pp.setSeparateProcesses(mSeparateProcesses);
11098        pp.setDisplayMetrics(mMetrics);
11099
11100        final PackageParser.Package pkg;
11101        try {
11102            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11103        } catch (PackageParserException e) {
11104            res.setError("Failed parse during installPackageLI", e);
11105            return;
11106        }
11107
11108        // Mark that we have an install time CPU ABI override.
11109        pkg.cpuAbiOverride = args.abiOverride;
11110
11111        String pkgName = res.name = pkg.packageName;
11112        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11113            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11114                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11115                return;
11116            }
11117        }
11118
11119        try {
11120            pp.collectCertificates(pkg, parseFlags);
11121            pp.collectManifestDigest(pkg);
11122        } catch (PackageParserException e) {
11123            res.setError("Failed collect during installPackageLI", e);
11124            return;
11125        }
11126
11127        /* If the installer passed in a manifest digest, compare it now. */
11128        if (args.manifestDigest != null) {
11129            if (DEBUG_INSTALL) {
11130                final String parsedManifest = pkg.manifestDigest == null ? "null"
11131                        : pkg.manifestDigest.toString();
11132                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11133                        + parsedManifest);
11134            }
11135
11136            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11137                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11138                return;
11139            }
11140        } else if (DEBUG_INSTALL) {
11141            final String parsedManifest = pkg.manifestDigest == null
11142                    ? "null" : pkg.manifestDigest.toString();
11143            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11144        }
11145
11146        // Get rid of all references to package scan path via parser.
11147        pp = null;
11148        String oldCodePath = null;
11149        boolean systemApp = false;
11150        synchronized (mPackages) {
11151            // Check if installing already existing package
11152            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11153                String oldName = mSettings.mRenamedPackages.get(pkgName);
11154                if (pkg.mOriginalPackages != null
11155                        && pkg.mOriginalPackages.contains(oldName)
11156                        && mPackages.containsKey(oldName)) {
11157                    // This package is derived from an original package,
11158                    // and this device has been updating from that original
11159                    // name.  We must continue using the original name, so
11160                    // rename the new package here.
11161                    pkg.setPackageName(oldName);
11162                    pkgName = pkg.packageName;
11163                    replace = true;
11164                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11165                            + oldName + " pkgName=" + pkgName);
11166                } else if (mPackages.containsKey(pkgName)) {
11167                    // This package, under its official name, already exists
11168                    // on the device; we should replace it.
11169                    replace = true;
11170                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11171                }
11172            }
11173
11174            PackageSetting ps = mSettings.mPackages.get(pkgName);
11175            if (ps != null) {
11176                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11177
11178                // Quick sanity check that we're signed correctly if updating;
11179                // we'll check this again later when scanning, but we want to
11180                // bail early here before tripping over redefined permissions.
11181                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11182                    try {
11183                        verifySignaturesLP(ps, pkg);
11184                    } catch (PackageManagerException e) {
11185                        res.setError(e.error, e.getMessage());
11186                        return;
11187                    }
11188                } else {
11189                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11190                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11191                                + pkg.packageName + " upgrade keys do not match the "
11192                                + "previously installed version");
11193                        return;
11194                    }
11195                }
11196
11197                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11198                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11199                    systemApp = (ps.pkg.applicationInfo.flags &
11200                            ApplicationInfo.FLAG_SYSTEM) != 0;
11201                }
11202                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11203            }
11204
11205            // Check whether the newly-scanned package wants to define an already-defined perm
11206            int N = pkg.permissions.size();
11207            for (int i = N-1; i >= 0; i--) {
11208                PackageParser.Permission perm = pkg.permissions.get(i);
11209                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11210                if (bp != null) {
11211                    // If the defining package is signed with our cert, it's okay.  This
11212                    // also includes the "updating the same package" case, of course.
11213                    // "updating same package" could also involve key-rotation.
11214                    final boolean sigsOk;
11215                    if (!bp.sourcePackage.equals(pkg.packageName)
11216                            || !(bp.packageSetting instanceof PackageSetting)
11217                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
11218                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
11219                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11220                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11221                    } else {
11222                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11223                    }
11224                    if (!sigsOk) {
11225                        // If the owning package is the system itself, we log but allow
11226                        // install to proceed; we fail the install on all other permission
11227                        // redefinitions.
11228                        if (!bp.sourcePackage.equals("android")) {
11229                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11230                                    + pkg.packageName + " attempting to redeclare permission "
11231                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11232                            res.origPermission = perm.info.name;
11233                            res.origPackage = bp.sourcePackage;
11234                            return;
11235                        } else {
11236                            Slog.w(TAG, "Package " + pkg.packageName
11237                                    + " attempting to redeclare system permission "
11238                                    + perm.info.name + "; ignoring new declaration");
11239                            pkg.permissions.remove(i);
11240                        }
11241                    }
11242                }
11243            }
11244
11245        }
11246
11247        if (systemApp && onExternal) {
11248            // Disable updates to system apps on sdcard
11249            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11250                    "Cannot install updates to system apps on sdcard");
11251            return;
11252        }
11253
11254        // Run dexopt before old package gets removed, to minimize time when app is not available
11255        int result = mPackageDexOptimizer
11256                .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */,
11257                        false /* defer */, false /* inclDependencies */);
11258        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11259            res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11260            return;
11261        }
11262
11263        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11264            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11265            return;
11266        }
11267
11268        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11269
11270        // Call with SCAN_NO_DEX, since dexopt has already been made
11271        if (replace) {
11272            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING | SCAN_NO_DEX, args.user,
11273                    installerPackageName, volumeUuid, res);
11274        } else {
11275            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES
11276                    | SCAN_NO_DEX, args.user, installerPackageName, volumeUuid, res);
11277        }
11278        synchronized (mPackages) {
11279            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11280            if (ps != null) {
11281                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11282            }
11283        }
11284    }
11285
11286    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11287        if (mIntentFilterVerifierComponent == null) {
11288            Slog.d(TAG, "No IntentFilter verification will not be done as "
11289                    + "there is no IntentFilterVerifier available!");
11290            return;
11291        }
11292
11293        final int verifierUid = getPackageUid(
11294                mIntentFilterVerifierComponent.getPackageName(),
11295                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11296
11297        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11298        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11299        msg.obj = pkg;
11300        msg.arg1 = userId;
11301        msg.arg2 = verifierUid;
11302
11303        mHandler.sendMessage(msg);
11304    }
11305
11306    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11307            PackageParser.Package pkg) {
11308        int size = pkg.activities.size();
11309        if (size == 0) {
11310            Slog.d(TAG, "No activity, so no need to verify any IntentFilter!");
11311            return;
11312        }
11313
11314        final boolean hasDomainURLs = hasDomainURLs(pkg);
11315        if (!hasDomainURLs) {
11316            Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!");
11317            return;
11318        }
11319
11320        Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size
11321                + " Activities needs verification ...");
11322
11323        final int verificationId = mIntentFilterVerificationToken++;
11324        int count = 0;
11325        final String packageName = pkg.packageName;
11326        ArrayList<String> allHosts = new ArrayList<>();
11327
11328        synchronized (mPackages) {
11329            for (PackageParser.Activity a : pkg.activities) {
11330                for (ActivityIntentInfo filter : a.intents) {
11331                    boolean needsFilterVerification = filter.needsVerification();
11332                    if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11333                        Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString());
11334                        mIntentFilterVerifier.addOneIntentFilterVerification(
11335                                verifierUid, userId, verificationId, filter, packageName);
11336                        count++;
11337                    } else if (!needsFilterVerification) {
11338                        Slog.d(TAG, "No verification needed for IntentFilter:"
11339                                + filter.toString());
11340                        if (hasValidDomains(filter)) {
11341                            allHosts.addAll(filter.getHostsList());
11342                        }
11343                    } else {
11344                        Slog.d(TAG, "Verification already done for IntentFilter:"
11345                                + filter.toString());
11346                    }
11347                }
11348            }
11349        }
11350
11351        if (count > 0) {
11352            mIntentFilterVerifier.startVerifications(userId);
11353            Slog.d(TAG, "Started " + count + " IntentFilter verification"
11354                    + (count > 1 ? "s" : "") +  " for userId:" + userId + "!");
11355        } else {
11356            Slog.d(TAG, "No need to start any IntentFilter verification!");
11357            if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw(
11358                    packageName, allHosts) != null) {
11359                scheduleWriteSettingsLocked();
11360            }
11361        }
11362    }
11363
11364    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11365        final ComponentName cn  = filter.activity.getComponentName();
11366        final String packageName = cn.getPackageName();
11367
11368        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11369                packageName);
11370        if (ivi == null) {
11371            return true;
11372        }
11373        int status = ivi.getStatus();
11374        switch (status) {
11375            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11376            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11377                return true;
11378
11379            default:
11380                // Nothing to do
11381                return false;
11382        }
11383    }
11384
11385    private static boolean isMultiArch(PackageSetting ps) {
11386        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11387    }
11388
11389    private static boolean isMultiArch(ApplicationInfo info) {
11390        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11391    }
11392
11393    private static boolean isExternal(PackageParser.Package pkg) {
11394        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11395    }
11396
11397    private static boolean isExternal(PackageSetting ps) {
11398        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11399    }
11400
11401    private static boolean isExternal(ApplicationInfo info) {
11402        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11403    }
11404
11405    private static boolean isSystemApp(PackageParser.Package pkg) {
11406        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11407    }
11408
11409    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11410        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11411    }
11412
11413    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11414        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11415    }
11416
11417    private static boolean isSystemApp(PackageSetting ps) {
11418        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11419    }
11420
11421    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11422        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11423    }
11424
11425    private int packageFlagsToInstallFlags(PackageSetting ps) {
11426        int installFlags = 0;
11427        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11428            // This existing package was an external ASEC install when we have
11429            // the external flag without a UUID
11430            installFlags |= PackageManager.INSTALL_EXTERNAL;
11431        }
11432        if (ps.isForwardLocked()) {
11433            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11434        }
11435        return installFlags;
11436    }
11437
11438    private void deleteTempPackageFiles() {
11439        final FilenameFilter filter = new FilenameFilter() {
11440            public boolean accept(File dir, String name) {
11441                return name.startsWith("vmdl") && name.endsWith(".tmp");
11442            }
11443        };
11444        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11445            file.delete();
11446        }
11447    }
11448
11449    @Override
11450    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11451            int flags) {
11452        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11453                flags);
11454    }
11455
11456    @Override
11457    public void deletePackage(final String packageName,
11458            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11459        mContext.enforceCallingOrSelfPermission(
11460                android.Manifest.permission.DELETE_PACKAGES, null);
11461        final int uid = Binder.getCallingUid();
11462        if (UserHandle.getUserId(uid) != userId) {
11463            mContext.enforceCallingPermission(
11464                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11465                    "deletePackage for user " + userId);
11466        }
11467        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11468            try {
11469                observer.onPackageDeleted(packageName,
11470                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11471            } catch (RemoteException re) {
11472            }
11473            return;
11474        }
11475
11476        boolean uninstallBlocked = false;
11477        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11478            int[] users = sUserManager.getUserIds();
11479            for (int i = 0; i < users.length; ++i) {
11480                if (getBlockUninstallForUser(packageName, users[i])) {
11481                    uninstallBlocked = true;
11482                    break;
11483                }
11484            }
11485        } else {
11486            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11487        }
11488        if (uninstallBlocked) {
11489            try {
11490                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11491                        null);
11492            } catch (RemoteException re) {
11493            }
11494            return;
11495        }
11496
11497        if (DEBUG_REMOVE) {
11498            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
11499        }
11500        // Queue up an async operation since the package deletion may take a little while.
11501        mHandler.post(new Runnable() {
11502            public void run() {
11503                mHandler.removeCallbacks(this);
11504                final int returnCode = deletePackageX(packageName, userId, flags);
11505                if (observer != null) {
11506                    try {
11507                        observer.onPackageDeleted(packageName, returnCode, null);
11508                    } catch (RemoteException e) {
11509                        Log.i(TAG, "Observer no longer exists.");
11510                    } //end catch
11511                } //end if
11512            } //end run
11513        });
11514    }
11515
11516    private boolean isPackageDeviceAdmin(String packageName, int userId) {
11517        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
11518                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
11519        try {
11520            if (dpm != null) {
11521                if (dpm.isDeviceOwner(packageName)) {
11522                    return true;
11523                }
11524                int[] users;
11525                if (userId == UserHandle.USER_ALL) {
11526                    users = sUserManager.getUserIds();
11527                } else {
11528                    users = new int[]{userId};
11529                }
11530                for (int i = 0; i < users.length; ++i) {
11531                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
11532                        return true;
11533                    }
11534                }
11535            }
11536        } catch (RemoteException e) {
11537        }
11538        return false;
11539    }
11540
11541    /**
11542     *  This method is an internal method that could be get invoked either
11543     *  to delete an installed package or to clean up a failed installation.
11544     *  After deleting an installed package, a broadcast is sent to notify any
11545     *  listeners that the package has been installed. For cleaning up a failed
11546     *  installation, the broadcast is not necessary since the package's
11547     *  installation wouldn't have sent the initial broadcast either
11548     *  The key steps in deleting a package are
11549     *  deleting the package information in internal structures like mPackages,
11550     *  deleting the packages base directories through installd
11551     *  updating mSettings to reflect current status
11552     *  persisting settings for later use
11553     *  sending a broadcast if necessary
11554     */
11555    private int deletePackageX(String packageName, int userId, int flags) {
11556        final PackageRemovedInfo info = new PackageRemovedInfo();
11557        final boolean res;
11558
11559        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
11560                ? UserHandle.ALL : new UserHandle(userId);
11561
11562        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
11563            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
11564            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
11565        }
11566
11567        boolean removedForAllUsers = false;
11568        boolean systemUpdate = false;
11569
11570        // for the uninstall-updates case and restricted profiles, remember the per-
11571        // userhandle installed state
11572        int[] allUsers;
11573        boolean[] perUserInstalled;
11574        synchronized (mPackages) {
11575            PackageSetting ps = mSettings.mPackages.get(packageName);
11576            allUsers = sUserManager.getUserIds();
11577            perUserInstalled = new boolean[allUsers.length];
11578            for (int i = 0; i < allUsers.length; i++) {
11579                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11580            }
11581        }
11582
11583        synchronized (mInstallLock) {
11584            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
11585            res = deletePackageLI(packageName, removeForUser,
11586                    true, allUsers, perUserInstalled,
11587                    flags | REMOVE_CHATTY, info, true);
11588            systemUpdate = info.isRemovedPackageSystemUpdate;
11589            if (res && !systemUpdate && mPackages.get(packageName) == null) {
11590                removedForAllUsers = true;
11591            }
11592            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
11593                    + " removedForAllUsers=" + removedForAllUsers);
11594        }
11595
11596        if (res) {
11597            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
11598
11599            // If the removed package was a system update, the old system package
11600            // was re-enabled; we need to broadcast this information
11601            if (systemUpdate) {
11602                Bundle extras = new Bundle(1);
11603                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
11604                        ? info.removedAppId : info.uid);
11605                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11606
11607                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
11608                        extras, null, null, null);
11609                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
11610                        extras, null, null, null);
11611                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
11612                        null, packageName, null, null);
11613            }
11614        }
11615        // Force a gc here.
11616        Runtime.getRuntime().gc();
11617        // Delete the resources here after sending the broadcast to let
11618        // other processes clean up before deleting resources.
11619        if (info.args != null) {
11620            synchronized (mInstallLock) {
11621                info.args.doPostDeleteLI(true);
11622            }
11623        }
11624
11625        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
11626    }
11627
11628    static class PackageRemovedInfo {
11629        String removedPackage;
11630        int uid = -1;
11631        int removedAppId = -1;
11632        int[] removedUsers = null;
11633        boolean isRemovedPackageSystemUpdate = false;
11634        // Clean up resources deleted packages.
11635        InstallArgs args = null;
11636
11637        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
11638            Bundle extras = new Bundle(1);
11639            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
11640            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
11641            if (replacing) {
11642                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11643            }
11644            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
11645            if (removedPackage != null) {
11646                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
11647                        extras, null, null, removedUsers);
11648                if (fullRemove && !replacing) {
11649                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
11650                            extras, null, null, removedUsers);
11651                }
11652            }
11653            if (removedAppId >= 0) {
11654                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
11655                        removedUsers);
11656            }
11657        }
11658    }
11659
11660    /*
11661     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
11662     * flag is not set, the data directory is removed as well.
11663     * make sure this flag is set for partially installed apps. If not its meaningless to
11664     * delete a partially installed application.
11665     */
11666    private void removePackageDataLI(PackageSetting ps,
11667            int[] allUserHandles, boolean[] perUserInstalled,
11668            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
11669        String packageName = ps.name;
11670        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
11671        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
11672        // Retrieve object to delete permissions for shared user later on
11673        final PackageSetting deletedPs;
11674        // reader
11675        synchronized (mPackages) {
11676            deletedPs = mSettings.mPackages.get(packageName);
11677            if (outInfo != null) {
11678                outInfo.removedPackage = packageName;
11679                outInfo.removedUsers = deletedPs != null
11680                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
11681                        : null;
11682            }
11683        }
11684        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11685            removeDataDirsLI(packageName);
11686            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
11687        }
11688        // writer
11689        synchronized (mPackages) {
11690            if (deletedPs != null) {
11691                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11692                    if (outInfo != null) {
11693                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
11694                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
11695                    }
11696                    updatePermissionsLPw(deletedPs.name, null, 0);
11697                    if (deletedPs.sharedUser != null) {
11698                        // Remove permissions associated with package. Since runtime
11699                        // permissions are per user we have to kill the removed package
11700                        // or packages running under the shared user of the removed
11701                        // package if revoking the permissions requested only by the removed
11702                        // package is successful and this causes a change in gids.
11703                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11704                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
11705                                    userId);
11706                            if (userIdToKill == UserHandle.USER_ALL
11707                                    || userIdToKill >= UserHandle.USER_OWNER) {
11708                                // If gids changed for this user, kill all affected packages.
11709                                mHandler.post(new Runnable() {
11710                                    @Override
11711                                    public void run() {
11712                                        // This has to happen with no lock held.
11713                                        killSettingPackagesForUser(deletedPs, userIdToKill,
11714                                                KILL_APP_REASON_GIDS_CHANGED);
11715                                    }
11716                                });
11717                            break;
11718                            }
11719                        }
11720                    }
11721                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
11722                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
11723                }
11724                // make sure to preserve per-user disabled state if this removal was just
11725                // a downgrade of a system app to the factory package
11726                if (allUserHandles != null && perUserInstalled != null) {
11727                    if (DEBUG_REMOVE) {
11728                        Slog.d(TAG, "Propagating install state across downgrade");
11729                    }
11730                    for (int i = 0; i < allUserHandles.length; i++) {
11731                        if (DEBUG_REMOVE) {
11732                            Slog.d(TAG, "    user " + allUserHandles[i]
11733                                    + " => " + perUserInstalled[i]);
11734                        }
11735                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11736                    }
11737                }
11738            }
11739            // can downgrade to reader
11740            if (writeSettings) {
11741                // Save settings now
11742                mSettings.writeLPr();
11743            }
11744        }
11745        if (outInfo != null) {
11746            // A user ID was deleted here. Go through all users and remove it
11747            // from KeyStore.
11748            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
11749        }
11750    }
11751
11752    static boolean locationIsPrivileged(File path) {
11753        try {
11754            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
11755                    .getCanonicalPath();
11756            return path.getCanonicalPath().startsWith(privilegedAppDir);
11757        } catch (IOException e) {
11758            Slog.e(TAG, "Unable to access code path " + path);
11759        }
11760        return false;
11761    }
11762
11763    /*
11764     * Tries to delete system package.
11765     */
11766    private boolean deleteSystemPackageLI(PackageSetting newPs,
11767            int[] allUserHandles, boolean[] perUserInstalled,
11768            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
11769        final boolean applyUserRestrictions
11770                = (allUserHandles != null) && (perUserInstalled != null);
11771        PackageSetting disabledPs = null;
11772        // Confirm if the system package has been updated
11773        // An updated system app can be deleted. This will also have to restore
11774        // the system pkg from system partition
11775        // reader
11776        synchronized (mPackages) {
11777            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
11778        }
11779        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
11780                + " disabledPs=" + disabledPs);
11781        if (disabledPs == null) {
11782            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
11783            return false;
11784        } else if (DEBUG_REMOVE) {
11785            Slog.d(TAG, "Deleting system pkg from data partition");
11786        }
11787        if (DEBUG_REMOVE) {
11788            if (applyUserRestrictions) {
11789                Slog.d(TAG, "Remembering install states:");
11790                for (int i = 0; i < allUserHandles.length; i++) {
11791                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
11792                }
11793            }
11794        }
11795        // Delete the updated package
11796        outInfo.isRemovedPackageSystemUpdate = true;
11797        if (disabledPs.versionCode < newPs.versionCode) {
11798            // Delete data for downgrades
11799            flags &= ~PackageManager.DELETE_KEEP_DATA;
11800        } else {
11801            // Preserve data by setting flag
11802            flags |= PackageManager.DELETE_KEEP_DATA;
11803        }
11804        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
11805                allUserHandles, perUserInstalled, outInfo, writeSettings);
11806        if (!ret) {
11807            return false;
11808        }
11809        // writer
11810        synchronized (mPackages) {
11811            // Reinstate the old system package
11812            mSettings.enableSystemPackageLPw(newPs.name);
11813            // Remove any native libraries from the upgraded package.
11814            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
11815        }
11816        // Install the system package
11817        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
11818        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
11819        if (locationIsPrivileged(disabledPs.codePath)) {
11820            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11821        }
11822
11823        final PackageParser.Package newPkg;
11824        try {
11825            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
11826        } catch (PackageManagerException e) {
11827            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
11828            return false;
11829        }
11830
11831        // writer
11832        synchronized (mPackages) {
11833            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
11834            updatePermissionsLPw(newPkg.packageName, newPkg,
11835                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
11836            if (applyUserRestrictions) {
11837                if (DEBUG_REMOVE) {
11838                    Slog.d(TAG, "Propagating install state across reinstall");
11839                }
11840                for (int i = 0; i < allUserHandles.length; i++) {
11841                    if (DEBUG_REMOVE) {
11842                        Slog.d(TAG, "    user " + allUserHandles[i]
11843                                + " => " + perUserInstalled[i]);
11844                    }
11845                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11846                }
11847                // Regardless of writeSettings we need to ensure that this restriction
11848                // state propagation is persisted
11849                mSettings.writeAllUsersPackageRestrictionsLPr();
11850            }
11851            // can downgrade to reader here
11852            if (writeSettings) {
11853                mSettings.writeLPr();
11854            }
11855        }
11856        return true;
11857    }
11858
11859    private boolean deleteInstalledPackageLI(PackageSetting ps,
11860            boolean deleteCodeAndResources, int flags,
11861            int[] allUserHandles, boolean[] perUserInstalled,
11862            PackageRemovedInfo outInfo, boolean writeSettings) {
11863        if (outInfo != null) {
11864            outInfo.uid = ps.appId;
11865        }
11866
11867        // Delete package data from internal structures and also remove data if flag is set
11868        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
11869
11870        // Delete application code and resources
11871        if (deleteCodeAndResources && (outInfo != null)) {
11872            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
11873                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
11874                    getAppDexInstructionSets(ps));
11875            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
11876        }
11877        return true;
11878    }
11879
11880    @Override
11881    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
11882            int userId) {
11883        mContext.enforceCallingOrSelfPermission(
11884                android.Manifest.permission.DELETE_PACKAGES, null);
11885        synchronized (mPackages) {
11886            PackageSetting ps = mSettings.mPackages.get(packageName);
11887            if (ps == null) {
11888                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
11889                return false;
11890            }
11891            if (!ps.getInstalled(userId)) {
11892                // Can't block uninstall for an app that is not installed or enabled.
11893                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11894                return false;
11895            }
11896            ps.setBlockUninstall(blockUninstall, userId);
11897            mSettings.writePackageRestrictionsLPr(userId);
11898        }
11899        return true;
11900    }
11901
11902    @Override
11903    public boolean getBlockUninstallForUser(String packageName, int userId) {
11904        synchronized (mPackages) {
11905            PackageSetting ps = mSettings.mPackages.get(packageName);
11906            if (ps == null) {
11907                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11908                return false;
11909            }
11910            return ps.getBlockUninstall(userId);
11911        }
11912    }
11913
11914    /*
11915     * This method handles package deletion in general
11916     */
11917    private boolean deletePackageLI(String packageName, UserHandle user,
11918            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11919            int flags, PackageRemovedInfo outInfo,
11920            boolean writeSettings) {
11921        if (packageName == null) {
11922            Slog.w(TAG, "Attempt to delete null packageName.");
11923            return false;
11924        }
11925        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11926        PackageSetting ps;
11927        boolean dataOnly = false;
11928        int removeUser = -1;
11929        int appId = -1;
11930        synchronized (mPackages) {
11931            ps = mSettings.mPackages.get(packageName);
11932            if (ps == null) {
11933                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11934                return false;
11935            }
11936            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11937                    && user.getIdentifier() != UserHandle.USER_ALL) {
11938                // The caller is asking that the package only be deleted for a single
11939                // user.  To do this, we just mark its uninstalled state and delete
11940                // its data.  If this is a system app, we only allow this to happen if
11941                // they have set the special DELETE_SYSTEM_APP which requests different
11942                // semantics than normal for uninstalling system apps.
11943                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11944                ps.setUserState(user.getIdentifier(),
11945                        COMPONENT_ENABLED_STATE_DEFAULT,
11946                        false, //installed
11947                        true,  //stopped
11948                        true,  //notLaunched
11949                        false, //hidden
11950                        null, null, null,
11951                        false, // blockUninstall
11952                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
11953                if (!isSystemApp(ps)) {
11954                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11955                        // Other user still have this package installed, so all
11956                        // we need to do is clear this user's data and save that
11957                        // it is uninstalled.
11958                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11959                        removeUser = user.getIdentifier();
11960                        appId = ps.appId;
11961                        mSettings.writePackageRestrictionsLPr(removeUser);
11962                    } else {
11963                        // We need to set it back to 'installed' so the uninstall
11964                        // broadcasts will be sent correctly.
11965                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11966                        ps.setInstalled(true, user.getIdentifier());
11967                    }
11968                } else {
11969                    // This is a system app, so we assume that the
11970                    // other users still have this package installed, so all
11971                    // we need to do is clear this user's data and save that
11972                    // it is uninstalled.
11973                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11974                    removeUser = user.getIdentifier();
11975                    appId = ps.appId;
11976                    mSettings.writePackageRestrictionsLPr(removeUser);
11977                }
11978            }
11979        }
11980
11981        if (removeUser >= 0) {
11982            // From above, we determined that we are deleting this only
11983            // for a single user.  Continue the work here.
11984            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11985            if (outInfo != null) {
11986                outInfo.removedPackage = packageName;
11987                outInfo.removedAppId = appId;
11988                outInfo.removedUsers = new int[] {removeUser};
11989            }
11990            mInstaller.clearUserData(packageName, removeUser);
11991            removeKeystoreDataIfNeeded(removeUser, appId);
11992            schedulePackageCleaning(packageName, removeUser, false);
11993            return true;
11994        }
11995
11996        if (dataOnly) {
11997            // Delete application data first
11998            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11999            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12000            return true;
12001        }
12002
12003        boolean ret = false;
12004        if (isSystemApp(ps)) {
12005            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12006            // When an updated system application is deleted we delete the existing resources as well and
12007            // fall back to existing code in system partition
12008            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12009                    flags, outInfo, writeSettings);
12010        } else {
12011            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12012            // Kill application pre-emptively especially for apps on sd.
12013            killApplication(packageName, ps.appId, "uninstall pkg");
12014            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12015                    allUserHandles, perUserInstalled,
12016                    outInfo, writeSettings);
12017        }
12018
12019        return ret;
12020    }
12021
12022    private final class ClearStorageConnection implements ServiceConnection {
12023        IMediaContainerService mContainerService;
12024
12025        @Override
12026        public void onServiceConnected(ComponentName name, IBinder service) {
12027            synchronized (this) {
12028                mContainerService = IMediaContainerService.Stub.asInterface(service);
12029                notifyAll();
12030            }
12031        }
12032
12033        @Override
12034        public void onServiceDisconnected(ComponentName name) {
12035        }
12036    }
12037
12038    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12039        final boolean mounted;
12040        if (Environment.isExternalStorageEmulated()) {
12041            mounted = true;
12042        } else {
12043            final String status = Environment.getExternalStorageState();
12044
12045            mounted = status.equals(Environment.MEDIA_MOUNTED)
12046                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12047        }
12048
12049        if (!mounted) {
12050            return;
12051        }
12052
12053        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12054        int[] users;
12055        if (userId == UserHandle.USER_ALL) {
12056            users = sUserManager.getUserIds();
12057        } else {
12058            users = new int[] { userId };
12059        }
12060        final ClearStorageConnection conn = new ClearStorageConnection();
12061        if (mContext.bindServiceAsUser(
12062                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12063            try {
12064                for (int curUser : users) {
12065                    long timeout = SystemClock.uptimeMillis() + 5000;
12066                    synchronized (conn) {
12067                        long now = SystemClock.uptimeMillis();
12068                        while (conn.mContainerService == null && now < timeout) {
12069                            try {
12070                                conn.wait(timeout - now);
12071                            } catch (InterruptedException e) {
12072                            }
12073                        }
12074                    }
12075                    if (conn.mContainerService == null) {
12076                        return;
12077                    }
12078
12079                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12080                    clearDirectory(conn.mContainerService,
12081                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12082                    if (allData) {
12083                        clearDirectory(conn.mContainerService,
12084                                userEnv.buildExternalStorageAppDataDirs(packageName));
12085                        clearDirectory(conn.mContainerService,
12086                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12087                    }
12088                }
12089            } finally {
12090                mContext.unbindService(conn);
12091            }
12092        }
12093    }
12094
12095    @Override
12096    public void clearApplicationUserData(final String packageName,
12097            final IPackageDataObserver observer, final int userId) {
12098        mContext.enforceCallingOrSelfPermission(
12099                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12100        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12101        // Queue up an async operation since the package deletion may take a little while.
12102        mHandler.post(new Runnable() {
12103            public void run() {
12104                mHandler.removeCallbacks(this);
12105                final boolean succeeded;
12106                synchronized (mInstallLock) {
12107                    succeeded = clearApplicationUserDataLI(packageName, userId);
12108                }
12109                clearExternalStorageDataSync(packageName, userId, true);
12110                if (succeeded) {
12111                    // invoke DeviceStorageMonitor's update method to clear any notifications
12112                    DeviceStorageMonitorInternal
12113                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12114                    if (dsm != null) {
12115                        dsm.checkMemory();
12116                    }
12117                }
12118                if(observer != null) {
12119                    try {
12120                        observer.onRemoveCompleted(packageName, succeeded);
12121                    } catch (RemoteException e) {
12122                        Log.i(TAG, "Observer no longer exists.");
12123                    }
12124                } //end if observer
12125            } //end run
12126        });
12127    }
12128
12129    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12130        if (packageName == null) {
12131            Slog.w(TAG, "Attempt to delete null packageName.");
12132            return false;
12133        }
12134
12135        // Try finding details about the requested package
12136        PackageParser.Package pkg;
12137        synchronized (mPackages) {
12138            pkg = mPackages.get(packageName);
12139            if (pkg == null) {
12140                final PackageSetting ps = mSettings.mPackages.get(packageName);
12141                if (ps != null) {
12142                    pkg = ps.pkg;
12143                }
12144            }
12145        }
12146
12147        if (pkg == null) {
12148            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12149        }
12150
12151        // Always delete data directories for package, even if we found no other
12152        // record of app. This helps users recover from UID mismatches without
12153        // resorting to a full data wipe.
12154        int retCode = mInstaller.clearUserData(packageName, userId);
12155        if (retCode < 0) {
12156            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12157            return false;
12158        }
12159
12160        if (pkg == null) {
12161            return false;
12162        }
12163
12164        if (pkg != null && pkg.applicationInfo != null) {
12165            final int appId = pkg.applicationInfo.uid;
12166            removeKeystoreDataIfNeeded(userId, appId);
12167        }
12168
12169        // Create a native library symlink only if we have native libraries
12170        // and if the native libraries are 32 bit libraries. We do not provide
12171        // this symlink for 64 bit libraries.
12172        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
12173                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12174            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12175            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
12176                Slog.w(TAG, "Failed linking native library dir");
12177                return false;
12178            }
12179        }
12180
12181        return true;
12182    }
12183
12184    /**
12185     * Remove entries from the keystore daemon. Will only remove it if the
12186     * {@code appId} is valid.
12187     */
12188    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12189        if (appId < 0) {
12190            return;
12191        }
12192
12193        final KeyStore keyStore = KeyStore.getInstance();
12194        if (keyStore != null) {
12195            if (userId == UserHandle.USER_ALL) {
12196                for (final int individual : sUserManager.getUserIds()) {
12197                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12198                }
12199            } else {
12200                keyStore.clearUid(UserHandle.getUid(userId, appId));
12201            }
12202        } else {
12203            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12204        }
12205    }
12206
12207    @Override
12208    public void deleteApplicationCacheFiles(final String packageName,
12209            final IPackageDataObserver observer) {
12210        mContext.enforceCallingOrSelfPermission(
12211                android.Manifest.permission.DELETE_CACHE_FILES, null);
12212        // Queue up an async operation since the package deletion may take a little while.
12213        final int userId = UserHandle.getCallingUserId();
12214        mHandler.post(new Runnable() {
12215            public void run() {
12216                mHandler.removeCallbacks(this);
12217                final boolean succeded;
12218                synchronized (mInstallLock) {
12219                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12220                }
12221                clearExternalStorageDataSync(packageName, userId, false);
12222                if(observer != null) {
12223                    try {
12224                        observer.onRemoveCompleted(packageName, succeded);
12225                    } catch (RemoteException e) {
12226                        Log.i(TAG, "Observer no longer exists.");
12227                    }
12228                } //end if observer
12229            } //end run
12230        });
12231    }
12232
12233    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12234        if (packageName == null) {
12235            Slog.w(TAG, "Attempt to delete null packageName.");
12236            return false;
12237        }
12238        PackageParser.Package p;
12239        synchronized (mPackages) {
12240            p = mPackages.get(packageName);
12241        }
12242        if (p == null) {
12243            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12244            return false;
12245        }
12246        final ApplicationInfo applicationInfo = p.applicationInfo;
12247        if (applicationInfo == null) {
12248            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12249            return false;
12250        }
12251        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
12252        if (retCode < 0) {
12253            Slog.w(TAG, "Couldn't remove cache files for package: "
12254                       + packageName + " u" + userId);
12255            return false;
12256        }
12257        return true;
12258    }
12259
12260    @Override
12261    public void getPackageSizeInfo(final String packageName, int userHandle,
12262            final IPackageStatsObserver observer) {
12263        mContext.enforceCallingOrSelfPermission(
12264                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12265        if (packageName == null) {
12266            throw new IllegalArgumentException("Attempt to get size of null packageName");
12267        }
12268
12269        PackageStats stats = new PackageStats(packageName, userHandle);
12270
12271        /*
12272         * Queue up an async operation since the package measurement may take a
12273         * little while.
12274         */
12275        Message msg = mHandler.obtainMessage(INIT_COPY);
12276        msg.obj = new MeasureParams(stats, observer);
12277        mHandler.sendMessage(msg);
12278    }
12279
12280    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12281            PackageStats pStats) {
12282        if (packageName == null) {
12283            Slog.w(TAG, "Attempt to get size of null packageName.");
12284            return false;
12285        }
12286        PackageParser.Package p;
12287        boolean dataOnly = false;
12288        String libDirRoot = null;
12289        String asecPath = null;
12290        PackageSetting ps = null;
12291        synchronized (mPackages) {
12292            p = mPackages.get(packageName);
12293            ps = mSettings.mPackages.get(packageName);
12294            if(p == null) {
12295                dataOnly = true;
12296                if((ps == null) || (ps.pkg == null)) {
12297                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12298                    return false;
12299                }
12300                p = ps.pkg;
12301            }
12302            if (ps != null) {
12303                libDirRoot = ps.legacyNativeLibraryPathString;
12304            }
12305            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12306                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12307                if (secureContainerId != null) {
12308                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12309                }
12310            }
12311        }
12312        String publicSrcDir = null;
12313        if(!dataOnly) {
12314            final ApplicationInfo applicationInfo = p.applicationInfo;
12315            if (applicationInfo == null) {
12316                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12317                return false;
12318            }
12319            if (p.isForwardLocked()) {
12320                publicSrcDir = applicationInfo.getBaseResourcePath();
12321            }
12322        }
12323        // TODO: extend to measure size of split APKs
12324        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12325        // not just the first level.
12326        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12327        // just the primary.
12328        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12329        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
12330                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12331        if (res < 0) {
12332            return false;
12333        }
12334
12335        // Fix-up for forward-locked applications in ASEC containers.
12336        if (!isExternal(p)) {
12337            pStats.codeSize += pStats.externalCodeSize;
12338            pStats.externalCodeSize = 0L;
12339        }
12340
12341        return true;
12342    }
12343
12344
12345    @Override
12346    public void addPackageToPreferred(String packageName) {
12347        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12348    }
12349
12350    @Override
12351    public void removePackageFromPreferred(String packageName) {
12352        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12353    }
12354
12355    @Override
12356    public List<PackageInfo> getPreferredPackages(int flags) {
12357        return new ArrayList<PackageInfo>();
12358    }
12359
12360    private int getUidTargetSdkVersionLockedLPr(int uid) {
12361        Object obj = mSettings.getUserIdLPr(uid);
12362        if (obj instanceof SharedUserSetting) {
12363            final SharedUserSetting sus = (SharedUserSetting) obj;
12364            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12365            final Iterator<PackageSetting> it = sus.packages.iterator();
12366            while (it.hasNext()) {
12367                final PackageSetting ps = it.next();
12368                if (ps.pkg != null) {
12369                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12370                    if (v < vers) vers = v;
12371                }
12372            }
12373            return vers;
12374        } else if (obj instanceof PackageSetting) {
12375            final PackageSetting ps = (PackageSetting) obj;
12376            if (ps.pkg != null) {
12377                return ps.pkg.applicationInfo.targetSdkVersion;
12378            }
12379        }
12380        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12381    }
12382
12383    @Override
12384    public void addPreferredActivity(IntentFilter filter, int match,
12385            ComponentName[] set, ComponentName activity, int userId) {
12386        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12387                "Adding preferred");
12388    }
12389
12390    private void addPreferredActivityInternal(IntentFilter filter, int match,
12391            ComponentName[] set, ComponentName activity, boolean always, int userId,
12392            String opname) {
12393        // writer
12394        int callingUid = Binder.getCallingUid();
12395        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12396        if (filter.countActions() == 0) {
12397            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12398            return;
12399        }
12400        synchronized (mPackages) {
12401            if (mContext.checkCallingOrSelfPermission(
12402                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12403                    != PackageManager.PERMISSION_GRANTED) {
12404                if (getUidTargetSdkVersionLockedLPr(callingUid)
12405                        < Build.VERSION_CODES.FROYO) {
12406                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12407                            + callingUid);
12408                    return;
12409                }
12410                mContext.enforceCallingOrSelfPermission(
12411                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12412            }
12413
12414            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12415            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12416                    + userId + ":");
12417            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12418            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12419            scheduleWritePackageRestrictionsLocked(userId);
12420        }
12421    }
12422
12423    @Override
12424    public void replacePreferredActivity(IntentFilter filter, int match,
12425            ComponentName[] set, ComponentName activity, int userId) {
12426        if (filter.countActions() != 1) {
12427            throw new IllegalArgumentException(
12428                    "replacePreferredActivity expects filter to have only 1 action.");
12429        }
12430        if (filter.countDataAuthorities() != 0
12431                || filter.countDataPaths() != 0
12432                || filter.countDataSchemes() > 1
12433                || filter.countDataTypes() != 0) {
12434            throw new IllegalArgumentException(
12435                    "replacePreferredActivity expects filter to have no data authorities, " +
12436                    "paths, or types; and at most one scheme.");
12437        }
12438
12439        final int callingUid = Binder.getCallingUid();
12440        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12441        synchronized (mPackages) {
12442            if (mContext.checkCallingOrSelfPermission(
12443                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12444                    != PackageManager.PERMISSION_GRANTED) {
12445                if (getUidTargetSdkVersionLockedLPr(callingUid)
12446                        < Build.VERSION_CODES.FROYO) {
12447                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12448                            + Binder.getCallingUid());
12449                    return;
12450                }
12451                mContext.enforceCallingOrSelfPermission(
12452                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12453            }
12454
12455            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12456            if (pir != null) {
12457                // Get all of the existing entries that exactly match this filter.
12458                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
12459                if (existing != null && existing.size() == 1) {
12460                    PreferredActivity cur = existing.get(0);
12461                    if (DEBUG_PREFERRED) {
12462                        Slog.i(TAG, "Checking replace of preferred:");
12463                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12464                        if (!cur.mPref.mAlways) {
12465                            Slog.i(TAG, "  -- CUR; not mAlways!");
12466                        } else {
12467                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
12468                            Slog.i(TAG, "  -- CUR: mSet="
12469                                    + Arrays.toString(cur.mPref.mSetComponents));
12470                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
12471                            Slog.i(TAG, "  -- NEW: mMatch="
12472                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
12473                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
12474                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
12475                        }
12476                    }
12477                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
12478                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
12479                            && cur.mPref.sameSet(set)) {
12480                        // Setting the preferred activity to what it happens to be already
12481                        if (DEBUG_PREFERRED) {
12482                            Slog.i(TAG, "Replacing with same preferred activity "
12483                                    + cur.mPref.mShortComponent + " for user "
12484                                    + userId + ":");
12485                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12486                        }
12487                        return;
12488                    }
12489                }
12490
12491                if (existing != null) {
12492                    if (DEBUG_PREFERRED) {
12493                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
12494                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12495                    }
12496                    for (int i = 0; i < existing.size(); i++) {
12497                        PreferredActivity pa = existing.get(i);
12498                        if (DEBUG_PREFERRED) {
12499                            Slog.i(TAG, "Removing existing preferred activity "
12500                                    + pa.mPref.mComponent + ":");
12501                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
12502                        }
12503                        pir.removeFilter(pa);
12504                    }
12505                }
12506            }
12507            addPreferredActivityInternal(filter, match, set, activity, true, userId,
12508                    "Replacing preferred");
12509        }
12510    }
12511
12512    @Override
12513    public void clearPackagePreferredActivities(String packageName) {
12514        final int uid = Binder.getCallingUid();
12515        // writer
12516        synchronized (mPackages) {
12517            PackageParser.Package pkg = mPackages.get(packageName);
12518            if (pkg == null || pkg.applicationInfo.uid != uid) {
12519                if (mContext.checkCallingOrSelfPermission(
12520                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12521                        != PackageManager.PERMISSION_GRANTED) {
12522                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
12523                            < Build.VERSION_CODES.FROYO) {
12524                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
12525                                + Binder.getCallingUid());
12526                        return;
12527                    }
12528                    mContext.enforceCallingOrSelfPermission(
12529                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12530                }
12531            }
12532
12533            int user = UserHandle.getCallingUserId();
12534            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
12535                scheduleWritePackageRestrictionsLocked(user);
12536            }
12537        }
12538    }
12539
12540    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12541    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
12542        ArrayList<PreferredActivity> removed = null;
12543        boolean changed = false;
12544        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12545            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
12546            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12547            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
12548                continue;
12549            }
12550            Iterator<PreferredActivity> it = pir.filterIterator();
12551            while (it.hasNext()) {
12552                PreferredActivity pa = it.next();
12553                // Mark entry for removal only if it matches the package name
12554                // and the entry is of type "always".
12555                if (packageName == null ||
12556                        (pa.mPref.mComponent.getPackageName().equals(packageName)
12557                                && pa.mPref.mAlways)) {
12558                    if (removed == null) {
12559                        removed = new ArrayList<PreferredActivity>();
12560                    }
12561                    removed.add(pa);
12562                }
12563            }
12564            if (removed != null) {
12565                for (int j=0; j<removed.size(); j++) {
12566                    PreferredActivity pa = removed.get(j);
12567                    pir.removeFilter(pa);
12568                }
12569                changed = true;
12570            }
12571        }
12572        return changed;
12573    }
12574
12575    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12576    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
12577        if (userId == UserHandle.USER_ALL) {
12578            mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds());
12579            for (int oneUserId : sUserManager.getUserIds()) {
12580                scheduleWritePackageRestrictionsLocked(oneUserId);
12581            }
12582        } else {
12583            mSettings.removeIntentFilterVerificationLPw(packageName, userId);
12584            scheduleWritePackageRestrictionsLocked(userId);
12585        }
12586    }
12587
12588    @Override
12589    public void resetPreferredActivities(int userId) {
12590        /* TODO: Actually use userId. Why is it being passed in? */
12591        mContext.enforceCallingOrSelfPermission(
12592                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12593        // writer
12594        synchronized (mPackages) {
12595            int user = UserHandle.getCallingUserId();
12596            clearPackagePreferredActivitiesLPw(null, user);
12597            mSettings.readDefaultPreferredAppsLPw(this, user);
12598            scheduleWritePackageRestrictionsLocked(user);
12599        }
12600    }
12601
12602    @Override
12603    public int getPreferredActivities(List<IntentFilter> outFilters,
12604            List<ComponentName> outActivities, String packageName) {
12605
12606        int num = 0;
12607        final int userId = UserHandle.getCallingUserId();
12608        // reader
12609        synchronized (mPackages) {
12610            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12611            if (pir != null) {
12612                final Iterator<PreferredActivity> it = pir.filterIterator();
12613                while (it.hasNext()) {
12614                    final PreferredActivity pa = it.next();
12615                    if (packageName == null
12616                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
12617                                    && pa.mPref.mAlways)) {
12618                        if (outFilters != null) {
12619                            outFilters.add(new IntentFilter(pa));
12620                        }
12621                        if (outActivities != null) {
12622                            outActivities.add(pa.mPref.mComponent);
12623                        }
12624                    }
12625                }
12626            }
12627        }
12628
12629        return num;
12630    }
12631
12632    @Override
12633    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
12634            int userId) {
12635        int callingUid = Binder.getCallingUid();
12636        if (callingUid != Process.SYSTEM_UID) {
12637            throw new SecurityException(
12638                    "addPersistentPreferredActivity can only be run by the system");
12639        }
12640        if (filter.countActions() == 0) {
12641            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12642            return;
12643        }
12644        synchronized (mPackages) {
12645            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
12646                    " :");
12647            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12648            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
12649                    new PersistentPreferredActivity(filter, activity));
12650            scheduleWritePackageRestrictionsLocked(userId);
12651        }
12652    }
12653
12654    @Override
12655    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
12656        int callingUid = Binder.getCallingUid();
12657        if (callingUid != Process.SYSTEM_UID) {
12658            throw new SecurityException(
12659                    "clearPackagePersistentPreferredActivities can only be run by the system");
12660        }
12661        ArrayList<PersistentPreferredActivity> removed = null;
12662        boolean changed = false;
12663        synchronized (mPackages) {
12664            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
12665                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
12666                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
12667                        .valueAt(i);
12668                if (userId != thisUserId) {
12669                    continue;
12670                }
12671                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
12672                while (it.hasNext()) {
12673                    PersistentPreferredActivity ppa = it.next();
12674                    // Mark entry for removal only if it matches the package name.
12675                    if (ppa.mComponent.getPackageName().equals(packageName)) {
12676                        if (removed == null) {
12677                            removed = new ArrayList<PersistentPreferredActivity>();
12678                        }
12679                        removed.add(ppa);
12680                    }
12681                }
12682                if (removed != null) {
12683                    for (int j=0; j<removed.size(); j++) {
12684                        PersistentPreferredActivity ppa = removed.get(j);
12685                        ppir.removeFilter(ppa);
12686                    }
12687                    changed = true;
12688                }
12689            }
12690
12691            if (changed) {
12692                scheduleWritePackageRestrictionsLocked(userId);
12693            }
12694        }
12695    }
12696
12697    /**
12698     * Non-Binder method, support for the backup/restore mechanism: write the
12699     * full set of preferred activities in its canonical XML format.  Returns true
12700     * on success; false otherwise.
12701     */
12702    @Override
12703    public byte[] getPreferredActivityBackup(int userId) {
12704        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
12705            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
12706        }
12707
12708        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
12709        try {
12710            final XmlSerializer serializer = new FastXmlSerializer();
12711            serializer.setOutput(dataStream, "utf-8");
12712            serializer.startDocument(null, true);
12713            serializer.startTag(null, TAG_PREFERRED_BACKUP);
12714
12715            synchronized (mPackages) {
12716                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
12717            }
12718
12719            serializer.endTag(null, TAG_PREFERRED_BACKUP);
12720            serializer.endDocument();
12721            serializer.flush();
12722        } catch (Exception e) {
12723            if (DEBUG_BACKUP) {
12724                Slog.e(TAG, "Unable to write preferred activities for backup", e);
12725            }
12726            return null;
12727        }
12728
12729        return dataStream.toByteArray();
12730    }
12731
12732    @Override
12733    public void restorePreferredActivities(byte[] backup, int userId) {
12734        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
12735            throw new SecurityException("Only the system may call restorePreferredActivities()");
12736        }
12737
12738        try {
12739            final XmlPullParser parser = Xml.newPullParser();
12740            parser.setInput(new ByteArrayInputStream(backup), null);
12741
12742            int type;
12743            while ((type = parser.next()) != XmlPullParser.START_TAG
12744                    && type != XmlPullParser.END_DOCUMENT) {
12745            }
12746            if (type != XmlPullParser.START_TAG) {
12747                // oops didn't find a start tag?!
12748                if (DEBUG_BACKUP) {
12749                    Slog.e(TAG, "Didn't find start tag during restore");
12750                }
12751                return;
12752            }
12753
12754            // this is supposed to be TAG_PREFERRED_BACKUP
12755            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
12756                if (DEBUG_BACKUP) {
12757                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
12758                }
12759                return;
12760            }
12761
12762            // skip interfering stuff, then we're aligned with the backing implementation
12763            while ((type = parser.next()) == XmlPullParser.TEXT) { }
12764            synchronized (mPackages) {
12765                mSettings.readPreferredActivitiesLPw(parser, userId);
12766            }
12767        } catch (Exception e) {
12768            if (DEBUG_BACKUP) {
12769                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
12770            }
12771        }
12772    }
12773
12774    @Override
12775    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
12776            int sourceUserId, int targetUserId, int flags) {
12777        mContext.enforceCallingOrSelfPermission(
12778                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12779        int callingUid = Binder.getCallingUid();
12780        enforceOwnerRights(ownerPackage, callingUid);
12781        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12782        if (intentFilter.countActions() == 0) {
12783            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
12784            return;
12785        }
12786        synchronized (mPackages) {
12787            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
12788                    ownerPackage, targetUserId, flags);
12789            CrossProfileIntentResolver resolver =
12790                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12791            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
12792            // We have all those whose filter is equal. Now checking if the rest is equal as well.
12793            if (existing != null) {
12794                int size = existing.size();
12795                for (int i = 0; i < size; i++) {
12796                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
12797                        return;
12798                    }
12799                }
12800            }
12801            resolver.addFilter(newFilter);
12802            scheduleWritePackageRestrictionsLocked(sourceUserId);
12803        }
12804    }
12805
12806    @Override
12807    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
12808        mContext.enforceCallingOrSelfPermission(
12809                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12810        int callingUid = Binder.getCallingUid();
12811        enforceOwnerRights(ownerPackage, callingUid);
12812        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12813        synchronized (mPackages) {
12814            CrossProfileIntentResolver resolver =
12815                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12816            ArraySet<CrossProfileIntentFilter> set =
12817                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
12818            for (CrossProfileIntentFilter filter : set) {
12819                if (filter.getOwnerPackage().equals(ownerPackage)) {
12820                    resolver.removeFilter(filter);
12821                }
12822            }
12823            scheduleWritePackageRestrictionsLocked(sourceUserId);
12824        }
12825    }
12826
12827    // Enforcing that callingUid is owning pkg on userId
12828    private void enforceOwnerRights(String pkg, int callingUid) {
12829        // The system owns everything.
12830        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
12831            return;
12832        }
12833        int callingUserId = UserHandle.getUserId(callingUid);
12834        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
12835        if (pi == null) {
12836            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
12837                    + callingUserId);
12838        }
12839        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
12840            throw new SecurityException("Calling uid " + callingUid
12841                    + " does not own package " + pkg);
12842        }
12843    }
12844
12845    @Override
12846    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
12847        Intent intent = new Intent(Intent.ACTION_MAIN);
12848        intent.addCategory(Intent.CATEGORY_HOME);
12849
12850        final int callingUserId = UserHandle.getCallingUserId();
12851        List<ResolveInfo> list = queryIntentActivities(intent, null,
12852                PackageManager.GET_META_DATA, callingUserId);
12853        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
12854                true, false, false, callingUserId);
12855
12856        allHomeCandidates.clear();
12857        if (list != null) {
12858            for (ResolveInfo ri : list) {
12859                allHomeCandidates.add(ri);
12860            }
12861        }
12862        return (preferred == null || preferred.activityInfo == null)
12863                ? null
12864                : new ComponentName(preferred.activityInfo.packageName,
12865                        preferred.activityInfo.name);
12866    }
12867
12868    @Override
12869    public void setApplicationEnabledSetting(String appPackageName,
12870            int newState, int flags, int userId, String callingPackage) {
12871        if (!sUserManager.exists(userId)) return;
12872        if (callingPackage == null) {
12873            callingPackage = Integer.toString(Binder.getCallingUid());
12874        }
12875        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
12876    }
12877
12878    @Override
12879    public void setComponentEnabledSetting(ComponentName componentName,
12880            int newState, int flags, int userId) {
12881        if (!sUserManager.exists(userId)) return;
12882        setEnabledSetting(componentName.getPackageName(),
12883                componentName.getClassName(), newState, flags, userId, null);
12884    }
12885
12886    private void setEnabledSetting(final String packageName, String className, int newState,
12887            final int flags, int userId, String callingPackage) {
12888        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
12889              || newState == COMPONENT_ENABLED_STATE_ENABLED
12890              || newState == COMPONENT_ENABLED_STATE_DISABLED
12891              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
12892              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
12893            throw new IllegalArgumentException("Invalid new component state: "
12894                    + newState);
12895        }
12896        PackageSetting pkgSetting;
12897        final int uid = Binder.getCallingUid();
12898        final int permission = mContext.checkCallingOrSelfPermission(
12899                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12900        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
12901        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12902        boolean sendNow = false;
12903        boolean isApp = (className == null);
12904        String componentName = isApp ? packageName : className;
12905        int packageUid = -1;
12906        ArrayList<String> components;
12907
12908        // writer
12909        synchronized (mPackages) {
12910            pkgSetting = mSettings.mPackages.get(packageName);
12911            if (pkgSetting == null) {
12912                if (className == null) {
12913                    throw new IllegalArgumentException(
12914                            "Unknown package: " + packageName);
12915                }
12916                throw new IllegalArgumentException(
12917                        "Unknown component: " + packageName
12918                        + "/" + className);
12919            }
12920            // Allow root and verify that userId is not being specified by a different user
12921            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
12922                throw new SecurityException(
12923                        "Permission Denial: attempt to change component state from pid="
12924                        + Binder.getCallingPid()
12925                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
12926            }
12927            if (className == null) {
12928                // We're dealing with an application/package level state change
12929                if (pkgSetting.getEnabled(userId) == newState) {
12930                    // Nothing to do
12931                    return;
12932                }
12933                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
12934                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
12935                    // Don't care about who enables an app.
12936                    callingPackage = null;
12937                }
12938                pkgSetting.setEnabled(newState, userId, callingPackage);
12939                // pkgSetting.pkg.mSetEnabled = newState;
12940            } else {
12941                // We're dealing with a component level state change
12942                // First, verify that this is a valid class name.
12943                PackageParser.Package pkg = pkgSetting.pkg;
12944                if (pkg == null || !pkg.hasComponentClassName(className)) {
12945                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
12946                        throw new IllegalArgumentException("Component class " + className
12947                                + " does not exist in " + packageName);
12948                    } else {
12949                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
12950                                + className + " does not exist in " + packageName);
12951                    }
12952                }
12953                switch (newState) {
12954                case COMPONENT_ENABLED_STATE_ENABLED:
12955                    if (!pkgSetting.enableComponentLPw(className, userId)) {
12956                        return;
12957                    }
12958                    break;
12959                case COMPONENT_ENABLED_STATE_DISABLED:
12960                    if (!pkgSetting.disableComponentLPw(className, userId)) {
12961                        return;
12962                    }
12963                    break;
12964                case COMPONENT_ENABLED_STATE_DEFAULT:
12965                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
12966                        return;
12967                    }
12968                    break;
12969                default:
12970                    Slog.e(TAG, "Invalid new component state: " + newState);
12971                    return;
12972                }
12973            }
12974            scheduleWritePackageRestrictionsLocked(userId);
12975            components = mPendingBroadcasts.get(userId, packageName);
12976            final boolean newPackage = components == null;
12977            if (newPackage) {
12978                components = new ArrayList<String>();
12979            }
12980            if (!components.contains(componentName)) {
12981                components.add(componentName);
12982            }
12983            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12984                sendNow = true;
12985                // Purge entry from pending broadcast list if another one exists already
12986                // since we are sending one right away.
12987                mPendingBroadcasts.remove(userId, packageName);
12988            } else {
12989                if (newPackage) {
12990                    mPendingBroadcasts.put(userId, packageName, components);
12991                }
12992                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12993                    // Schedule a message
12994                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12995                }
12996            }
12997        }
12998
12999        long callingId = Binder.clearCallingIdentity();
13000        try {
13001            if (sendNow) {
13002                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13003                sendPackageChangedBroadcast(packageName,
13004                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13005            }
13006        } finally {
13007            Binder.restoreCallingIdentity(callingId);
13008        }
13009    }
13010
13011    private void sendPackageChangedBroadcast(String packageName,
13012            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13013        if (DEBUG_INSTALL)
13014            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13015                    + componentNames);
13016        Bundle extras = new Bundle(4);
13017        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13018        String nameList[] = new String[componentNames.size()];
13019        componentNames.toArray(nameList);
13020        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13021        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13022        extras.putInt(Intent.EXTRA_UID, packageUid);
13023        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13024                new int[] {UserHandle.getUserId(packageUid)});
13025    }
13026
13027    @Override
13028    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13029        if (!sUserManager.exists(userId)) return;
13030        final int uid = Binder.getCallingUid();
13031        final int permission = mContext.checkCallingOrSelfPermission(
13032                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13033        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13034        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13035        // writer
13036        synchronized (mPackages) {
13037            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
13038                    uid, userId)) {
13039                scheduleWritePackageRestrictionsLocked(userId);
13040            }
13041        }
13042    }
13043
13044    @Override
13045    public String getInstallerPackageName(String packageName) {
13046        // reader
13047        synchronized (mPackages) {
13048            return mSettings.getInstallerPackageNameLPr(packageName);
13049        }
13050    }
13051
13052    @Override
13053    public int getApplicationEnabledSetting(String packageName, int userId) {
13054        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13055        int uid = Binder.getCallingUid();
13056        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13057        // reader
13058        synchronized (mPackages) {
13059            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13060        }
13061    }
13062
13063    @Override
13064    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13065        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13066        int uid = Binder.getCallingUid();
13067        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13068        // reader
13069        synchronized (mPackages) {
13070            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13071        }
13072    }
13073
13074    @Override
13075    public void enterSafeMode() {
13076        enforceSystemOrRoot("Only the system can request entering safe mode");
13077
13078        if (!mSystemReady) {
13079            mSafeMode = true;
13080        }
13081    }
13082
13083    @Override
13084    public void systemReady() {
13085        mSystemReady = true;
13086
13087        // Read the compatibilty setting when the system is ready.
13088        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13089                mContext.getContentResolver(),
13090                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13091        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13092        if (DEBUG_SETTINGS) {
13093            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13094        }
13095
13096        synchronized (mPackages) {
13097            // Verify that all of the preferred activity components actually
13098            // exist.  It is possible for applications to be updated and at
13099            // that point remove a previously declared activity component that
13100            // had been set as a preferred activity.  We try to clean this up
13101            // the next time we encounter that preferred activity, but it is
13102            // possible for the user flow to never be able to return to that
13103            // situation so here we do a sanity check to make sure we haven't
13104            // left any junk around.
13105            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13106            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13107                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13108                removed.clear();
13109                for (PreferredActivity pa : pir.filterSet()) {
13110                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13111                        removed.add(pa);
13112                    }
13113                }
13114                if (removed.size() > 0) {
13115                    for (int r=0; r<removed.size(); r++) {
13116                        PreferredActivity pa = removed.get(r);
13117                        Slog.w(TAG, "Removing dangling preferred activity: "
13118                                + pa.mPref.mComponent);
13119                        pir.removeFilter(pa);
13120                    }
13121                    mSettings.writePackageRestrictionsLPr(
13122                            mSettings.mPreferredActivities.keyAt(i));
13123                }
13124            }
13125        }
13126        sUserManager.systemReady();
13127
13128        // Kick off any messages waiting for system ready
13129        if (mPostSystemReadyMessages != null) {
13130            for (Message msg : mPostSystemReadyMessages) {
13131                msg.sendToTarget();
13132            }
13133            mPostSystemReadyMessages = null;
13134        }
13135
13136        // Watch for external volumes that come and go over time
13137        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13138        storage.registerListener(mStorageListener);
13139
13140        mInstallerService.systemReady();
13141    }
13142
13143    @Override
13144    public boolean isSafeMode() {
13145        return mSafeMode;
13146    }
13147
13148    @Override
13149    public boolean hasSystemUidErrors() {
13150        return mHasSystemUidErrors;
13151    }
13152
13153    static String arrayToString(int[] array) {
13154        StringBuffer buf = new StringBuffer(128);
13155        buf.append('[');
13156        if (array != null) {
13157            for (int i=0; i<array.length; i++) {
13158                if (i > 0) buf.append(", ");
13159                buf.append(array[i]);
13160            }
13161        }
13162        buf.append(']');
13163        return buf.toString();
13164    }
13165
13166    static class DumpState {
13167        public static final int DUMP_LIBS = 1 << 0;
13168        public static final int DUMP_FEATURES = 1 << 1;
13169        public static final int DUMP_RESOLVERS = 1 << 2;
13170        public static final int DUMP_PERMISSIONS = 1 << 3;
13171        public static final int DUMP_PACKAGES = 1 << 4;
13172        public static final int DUMP_SHARED_USERS = 1 << 5;
13173        public static final int DUMP_MESSAGES = 1 << 6;
13174        public static final int DUMP_PROVIDERS = 1 << 7;
13175        public static final int DUMP_VERIFIERS = 1 << 8;
13176        public static final int DUMP_PREFERRED = 1 << 9;
13177        public static final int DUMP_PREFERRED_XML = 1 << 10;
13178        public static final int DUMP_KEYSETS = 1 << 11;
13179        public static final int DUMP_VERSION = 1 << 12;
13180        public static final int DUMP_INSTALLS = 1 << 13;
13181        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13182        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13183
13184        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13185
13186        private int mTypes;
13187
13188        private int mOptions;
13189
13190        private boolean mTitlePrinted;
13191
13192        private SharedUserSetting mSharedUser;
13193
13194        public boolean isDumping(int type) {
13195            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13196                return true;
13197            }
13198
13199            return (mTypes & type) != 0;
13200        }
13201
13202        public void setDump(int type) {
13203            mTypes |= type;
13204        }
13205
13206        public boolean isOptionEnabled(int option) {
13207            return (mOptions & option) != 0;
13208        }
13209
13210        public void setOptionEnabled(int option) {
13211            mOptions |= option;
13212        }
13213
13214        public boolean onTitlePrinted() {
13215            final boolean printed = mTitlePrinted;
13216            mTitlePrinted = true;
13217            return printed;
13218        }
13219
13220        public boolean getTitlePrinted() {
13221            return mTitlePrinted;
13222        }
13223
13224        public void setTitlePrinted(boolean enabled) {
13225            mTitlePrinted = enabled;
13226        }
13227
13228        public SharedUserSetting getSharedUser() {
13229            return mSharedUser;
13230        }
13231
13232        public void setSharedUser(SharedUserSetting user) {
13233            mSharedUser = user;
13234        }
13235    }
13236
13237    @Override
13238    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13239        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13240                != PackageManager.PERMISSION_GRANTED) {
13241            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13242                    + Binder.getCallingPid()
13243                    + ", uid=" + Binder.getCallingUid()
13244                    + " without permission "
13245                    + android.Manifest.permission.DUMP);
13246            return;
13247        }
13248
13249        DumpState dumpState = new DumpState();
13250        boolean fullPreferred = false;
13251        boolean checkin = false;
13252
13253        String packageName = null;
13254
13255        int opti = 0;
13256        while (opti < args.length) {
13257            String opt = args[opti];
13258            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13259                break;
13260            }
13261            opti++;
13262
13263            if ("-a".equals(opt)) {
13264                // Right now we only know how to print all.
13265            } else if ("-h".equals(opt)) {
13266                pw.println("Package manager dump options:");
13267                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13268                pw.println("    --checkin: dump for a checkin");
13269                pw.println("    -f: print details of intent filters");
13270                pw.println("    -h: print this help");
13271                pw.println("  cmd may be one of:");
13272                pw.println("    l[ibraries]: list known shared libraries");
13273                pw.println("    f[ibraries]: list device features");
13274                pw.println("    k[eysets]: print known keysets");
13275                pw.println("    r[esolvers]: dump intent resolvers");
13276                pw.println("    perm[issions]: dump permissions");
13277                pw.println("    pref[erred]: print preferred package settings");
13278                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13279                pw.println("    prov[iders]: dump content providers");
13280                pw.println("    p[ackages]: dump installed packages");
13281                pw.println("    s[hared-users]: dump shared user IDs");
13282                pw.println("    m[essages]: print collected runtime messages");
13283                pw.println("    v[erifiers]: print package verifier info");
13284                pw.println("    version: print database version info");
13285                pw.println("    write: write current settings now");
13286                pw.println("    <package.name>: info about given package");
13287                pw.println("    installs: details about install sessions");
13288                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13289                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13290                return;
13291            } else if ("--checkin".equals(opt)) {
13292                checkin = true;
13293            } else if ("-f".equals(opt)) {
13294                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13295            } else {
13296                pw.println("Unknown argument: " + opt + "; use -h for help");
13297            }
13298        }
13299
13300        // Is the caller requesting to dump a particular piece of data?
13301        if (opti < args.length) {
13302            String cmd = args[opti];
13303            opti++;
13304            // Is this a package name?
13305            if ("android".equals(cmd) || cmd.contains(".")) {
13306                packageName = cmd;
13307                // When dumping a single package, we always dump all of its
13308                // filter information since the amount of data will be reasonable.
13309                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13310            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13311                dumpState.setDump(DumpState.DUMP_LIBS);
13312            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13313                dumpState.setDump(DumpState.DUMP_FEATURES);
13314            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13315                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13316            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13317                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13318            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13319                dumpState.setDump(DumpState.DUMP_PREFERRED);
13320            } else if ("preferred-xml".equals(cmd)) {
13321                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13322                if (opti < args.length && "--full".equals(args[opti])) {
13323                    fullPreferred = true;
13324                    opti++;
13325                }
13326            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13327                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13328            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13329                dumpState.setDump(DumpState.DUMP_PACKAGES);
13330            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13331                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13332            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13333                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13334            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13335                dumpState.setDump(DumpState.DUMP_MESSAGES);
13336            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13337                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13338            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13339                    || "intent-filter-verifiers".equals(cmd)) {
13340                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13341            } else if ("version".equals(cmd)) {
13342                dumpState.setDump(DumpState.DUMP_VERSION);
13343            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13344                dumpState.setDump(DumpState.DUMP_KEYSETS);
13345            } else if ("installs".equals(cmd)) {
13346                dumpState.setDump(DumpState.DUMP_INSTALLS);
13347            } else if ("write".equals(cmd)) {
13348                synchronized (mPackages) {
13349                    mSettings.writeLPr();
13350                    pw.println("Settings written.");
13351                    return;
13352                }
13353            }
13354        }
13355
13356        if (checkin) {
13357            pw.println("vers,1");
13358        }
13359
13360        // reader
13361        synchronized (mPackages) {
13362            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13363                if (!checkin) {
13364                    if (dumpState.onTitlePrinted())
13365                        pw.println();
13366                    pw.println("Database versions:");
13367                    pw.print("  SDK Version:");
13368                    pw.print(" internal=");
13369                    pw.print(mSettings.mInternalSdkPlatform);
13370                    pw.print(" external=");
13371                    pw.println(mSettings.mExternalSdkPlatform);
13372                    pw.print("  DB Version:");
13373                    pw.print(" internal=");
13374                    pw.print(mSettings.mInternalDatabaseVersion);
13375                    pw.print(" external=");
13376                    pw.println(mSettings.mExternalDatabaseVersion);
13377                }
13378            }
13379
13380            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13381                if (!checkin) {
13382                    if (dumpState.onTitlePrinted())
13383                        pw.println();
13384                    pw.println("Verifiers:");
13385                    pw.print("  Required: ");
13386                    pw.print(mRequiredVerifierPackage);
13387                    pw.print(" (uid=");
13388                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13389                    pw.println(")");
13390                } else if (mRequiredVerifierPackage != null) {
13391                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13392                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13393                }
13394            }
13395
13396            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13397                    packageName == null) {
13398                if (mIntentFilterVerifierComponent != null) {
13399                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13400                    if (!checkin) {
13401                        if (dumpState.onTitlePrinted())
13402                            pw.println();
13403                        pw.println("Intent Filter Verifier:");
13404                        pw.print("  Using: ");
13405                        pw.print(verifierPackageName);
13406                        pw.print(" (uid=");
13407                        pw.print(getPackageUid(verifierPackageName, 0));
13408                        pw.println(")");
13409                    } else if (verifierPackageName != null) {
13410                        pw.print("ifv,"); pw.print(verifierPackageName);
13411                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13412                    }
13413                } else {
13414                    pw.println();
13415                    pw.println("No Intent Filter Verifier available!");
13416                }
13417            }
13418
13419            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13420                boolean printedHeader = false;
13421                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13422                while (it.hasNext()) {
13423                    String name = it.next();
13424                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13425                    if (!checkin) {
13426                        if (!printedHeader) {
13427                            if (dumpState.onTitlePrinted())
13428                                pw.println();
13429                            pw.println("Libraries:");
13430                            printedHeader = true;
13431                        }
13432                        pw.print("  ");
13433                    } else {
13434                        pw.print("lib,");
13435                    }
13436                    pw.print(name);
13437                    if (!checkin) {
13438                        pw.print(" -> ");
13439                    }
13440                    if (ent.path != null) {
13441                        if (!checkin) {
13442                            pw.print("(jar) ");
13443                            pw.print(ent.path);
13444                        } else {
13445                            pw.print(",jar,");
13446                            pw.print(ent.path);
13447                        }
13448                    } else {
13449                        if (!checkin) {
13450                            pw.print("(apk) ");
13451                            pw.print(ent.apk);
13452                        } else {
13453                            pw.print(",apk,");
13454                            pw.print(ent.apk);
13455                        }
13456                    }
13457                    pw.println();
13458                }
13459            }
13460
13461            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
13462                if (dumpState.onTitlePrinted())
13463                    pw.println();
13464                if (!checkin) {
13465                    pw.println("Features:");
13466                }
13467                Iterator<String> it = mAvailableFeatures.keySet().iterator();
13468                while (it.hasNext()) {
13469                    String name = it.next();
13470                    if (!checkin) {
13471                        pw.print("  ");
13472                    } else {
13473                        pw.print("feat,");
13474                    }
13475                    pw.println(name);
13476                }
13477            }
13478
13479            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
13480                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
13481                        : "Activity Resolver Table:", "  ", packageName,
13482                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13483                    dumpState.setTitlePrinted(true);
13484                }
13485                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
13486                        : "Receiver Resolver Table:", "  ", packageName,
13487                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13488                    dumpState.setTitlePrinted(true);
13489                }
13490                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
13491                        : "Service Resolver Table:", "  ", packageName,
13492                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13493                    dumpState.setTitlePrinted(true);
13494                }
13495                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
13496                        : "Provider Resolver Table:", "  ", packageName,
13497                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13498                    dumpState.setTitlePrinted(true);
13499                }
13500            }
13501
13502            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
13503                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13504                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13505                    int user = mSettings.mPreferredActivities.keyAt(i);
13506                    if (pir.dump(pw,
13507                            dumpState.getTitlePrinted()
13508                                ? "\nPreferred Activities User " + user + ":"
13509                                : "Preferred Activities User " + user + ":", "  ",
13510                            packageName, true, false)) {
13511                        dumpState.setTitlePrinted(true);
13512                    }
13513                }
13514            }
13515
13516            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
13517                pw.flush();
13518                FileOutputStream fout = new FileOutputStream(fd);
13519                BufferedOutputStream str = new BufferedOutputStream(fout);
13520                XmlSerializer serializer = new FastXmlSerializer();
13521                try {
13522                    serializer.setOutput(str, "utf-8");
13523                    serializer.startDocument(null, true);
13524                    serializer.setFeature(
13525                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
13526                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
13527                    serializer.endDocument();
13528                    serializer.flush();
13529                } catch (IllegalArgumentException e) {
13530                    pw.println("Failed writing: " + e);
13531                } catch (IllegalStateException e) {
13532                    pw.println("Failed writing: " + e);
13533                } catch (IOException e) {
13534                    pw.println("Failed writing: " + e);
13535                }
13536            }
13537
13538            if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) {
13539                pw.println();
13540                int count = mSettings.mPackages.size();
13541                if (count == 0) {
13542                    pw.println("No domain preferred apps!");
13543                    pw.println();
13544                } else {
13545                    final String prefix = "  ";
13546                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
13547                    if (allPackageSettings.size() == 0) {
13548                        pw.println("No domain preferred apps!");
13549                        pw.println();
13550                    } else {
13551                        pw.println("Domain preferred apps status:");
13552                        pw.println();
13553                        count = 0;
13554                        for (PackageSetting ps : allPackageSettings) {
13555                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13556                            if (ivi == null || ivi.getPackageName() == null) continue;
13557                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
13558                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
13559                            pw.println(prefix + "Status: " + ivi.getStatusString());
13560                            pw.println();
13561                            count++;
13562                        }
13563                        if (count == 0) {
13564                            pw.println(prefix + "No domain preferred app status!");
13565                            pw.println();
13566                        }
13567                        for (int userId : sUserManager.getUserIds()) {
13568                            pw.println("Domain preferred apps for User " + userId + ":");
13569                            pw.println();
13570                            count = 0;
13571                            for (PackageSetting ps : allPackageSettings) {
13572                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13573                                if (ivi == null || ivi.getPackageName() == null) {
13574                                    continue;
13575                                }
13576                                final int status = ps.getDomainVerificationStatusForUser(userId);
13577                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
13578                                    continue;
13579                                }
13580                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
13581                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
13582                                String statusStr = IntentFilterVerificationInfo.
13583                                        getStatusStringFromValue(status);
13584                                pw.println(prefix + "Status: " + statusStr);
13585                                pw.println();
13586                                count++;
13587                            }
13588                            if (count == 0) {
13589                                pw.println(prefix + "No domain preferred apps!");
13590                                pw.println();
13591                            }
13592                        }
13593                    }
13594                }
13595            }
13596
13597            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
13598                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
13599                if (packageName == null) {
13600                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
13601                        if (iperm == 0) {
13602                            if (dumpState.onTitlePrinted())
13603                                pw.println();
13604                            pw.println("AppOp Permissions:");
13605                        }
13606                        pw.print("  AppOp Permission ");
13607                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
13608                        pw.println(":");
13609                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
13610                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
13611                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
13612                        }
13613                    }
13614                }
13615            }
13616
13617            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
13618                boolean printedSomething = false;
13619                for (PackageParser.Provider p : mProviders.mProviders.values()) {
13620                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13621                        continue;
13622                    }
13623                    if (!printedSomething) {
13624                        if (dumpState.onTitlePrinted())
13625                            pw.println();
13626                        pw.println("Registered ContentProviders:");
13627                        printedSomething = true;
13628                    }
13629                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
13630                    pw.print("    "); pw.println(p.toString());
13631                }
13632                printedSomething = false;
13633                for (Map.Entry<String, PackageParser.Provider> entry :
13634                        mProvidersByAuthority.entrySet()) {
13635                    PackageParser.Provider p = entry.getValue();
13636                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13637                        continue;
13638                    }
13639                    if (!printedSomething) {
13640                        if (dumpState.onTitlePrinted())
13641                            pw.println();
13642                        pw.println("ContentProvider Authorities:");
13643                        printedSomething = true;
13644                    }
13645                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
13646                    pw.print("    "); pw.println(p.toString());
13647                    if (p.info != null && p.info.applicationInfo != null) {
13648                        final String appInfo = p.info.applicationInfo.toString();
13649                        pw.print("      applicationInfo="); pw.println(appInfo);
13650                    }
13651                }
13652            }
13653
13654            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
13655                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
13656            }
13657
13658            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
13659                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
13660            }
13661
13662            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
13663                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
13664            }
13665
13666            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
13667                // XXX should handle packageName != null by dumping only install data that
13668                // the given package is involved with.
13669                if (dumpState.onTitlePrinted()) pw.println();
13670                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
13671            }
13672
13673            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
13674                if (dumpState.onTitlePrinted()) pw.println();
13675                mSettings.dumpReadMessagesLPr(pw, dumpState);
13676
13677                pw.println();
13678                pw.println("Package warning messages:");
13679                BufferedReader in = null;
13680                String line = null;
13681                try {
13682                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
13683                    while ((line = in.readLine()) != null) {
13684                        if (line.contains("ignored: updated version")) continue;
13685                        pw.println(line);
13686                    }
13687                } catch (IOException ignored) {
13688                } finally {
13689                    IoUtils.closeQuietly(in);
13690                }
13691            }
13692
13693            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
13694                BufferedReader in = null;
13695                String line = null;
13696                try {
13697                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
13698                    while ((line = in.readLine()) != null) {
13699                        if (line.contains("ignored: updated version")) continue;
13700                        pw.print("msg,");
13701                        pw.println(line);
13702                    }
13703                } catch (IOException ignored) {
13704                } finally {
13705                    IoUtils.closeQuietly(in);
13706                }
13707            }
13708        }
13709    }
13710
13711    // ------- apps on sdcard specific code -------
13712    static final boolean DEBUG_SD_INSTALL = false;
13713
13714    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
13715
13716    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
13717
13718    private boolean mMediaMounted = false;
13719
13720    static String getEncryptKey() {
13721        try {
13722            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
13723                    SD_ENCRYPTION_KEYSTORE_NAME);
13724            if (sdEncKey == null) {
13725                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
13726                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
13727                if (sdEncKey == null) {
13728                    Slog.e(TAG, "Failed to create encryption keys");
13729                    return null;
13730                }
13731            }
13732            return sdEncKey;
13733        } catch (NoSuchAlgorithmException nsae) {
13734            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
13735            return null;
13736        } catch (IOException ioe) {
13737            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
13738            return null;
13739        }
13740    }
13741
13742    /*
13743     * Update media status on PackageManager.
13744     */
13745    @Override
13746    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
13747        int callingUid = Binder.getCallingUid();
13748        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
13749            throw new SecurityException("Media status can only be updated by the system");
13750        }
13751        // reader; this apparently protects mMediaMounted, but should probably
13752        // be a different lock in that case.
13753        synchronized (mPackages) {
13754            Log.i(TAG, "Updating external media status from "
13755                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
13756                    + (mediaStatus ? "mounted" : "unmounted"));
13757            if (DEBUG_SD_INSTALL)
13758                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
13759                        + ", mMediaMounted=" + mMediaMounted);
13760            if (mediaStatus == mMediaMounted) {
13761                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
13762                        : 0, -1);
13763                mHandler.sendMessage(msg);
13764                return;
13765            }
13766            mMediaMounted = mediaStatus;
13767        }
13768        // Queue up an async operation since the package installation may take a
13769        // little while.
13770        mHandler.post(new Runnable() {
13771            public void run() {
13772                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
13773            }
13774        });
13775    }
13776
13777    /**
13778     * Called by MountService when the initial ASECs to scan are available.
13779     * Should block until all the ASEC containers are finished being scanned.
13780     */
13781    public void scanAvailableAsecs() {
13782        updateExternalMediaStatusInner(true, false, false);
13783        if (mShouldRestoreconData) {
13784            SELinuxMMAC.setRestoreconDone();
13785            mShouldRestoreconData = false;
13786        }
13787    }
13788
13789    /*
13790     * Collect information of applications on external media, map them against
13791     * existing containers and update information based on current mount status.
13792     * Please note that we always have to report status if reportStatus has been
13793     * set to true especially when unloading packages.
13794     */
13795    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
13796            boolean externalStorage) {
13797        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
13798        int[] uidArr = EmptyArray.INT;
13799
13800        final String[] list = PackageHelper.getSecureContainerList();
13801        if (ArrayUtils.isEmpty(list)) {
13802            Log.i(TAG, "No secure containers found");
13803        } else {
13804            // Process list of secure containers and categorize them
13805            // as active or stale based on their package internal state.
13806
13807            // reader
13808            synchronized (mPackages) {
13809                for (String cid : list) {
13810                    // Leave stages untouched for now; installer service owns them
13811                    if (PackageInstallerService.isStageName(cid)) continue;
13812
13813                    if (DEBUG_SD_INSTALL)
13814                        Log.i(TAG, "Processing container " + cid);
13815                    String pkgName = getAsecPackageName(cid);
13816                    if (pkgName == null) {
13817                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
13818                        continue;
13819                    }
13820                    if (DEBUG_SD_INSTALL)
13821                        Log.i(TAG, "Looking for pkg : " + pkgName);
13822
13823                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
13824                    if (ps == null) {
13825                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
13826                        continue;
13827                    }
13828
13829                    /*
13830                     * Skip packages that are not external if we're unmounting
13831                     * external storage.
13832                     */
13833                    if (externalStorage && !isMounted && !isExternal(ps)) {
13834                        continue;
13835                    }
13836
13837                    final AsecInstallArgs args = new AsecInstallArgs(cid,
13838                            getAppDexInstructionSets(ps), ps.isForwardLocked());
13839                    // The package status is changed only if the code path
13840                    // matches between settings and the container id.
13841                    if (ps.codePathString != null
13842                            && ps.codePathString.startsWith(args.getCodePath())) {
13843                        if (DEBUG_SD_INSTALL) {
13844                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
13845                                    + " at code path: " + ps.codePathString);
13846                        }
13847
13848                        // We do have a valid package installed on sdcard
13849                        processCids.put(args, ps.codePathString);
13850                        final int uid = ps.appId;
13851                        if (uid != -1) {
13852                            uidArr = ArrayUtils.appendInt(uidArr, uid);
13853                        }
13854                    } else {
13855                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
13856                                + ps.codePathString);
13857                    }
13858                }
13859            }
13860
13861            Arrays.sort(uidArr);
13862        }
13863
13864        // Process packages with valid entries.
13865        if (isMounted) {
13866            if (DEBUG_SD_INSTALL)
13867                Log.i(TAG, "Loading packages");
13868            loadMediaPackages(processCids, uidArr);
13869            startCleaningPackages();
13870            mInstallerService.onSecureContainersAvailable();
13871        } else {
13872            if (DEBUG_SD_INSTALL)
13873                Log.i(TAG, "Unloading packages");
13874            unloadMediaPackages(processCids, uidArr, reportStatus);
13875        }
13876    }
13877
13878    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13879            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
13880        final int size = infos.size();
13881        final String[] packageNames = new String[size];
13882        final int[] packageUids = new int[size];
13883        for (int i = 0; i < size; i++) {
13884            final ApplicationInfo info = infos.get(i);
13885            packageNames[i] = info.packageName;
13886            packageUids[i] = info.uid;
13887        }
13888        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
13889                finishedReceiver);
13890    }
13891
13892    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13893            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
13894        sendResourcesChangedBroadcast(mediaStatus, replacing,
13895                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
13896    }
13897
13898    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13899            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
13900        int size = pkgList.length;
13901        if (size > 0) {
13902            // Send broadcasts here
13903            Bundle extras = new Bundle();
13904            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13905            if (uidArr != null) {
13906                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
13907            }
13908            if (replacing) {
13909                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
13910            }
13911            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
13912                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
13913            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
13914        }
13915    }
13916
13917   /*
13918     * Look at potentially valid container ids from processCids If package
13919     * information doesn't match the one on record or package scanning fails,
13920     * the cid is added to list of removeCids. We currently don't delete stale
13921     * containers.
13922     */
13923    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
13924        ArrayList<String> pkgList = new ArrayList<String>();
13925        Set<AsecInstallArgs> keys = processCids.keySet();
13926
13927        for (AsecInstallArgs args : keys) {
13928            String codePath = processCids.get(args);
13929            if (DEBUG_SD_INSTALL)
13930                Log.i(TAG, "Loading container : " + args.cid);
13931            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13932            try {
13933                // Make sure there are no container errors first.
13934                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
13935                    Slog.e(TAG, "Failed to mount cid : " + args.cid
13936                            + " when installing from sdcard");
13937                    continue;
13938                }
13939                // Check code path here.
13940                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
13941                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
13942                            + " does not match one in settings " + codePath);
13943                    continue;
13944                }
13945                // Parse package
13946                int parseFlags = mDefParseFlags;
13947                if (args.isExternalAsec()) {
13948                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
13949                }
13950                if (args.isFwdLocked()) {
13951                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
13952                }
13953
13954                synchronized (mInstallLock) {
13955                    PackageParser.Package pkg = null;
13956                    try {
13957                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
13958                    } catch (PackageManagerException e) {
13959                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
13960                    }
13961                    // Scan the package
13962                    if (pkg != null) {
13963                        /*
13964                         * TODO why is the lock being held? doPostInstall is
13965                         * called in other places without the lock. This needs
13966                         * to be straightened out.
13967                         */
13968                        // writer
13969                        synchronized (mPackages) {
13970                            retCode = PackageManager.INSTALL_SUCCEEDED;
13971                            pkgList.add(pkg.packageName);
13972                            // Post process args
13973                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
13974                                    pkg.applicationInfo.uid);
13975                        }
13976                    } else {
13977                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
13978                    }
13979                }
13980
13981            } finally {
13982                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
13983                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
13984                }
13985            }
13986        }
13987        // writer
13988        synchronized (mPackages) {
13989            // If the platform SDK has changed since the last time we booted,
13990            // we need to re-grant app permission to catch any new ones that
13991            // appear. This is really a hack, and means that apps can in some
13992            // cases get permissions that the user didn't initially explicitly
13993            // allow... it would be nice to have some better way to handle
13994            // this situation.
13995            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
13996            if (regrantPermissions)
13997                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
13998                        + mSdkVersion + "; regranting permissions for external storage");
13999            mSettings.mExternalSdkPlatform = mSdkVersion;
14000
14001            // Make sure group IDs have been assigned, and any permission
14002            // changes in other apps are accounted for
14003            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14004                    | (regrantPermissions
14005                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14006                            : 0));
14007
14008            mSettings.updateExternalDatabaseVersion();
14009
14010            // can downgrade to reader
14011            // Persist settings
14012            mSettings.writeLPr();
14013        }
14014        // Send a broadcast to let everyone know we are done processing
14015        if (pkgList.size() > 0) {
14016            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14017        }
14018    }
14019
14020   /*
14021     * Utility method to unload a list of specified containers
14022     */
14023    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14024        // Just unmount all valid containers.
14025        for (AsecInstallArgs arg : cidArgs) {
14026            synchronized (mInstallLock) {
14027                arg.doPostDeleteLI(false);
14028           }
14029       }
14030   }
14031
14032    /*
14033     * Unload packages mounted on external media. This involves deleting package
14034     * data from internal structures, sending broadcasts about diabled packages,
14035     * gc'ing to free up references, unmounting all secure containers
14036     * corresponding to packages on external media, and posting a
14037     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14038     * that we always have to post this message if status has been requested no
14039     * matter what.
14040     */
14041    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14042            final boolean reportStatus) {
14043        if (DEBUG_SD_INSTALL)
14044            Log.i(TAG, "unloading media packages");
14045        ArrayList<String> pkgList = new ArrayList<String>();
14046        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14047        final Set<AsecInstallArgs> keys = processCids.keySet();
14048        for (AsecInstallArgs args : keys) {
14049            String pkgName = args.getPackageName();
14050            if (DEBUG_SD_INSTALL)
14051                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14052            // Delete package internally
14053            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14054            synchronized (mInstallLock) {
14055                boolean res = deletePackageLI(pkgName, null, false, null, null,
14056                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14057                if (res) {
14058                    pkgList.add(pkgName);
14059                } else {
14060                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14061                    failedList.add(args);
14062                }
14063            }
14064        }
14065
14066        // reader
14067        synchronized (mPackages) {
14068            // We didn't update the settings after removing each package;
14069            // write them now for all packages.
14070            mSettings.writeLPr();
14071        }
14072
14073        // We have to absolutely send UPDATED_MEDIA_STATUS only
14074        // after confirming that all the receivers processed the ordered
14075        // broadcast when packages get disabled, force a gc to clean things up.
14076        // and unload all the containers.
14077        if (pkgList.size() > 0) {
14078            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14079                    new IIntentReceiver.Stub() {
14080                public void performReceive(Intent intent, int resultCode, String data,
14081                        Bundle extras, boolean ordered, boolean sticky,
14082                        int sendingUser) throws RemoteException {
14083                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14084                            reportStatus ? 1 : 0, 1, keys);
14085                    mHandler.sendMessage(msg);
14086                }
14087            });
14088        } else {
14089            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14090                    keys);
14091            mHandler.sendMessage(msg);
14092        }
14093    }
14094
14095    private void loadPrivatePackages(VolumeInfo vol) {
14096        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14097        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14098        synchronized (mPackages) {
14099            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14100            for (PackageSetting ps : packages) {
14101                synchronized (mInstallLock) {
14102                    final PackageParser.Package pkg;
14103                    try {
14104                        pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14105                        loaded.add(pkg.applicationInfo);
14106                    } catch (PackageManagerException e) {
14107                        Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14108                    }
14109                }
14110            }
14111
14112            // TODO: regrant any permissions that changed based since original install
14113
14114            mSettings.writeLPr();
14115        }
14116
14117        Slog.d(TAG, "Loaded packages " + loaded);
14118        sendResourcesChangedBroadcast(true, false, loaded, null);
14119    }
14120
14121    private void unloadPrivatePackages(VolumeInfo vol) {
14122        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14123        synchronized (mPackages) {
14124            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14125            for (PackageSetting ps : packages) {
14126                if (ps.pkg == null) continue;
14127                synchronized (mInstallLock) {
14128                    final ApplicationInfo info = ps.pkg.applicationInfo;
14129                    final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14130                    if (deletePackageLI(ps.name, null, false, null, null,
14131                            PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14132                        unloaded.add(info);
14133                    } else {
14134                        Slog.w(TAG, "Failed to unload " + ps.codePath);
14135                    }
14136                }
14137            }
14138
14139            mSettings.writeLPr();
14140        }
14141
14142        Slog.d(TAG, "Unloaded packages " + unloaded);
14143        sendResourcesChangedBroadcast(false, false, unloaded, null);
14144    }
14145
14146    @Override
14147    public void movePackage(final String packageName, final IPackageMoveObserver observer,
14148            final int flags) {
14149        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14150
14151        final int installFlags;
14152        if ((flags & MOVE_INTERNAL) != 0) {
14153            installFlags = INSTALL_INTERNAL;
14154        } else if ((flags & MOVE_EXTERNAL_MEDIA) != 0) {
14155            installFlags = INSTALL_EXTERNAL;
14156        } else {
14157            throw new IllegalArgumentException("Unsupported move flags " + flags);
14158        }
14159
14160        try {
14161            movePackageInternal(packageName, null, installFlags, false, observer);
14162        } catch (PackageManagerException e) {
14163            Slog.d(TAG, "Failed to move " + packageName, e);
14164            try {
14165                observer.packageMoved(packageName, e.error);
14166            } catch (RemoteException ignored) {
14167            }
14168        }
14169    }
14170
14171    @Override
14172    public void movePackageAndData(final String packageName, final String volumeUuid,
14173            final IPackageMoveObserver observer) {
14174        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14175        try {
14176            movePackageInternal(packageName, volumeUuid, INSTALL_INTERNAL, true, observer);
14177        } catch (PackageManagerException e) {
14178            Slog.d(TAG, "Failed to move " + packageName, e);
14179            try {
14180                observer.packageMoved(packageName, e.error);
14181            } catch (RemoteException ignored) {
14182            }
14183        }
14184    }
14185
14186    private void movePackageInternal(final String packageName, String volumeUuid, int installFlags,
14187            boolean andData, final IPackageMoveObserver observer) throws PackageManagerException {
14188        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14189
14190        File codeFile = null;
14191        String installerPackageName = null;
14192        String packageAbiOverride = null;
14193
14194        // TOOD: move app private data before installing
14195
14196        // reader
14197        synchronized (mPackages) {
14198            final PackageParser.Package pkg = mPackages.get(packageName);
14199            final PackageSetting ps = mSettings.mPackages.get(packageName);
14200            if (pkg == null || ps == null) {
14201                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14202            }
14203
14204            if (pkg.applicationInfo.isSystemApp()) {
14205                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14206                        "Cannot move system application");
14207            } else if (pkg.mOperationPending) {
14208                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14209                        "Attempt to move package which has pending operations");
14210            }
14211
14212            // TODO: yell if already in desired location
14213
14214            pkg.mOperationPending = true;
14215
14216            codeFile = new File(pkg.codePath);
14217            installerPackageName = ps.installerPackageName;
14218            packageAbiOverride = ps.cpuAbiOverrideString;
14219        }
14220
14221        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14222            @Override
14223            public void onUserActionRequired(Intent intent) throws RemoteException {
14224                throw new IllegalStateException();
14225            }
14226
14227            @Override
14228            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14229                    Bundle extras) throws RemoteException {
14230                Slog.d(TAG, "Install result for move: "
14231                        + PackageManager.installStatusToString(returnCode, msg));
14232
14233                // We usually have a new package now after the install, but if
14234                // we failed we need to clear the pending flag on the original
14235                // package object.
14236                synchronized (mPackages) {
14237                    final PackageParser.Package pkg = mPackages.get(packageName);
14238                    if (pkg != null) {
14239                        pkg.mOperationPending = false;
14240                    }
14241                }
14242
14243                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14244                switch (status) {
14245                    case PackageInstaller.STATUS_SUCCESS:
14246                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
14247                        break;
14248                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14249                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14250                        break;
14251                    default:
14252                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14253                        break;
14254                }
14255            }
14256        };
14257
14258        // Treat a move like reinstalling an existing app, which ensures that we
14259        // process everythign uniformly, like unpacking native libraries.
14260        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14261
14262        final Message msg = mHandler.obtainMessage(INIT_COPY);
14263        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14264        msg.obj = new InstallParams(origin, installObserver, installFlags,
14265                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14266        mHandler.sendMessage(msg);
14267    }
14268
14269    @Override
14270    public boolean setInstallLocation(int loc) {
14271        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14272                null);
14273        if (getInstallLocation() == loc) {
14274            return true;
14275        }
14276        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14277                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14278            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14279                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14280            return true;
14281        }
14282        return false;
14283   }
14284
14285    @Override
14286    public int getInstallLocation() {
14287        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14288                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14289                PackageHelper.APP_INSTALL_AUTO);
14290    }
14291
14292    /** Called by UserManagerService */
14293    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14294        mDirtyUsers.remove(userHandle);
14295        mSettings.removeUserLPw(userHandle);
14296        mPendingBroadcasts.remove(userHandle);
14297        if (mInstaller != null) {
14298            // Technically, we shouldn't be doing this with the package lock
14299            // held.  However, this is very rare, and there is already so much
14300            // other disk I/O going on, that we'll let it slide for now.
14301            mInstaller.removeUserDataDirs(userHandle);
14302        }
14303        mUserNeedsBadging.delete(userHandle);
14304        removeUnusedPackagesLILPw(userManager, userHandle);
14305    }
14306
14307    /**
14308     * We're removing userHandle and would like to remove any downloaded packages
14309     * that are no longer in use by any other user.
14310     * @param userHandle the user being removed
14311     */
14312    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
14313        final boolean DEBUG_CLEAN_APKS = false;
14314        int [] users = userManager.getUserIdsLPr();
14315        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
14316        while (psit.hasNext()) {
14317            PackageSetting ps = psit.next();
14318            if (ps.pkg == null) {
14319                continue;
14320            }
14321            final String packageName = ps.pkg.packageName;
14322            // Skip over if system app
14323            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14324                continue;
14325            }
14326            if (DEBUG_CLEAN_APKS) {
14327                Slog.i(TAG, "Checking package " + packageName);
14328            }
14329            boolean keep = false;
14330            for (int i = 0; i < users.length; i++) {
14331                if (users[i] != userHandle && ps.getInstalled(users[i])) {
14332                    keep = true;
14333                    if (DEBUG_CLEAN_APKS) {
14334                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
14335                                + users[i]);
14336                    }
14337                    break;
14338                }
14339            }
14340            if (!keep) {
14341                if (DEBUG_CLEAN_APKS) {
14342                    Slog.i(TAG, "  Removing package " + packageName);
14343                }
14344                mHandler.post(new Runnable() {
14345                    public void run() {
14346                        deletePackageX(packageName, userHandle, 0);
14347                    } //end run
14348                });
14349            }
14350        }
14351    }
14352
14353    /** Called by UserManagerService */
14354    void createNewUserLILPw(int userHandle, File path) {
14355        if (mInstaller != null) {
14356            mInstaller.createUserConfig(userHandle);
14357            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
14358        }
14359    }
14360
14361    void newUserCreatedLILPw(int userHandle) {
14362        // Adding a user requires updating runtime permissions for system apps.
14363        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
14364    }
14365
14366    @Override
14367    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
14368        mContext.enforceCallingOrSelfPermission(
14369                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14370                "Only package verification agents can read the verifier device identity");
14371
14372        synchronized (mPackages) {
14373            return mSettings.getVerifierDeviceIdentityLPw();
14374        }
14375    }
14376
14377    @Override
14378    public void setPermissionEnforced(String permission, boolean enforced) {
14379        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
14380        if (READ_EXTERNAL_STORAGE.equals(permission)) {
14381            synchronized (mPackages) {
14382                if (mSettings.mReadExternalStorageEnforced == null
14383                        || mSettings.mReadExternalStorageEnforced != enforced) {
14384                    mSettings.mReadExternalStorageEnforced = enforced;
14385                    mSettings.writeLPr();
14386                }
14387            }
14388            // kill any non-foreground processes so we restart them and
14389            // grant/revoke the GID.
14390            final IActivityManager am = ActivityManagerNative.getDefault();
14391            if (am != null) {
14392                final long token = Binder.clearCallingIdentity();
14393                try {
14394                    am.killProcessesBelowForeground("setPermissionEnforcement");
14395                } catch (RemoteException e) {
14396                } finally {
14397                    Binder.restoreCallingIdentity(token);
14398                }
14399            }
14400        } else {
14401            throw new IllegalArgumentException("No selective enforcement for " + permission);
14402        }
14403    }
14404
14405    @Override
14406    @Deprecated
14407    public boolean isPermissionEnforced(String permission) {
14408        return true;
14409    }
14410
14411    @Override
14412    public boolean isStorageLow() {
14413        final long token = Binder.clearCallingIdentity();
14414        try {
14415            final DeviceStorageMonitorInternal
14416                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14417            if (dsm != null) {
14418                return dsm.isMemoryLow();
14419            } else {
14420                return false;
14421            }
14422        } finally {
14423            Binder.restoreCallingIdentity(token);
14424        }
14425    }
14426
14427    @Override
14428    public IPackageInstaller getPackageInstaller() {
14429        return mInstallerService;
14430    }
14431
14432    private boolean userNeedsBadging(int userId) {
14433        int index = mUserNeedsBadging.indexOfKey(userId);
14434        if (index < 0) {
14435            final UserInfo userInfo;
14436            final long token = Binder.clearCallingIdentity();
14437            try {
14438                userInfo = sUserManager.getUserInfo(userId);
14439            } finally {
14440                Binder.restoreCallingIdentity(token);
14441            }
14442            final boolean b;
14443            if (userInfo != null && userInfo.isManagedProfile()) {
14444                b = true;
14445            } else {
14446                b = false;
14447            }
14448            mUserNeedsBadging.put(userId, b);
14449            return b;
14450        }
14451        return mUserNeedsBadging.valueAt(index);
14452    }
14453
14454    @Override
14455    public KeySet getKeySetByAlias(String packageName, String alias) {
14456        if (packageName == null || alias == null) {
14457            return null;
14458        }
14459        synchronized(mPackages) {
14460            final PackageParser.Package pkg = mPackages.get(packageName);
14461            if (pkg == null) {
14462                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14463                throw new IllegalArgumentException("Unknown package: " + packageName);
14464            }
14465            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14466            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
14467        }
14468    }
14469
14470    @Override
14471    public KeySet getSigningKeySet(String packageName) {
14472        if (packageName == null) {
14473            return null;
14474        }
14475        synchronized(mPackages) {
14476            final PackageParser.Package pkg = mPackages.get(packageName);
14477            if (pkg == null) {
14478                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14479                throw new IllegalArgumentException("Unknown package: " + packageName);
14480            }
14481            if (pkg.applicationInfo.uid != Binder.getCallingUid()
14482                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
14483                throw new SecurityException("May not access signing KeySet of other apps.");
14484            }
14485            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14486            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
14487        }
14488    }
14489
14490    @Override
14491    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
14492        if (packageName == null || ks == null) {
14493            return false;
14494        }
14495        synchronized(mPackages) {
14496            final PackageParser.Package pkg = mPackages.get(packageName);
14497            if (pkg == null) {
14498                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14499                throw new IllegalArgumentException("Unknown package: " + packageName);
14500            }
14501            IBinder ksh = ks.getToken();
14502            if (ksh instanceof KeySetHandle) {
14503                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14504                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
14505            }
14506            return false;
14507        }
14508    }
14509
14510    @Override
14511    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
14512        if (packageName == null || ks == null) {
14513            return false;
14514        }
14515        synchronized(mPackages) {
14516            final PackageParser.Package pkg = mPackages.get(packageName);
14517            if (pkg == null) {
14518                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14519                throw new IllegalArgumentException("Unknown package: " + packageName);
14520            }
14521            IBinder ksh = ks.getToken();
14522            if (ksh instanceof KeySetHandle) {
14523                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14524                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
14525            }
14526            return false;
14527        }
14528    }
14529
14530    public void getUsageStatsIfNoPackageUsageInfo() {
14531        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
14532            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
14533            if (usm == null) {
14534                throw new IllegalStateException("UsageStatsManager must be initialized");
14535            }
14536            long now = System.currentTimeMillis();
14537            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
14538            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
14539                String packageName = entry.getKey();
14540                PackageParser.Package pkg = mPackages.get(packageName);
14541                if (pkg == null) {
14542                    continue;
14543                }
14544                UsageStats usage = entry.getValue();
14545                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
14546                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
14547            }
14548        }
14549    }
14550
14551    /**
14552     * Check and throw if the given before/after packages would be considered a
14553     * downgrade.
14554     */
14555    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
14556            throws PackageManagerException {
14557        if (after.versionCode < before.mVersionCode) {
14558            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14559                    "Update version code " + after.versionCode + " is older than current "
14560                    + before.mVersionCode);
14561        } else if (after.versionCode == before.mVersionCode) {
14562            if (after.baseRevisionCode < before.baseRevisionCode) {
14563                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14564                        "Update base revision code " + after.baseRevisionCode
14565                        + " is older than current " + before.baseRevisionCode);
14566            }
14567
14568            if (!ArrayUtils.isEmpty(after.splitNames)) {
14569                for (int i = 0; i < after.splitNames.length; i++) {
14570                    final String splitName = after.splitNames[i];
14571                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
14572                    if (j != -1) {
14573                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
14574                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14575                                    "Update split " + splitName + " revision code "
14576                                    + after.splitRevisionCodes[i] + " is older than current "
14577                                    + before.splitRevisionCodes[j]);
14578                        }
14579                    }
14580                }
14581            }
14582        }
14583    }
14584}
14585