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