PackageManagerService.java revision caa41648f4e3cecc1996447396aabc4e394b8fd0
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                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1851                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1852                                alreadyDexOpted.add(lib);
1853                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1854                            }
1855                        } catch (FileNotFoundException e) {
1856                            Slog.w(TAG, "Library not found: " + lib);
1857                        } catch (IOException e) {
1858                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1859                                    + e.getMessage());
1860                        }
1861                    }
1862                }
1863            }
1864
1865            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1866
1867            // Gross hack for now: we know this file doesn't contain any
1868            // code, so don't dexopt it to avoid the resulting log spew.
1869            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1870
1871            // Gross hack for now: we know this file is only part of
1872            // the boot class path for art, so don't dexopt it to
1873            // avoid the resulting log spew.
1874            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1875
1876            /**
1877             * And there are a number of commands implemented in Java, which
1878             * we currently need to do the dexopt on so that they can be
1879             * run from a non-root shell.
1880             */
1881            String[] frameworkFiles = frameworkDir.list();
1882            if (frameworkFiles != null) {
1883                // TODO: We could compile these only for the most preferred ABI. We should
1884                // first double check that the dex files for these commands are not referenced
1885                // by other system apps.
1886                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1887                    for (int i=0; i<frameworkFiles.length; i++) {
1888                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1889                        String path = libPath.getPath();
1890                        // Skip the file if we already did it.
1891                        if (alreadyDexOpted.contains(path)) {
1892                            continue;
1893                        }
1894                        // Skip the file if it is not a type we want to dexopt.
1895                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1896                            continue;
1897                        }
1898                        try {
1899                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1900                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1901                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1902                            }
1903                        } catch (FileNotFoundException e) {
1904                            Slog.w(TAG, "Jar not found: " + path);
1905                        } catch (IOException e) {
1906                            Slog.w(TAG, "Exception reading jar: " + path, e);
1907                        }
1908                    }
1909                }
1910            }
1911
1912            // Collect vendor overlay packages.
1913            // (Do this before scanning any apps.)
1914            // For security and version matching reason, only consider
1915            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1916            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1917            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1918                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1919
1920            // Find base frameworks (resource packages without code).
1921            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1922                    | PackageParser.PARSE_IS_SYSTEM_DIR
1923                    | PackageParser.PARSE_IS_PRIVILEGED,
1924                    scanFlags | SCAN_NO_DEX, 0);
1925
1926            // Collected privileged system packages.
1927            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1928            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1929                    | PackageParser.PARSE_IS_SYSTEM_DIR
1930                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1931
1932            // Collect ordinary system packages.
1933            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1934            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1935                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1936
1937            // Collect all vendor packages.
1938            File vendorAppDir = new File("/vendor/app");
1939            try {
1940                vendorAppDir = vendorAppDir.getCanonicalFile();
1941            } catch (IOException e) {
1942                // failed to look up canonical path, continue with original one
1943            }
1944            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1945                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1946
1947            // Collect all OEM packages.
1948            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1949            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1950                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1951
1952            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1953            mInstaller.moveFiles();
1954
1955            // Prune any system packages that no longer exist.
1956            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1957            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1958            if (!mOnlyCore) {
1959                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1960                while (psit.hasNext()) {
1961                    PackageSetting ps = psit.next();
1962
1963                    /*
1964                     * If this is not a system app, it can't be a
1965                     * disable system app.
1966                     */
1967                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1968                        continue;
1969                    }
1970
1971                    /*
1972                     * If the package is scanned, it's not erased.
1973                     */
1974                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1975                    if (scannedPkg != null) {
1976                        /*
1977                         * If the system app is both scanned and in the
1978                         * disabled packages list, then it must have been
1979                         * added via OTA. Remove it from the currently
1980                         * scanned package so the previously user-installed
1981                         * application can be scanned.
1982                         */
1983                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1984                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1985                                    + ps.name + "; removing system app.  Last known codePath="
1986                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1987                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1988                                    + scannedPkg.mVersionCode);
1989                            removePackageLI(ps, true);
1990                            expectingBetter.put(ps.name, ps.codePath);
1991                        }
1992
1993                        continue;
1994                    }
1995
1996                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1997                        psit.remove();
1998                        logCriticalInfo(Log.WARN, "System package " + ps.name
1999                                + " no longer exists; wiping its data");
2000                        removeDataDirsLI(ps.name);
2001                    } else {
2002                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2003                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2004                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2005                        }
2006                    }
2007                }
2008            }
2009
2010            //look for any incomplete package installations
2011            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2012            //clean up list
2013            for(int i = 0; i < deletePkgsList.size(); i++) {
2014                //clean up here
2015                cleanupInstallFailedPackage(deletePkgsList.get(i));
2016            }
2017            //delete tmp files
2018            deleteTempPackageFiles();
2019
2020            // Remove any shared userIDs that have no associated packages
2021            mSettings.pruneSharedUsersLPw();
2022
2023            if (!mOnlyCore) {
2024                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2025                        SystemClock.uptimeMillis());
2026                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2027
2028                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2029                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2030
2031                /**
2032                 * Remove disable package settings for any updated system
2033                 * apps that were removed via an OTA. If they're not a
2034                 * previously-updated app, remove them completely.
2035                 * Otherwise, just revoke their system-level permissions.
2036                 */
2037                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2038                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2039                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2040
2041                    String msg;
2042                    if (deletedPkg == null) {
2043                        msg = "Updated system package " + deletedAppName
2044                                + " no longer exists; wiping its data";
2045                        removeDataDirsLI(deletedAppName);
2046                    } else {
2047                        msg = "Updated system app + " + deletedAppName
2048                                + " no longer present; removing system privileges for "
2049                                + deletedAppName;
2050
2051                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2052
2053                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2054                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2055                    }
2056                    logCriticalInfo(Log.WARN, msg);
2057                }
2058
2059                /**
2060                 * Make sure all system apps that we expected to appear on
2061                 * the userdata partition actually showed up. If they never
2062                 * appeared, crawl back and revive the system version.
2063                 */
2064                for (int i = 0; i < expectingBetter.size(); i++) {
2065                    final String packageName = expectingBetter.keyAt(i);
2066                    if (!mPackages.containsKey(packageName)) {
2067                        final File scanFile = expectingBetter.valueAt(i);
2068
2069                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2070                                + " but never showed up; reverting to system");
2071
2072                        final int reparseFlags;
2073                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2074                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2075                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2076                                    | PackageParser.PARSE_IS_PRIVILEGED;
2077                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2078                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2079                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2080                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2081                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2082                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2083                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2084                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2085                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2086                        } else {
2087                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2088                            continue;
2089                        }
2090
2091                        mSettings.enableSystemPackageLPw(packageName);
2092
2093                        try {
2094                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2095                        } catch (PackageManagerException e) {
2096                            Slog.e(TAG, "Failed to parse original system package: "
2097                                    + e.getMessage());
2098                        }
2099                    }
2100                }
2101            }
2102
2103            // Now that we know all of the shared libraries, update all clients to have
2104            // the correct library paths.
2105            updateAllSharedLibrariesLPw();
2106
2107            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2108                // NOTE: We ignore potential failures here during a system scan (like
2109                // the rest of the commands above) because there's precious little we
2110                // can do about it. A settings error is reported, though.
2111                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2112                        false /* force dexopt */, false /* defer dexopt */);
2113            }
2114
2115            // Now that we know all the packages we are keeping,
2116            // read and update their last usage times.
2117            mPackageUsage.readLP();
2118
2119            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2120                    SystemClock.uptimeMillis());
2121            Slog.i(TAG, "Time to scan packages: "
2122                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2123                    + " seconds");
2124
2125            // If the platform SDK has changed since the last time we booted,
2126            // we need to re-grant app permission to catch any new ones that
2127            // appear.  This is really a hack, and means that apps can in some
2128            // cases get permissions that the user didn't initially explicitly
2129            // allow...  it would be nice to have some better way to handle
2130            // this situation.
2131            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2132                    != mSdkVersion;
2133            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2134                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2135                    + "; regranting permissions for internal storage");
2136            mSettings.mInternalSdkPlatform = mSdkVersion;
2137
2138            // For now runtime permissions are toggled via a system property.
2139            if (!RUNTIME_PERMISSIONS_ENABLED) {
2140                // Remove the runtime permissions state if the feature
2141                // was disabled by flipping the system property.
2142                mSettings.deleteRuntimePermissionsFiles();
2143            }
2144
2145            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2146                    | (regrantPermissions
2147                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2148                            : 0));
2149
2150            // If this is the first boot, and it is a normal boot, then
2151            // we need to initialize the default preferred apps.
2152            if (!mRestoredSettings && !onlyCore) {
2153                mSettings.readDefaultPreferredAppsLPw(this, 0);
2154            }
2155
2156            // If this is first boot after an OTA, and a normal boot, then
2157            // we need to clear code cache directories.
2158            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2159            if (mIsUpgrade && !onlyCore) {
2160                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2161                for (String pkgName : mSettings.mPackages.keySet()) {
2162                    deleteCodeCacheDirsLI(pkgName);
2163                }
2164                mSettings.mFingerprint = Build.FINGERPRINT;
2165            }
2166
2167            // All the changes are done during package scanning.
2168            mSettings.updateInternalDatabaseVersion();
2169
2170            // can downgrade to reader
2171            mSettings.writeLPr();
2172
2173            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2174                    SystemClock.uptimeMillis());
2175
2176            mRequiredVerifierPackage = getRequiredVerifierLPr();
2177
2178            mInstallerService = new PackageInstallerService(context, this);
2179
2180            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2181            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2182                    mIntentFilterVerifierComponent);
2183
2184            primeDomainVerificationsLPw(false);
2185
2186        } // synchronized (mPackages)
2187        } // synchronized (mInstallLock)
2188
2189        // Now after opening every single application zip, make sure they
2190        // are all flushed.  Not really needed, but keeps things nice and
2191        // tidy.
2192        Runtime.getRuntime().gc();
2193    }
2194
2195    @Override
2196    public boolean isFirstBoot() {
2197        return !mRestoredSettings;
2198    }
2199
2200    @Override
2201    public boolean isOnlyCoreApps() {
2202        return mOnlyCore;
2203    }
2204
2205    @Override
2206    public boolean isUpgrade() {
2207        return mIsUpgrade;
2208    }
2209
2210    private String getRequiredVerifierLPr() {
2211        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2212        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2213                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2214
2215        String requiredVerifier = null;
2216
2217        final int N = receivers.size();
2218        for (int i = 0; i < N; i++) {
2219            final ResolveInfo info = receivers.get(i);
2220
2221            if (info.activityInfo == null) {
2222                continue;
2223            }
2224
2225            final String packageName = info.activityInfo.packageName;
2226
2227            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2228                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2229                continue;
2230            }
2231
2232            if (requiredVerifier != null) {
2233                throw new RuntimeException("There can be only one required verifier");
2234            }
2235
2236            requiredVerifier = packageName;
2237        }
2238
2239        return requiredVerifier;
2240    }
2241
2242    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2243        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2244        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2245                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2246
2247        ComponentName verifierComponentName = null;
2248
2249        int priority = -1000;
2250        final int N = receivers.size();
2251        for (int i = 0; i < N; i++) {
2252            final ResolveInfo info = receivers.get(i);
2253
2254            if (info.activityInfo == null) {
2255                continue;
2256            }
2257
2258            final String packageName = info.activityInfo.packageName;
2259
2260            final PackageSetting ps = mSettings.mPackages.get(packageName);
2261            if (ps == null) {
2262                continue;
2263            }
2264
2265            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2266                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2267                continue;
2268            }
2269
2270            // Select the IntentFilterVerifier with the highest priority
2271            if (priority < info.priority) {
2272                priority = info.priority;
2273                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2274                Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName +
2275                        " with priority: " + info.priority);
2276            }
2277        }
2278
2279        return verifierComponentName;
2280    }
2281
2282    private void primeDomainVerificationsLPw(boolean logging) {
2283        Slog.d(TAG, "Start priming domain verification");
2284        boolean updated = false;
2285        ArrayList<String> allHosts = new ArrayList<>();
2286        for (PackageParser.Package pkg : mPackages.values()) {
2287            final String packageName = pkg.packageName;
2288            if (!hasDomainURLs(pkg)) {
2289                if (logging) {
2290                    Slog.d(TAG, "No priming domain verifications for " +
2291                            "package with no domain URLs: " + packageName);
2292                }
2293                continue;
2294            }
2295            for (PackageParser.Activity a : pkg.activities) {
2296                for (ActivityIntentInfo filter : a.intents) {
2297                    if (hasValidDomains(filter, false)) {
2298                        allHosts.addAll(filter.getHostsList());
2299                    }
2300                }
2301            }
2302            if (allHosts.size() > 0) {
2303                allHosts.add("*");
2304            }
2305            IntentFilterVerificationInfo ivi =
2306                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHosts);
2307            if (ivi != null) {
2308                // We will always log this
2309                Slog.d(TAG, "Priming domain verifications for package: " + packageName);
2310                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2311                updated = true;
2312            }
2313            else {
2314                if (logging) {
2315                    Slog.d(TAG, "No priming domain verifications for package: " + packageName);
2316                }
2317            }
2318            allHosts.clear();
2319        }
2320        if (updated) {
2321            scheduleWriteSettingsLocked();
2322        }
2323        Slog.d(TAG, "End priming domain verification");
2324    }
2325
2326    @Override
2327    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2328            throws RemoteException {
2329        try {
2330            return super.onTransact(code, data, reply, flags);
2331        } catch (RuntimeException e) {
2332            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2333                Slog.wtf(TAG, "Package Manager Crash", e);
2334            }
2335            throw e;
2336        }
2337    }
2338
2339    void cleanupInstallFailedPackage(PackageSetting ps) {
2340        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2341
2342        removeDataDirsLI(ps.name);
2343        if (ps.codePath != null) {
2344            if (ps.codePath.isDirectory()) {
2345                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2346            } else {
2347                ps.codePath.delete();
2348            }
2349        }
2350        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2351            if (ps.resourcePath.isDirectory()) {
2352                FileUtils.deleteContents(ps.resourcePath);
2353            }
2354            ps.resourcePath.delete();
2355        }
2356        mSettings.removePackageLPw(ps.name);
2357    }
2358
2359    static int[] appendInts(int[] cur, int[] add) {
2360        if (add == null) return cur;
2361        if (cur == null) return add;
2362        final int N = add.length;
2363        for (int i=0; i<N; i++) {
2364            cur = appendInt(cur, add[i]);
2365        }
2366        return cur;
2367    }
2368
2369    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2370        if (!sUserManager.exists(userId)) return null;
2371        final PackageSetting ps = (PackageSetting) p.mExtras;
2372        if (ps == null) {
2373            return null;
2374        }
2375
2376        final PermissionsState permissionsState = ps.getPermissionsState();
2377
2378        final int[] gids = permissionsState.computeGids(userId);
2379        final Set<String> permissions = permissionsState.getPermissions(userId);
2380        final PackageUserState state = ps.readUserState(userId);
2381
2382        return PackageParser.generatePackageInfo(p, gids, flags,
2383                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2384    }
2385
2386    @Override
2387    public boolean isPackageAvailable(String packageName, int userId) {
2388        if (!sUserManager.exists(userId)) return false;
2389        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2390        synchronized (mPackages) {
2391            PackageParser.Package p = mPackages.get(packageName);
2392            if (p != null) {
2393                final PackageSetting ps = (PackageSetting) p.mExtras;
2394                if (ps != null) {
2395                    final PackageUserState state = ps.readUserState(userId);
2396                    if (state != null) {
2397                        return PackageParser.isAvailable(state);
2398                    }
2399                }
2400            }
2401        }
2402        return false;
2403    }
2404
2405    @Override
2406    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2407        if (!sUserManager.exists(userId)) return null;
2408        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2409        // reader
2410        synchronized (mPackages) {
2411            PackageParser.Package p = mPackages.get(packageName);
2412            if (DEBUG_PACKAGE_INFO)
2413                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2414            if (p != null) {
2415                return generatePackageInfo(p, flags, userId);
2416            }
2417            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2418                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2419            }
2420        }
2421        return null;
2422    }
2423
2424    @Override
2425    public String[] currentToCanonicalPackageNames(String[] names) {
2426        String[] out = new String[names.length];
2427        // reader
2428        synchronized (mPackages) {
2429            for (int i=names.length-1; i>=0; i--) {
2430                PackageSetting ps = mSettings.mPackages.get(names[i]);
2431                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2432            }
2433        }
2434        return out;
2435    }
2436
2437    @Override
2438    public String[] canonicalToCurrentPackageNames(String[] names) {
2439        String[] out = new String[names.length];
2440        // reader
2441        synchronized (mPackages) {
2442            for (int i=names.length-1; i>=0; i--) {
2443                String cur = mSettings.mRenamedPackages.get(names[i]);
2444                out[i] = cur != null ? cur : names[i];
2445            }
2446        }
2447        return out;
2448    }
2449
2450    @Override
2451    public int getPackageUid(String packageName, int userId) {
2452        if (!sUserManager.exists(userId)) return -1;
2453        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2454
2455        // reader
2456        synchronized (mPackages) {
2457            PackageParser.Package p = mPackages.get(packageName);
2458            if(p != null) {
2459                return UserHandle.getUid(userId, p.applicationInfo.uid);
2460            }
2461            PackageSetting ps = mSettings.mPackages.get(packageName);
2462            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2463                return -1;
2464            }
2465            p = ps.pkg;
2466            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2467        }
2468    }
2469
2470    @Override
2471    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2472        if (!sUserManager.exists(userId)) {
2473            return null;
2474        }
2475
2476        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2477                "getPackageGids");
2478
2479        // reader
2480        synchronized (mPackages) {
2481            PackageParser.Package p = mPackages.get(packageName);
2482            if (DEBUG_PACKAGE_INFO) {
2483                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2484            }
2485            if (p != null) {
2486                PackageSetting ps = (PackageSetting) p.mExtras;
2487                return ps.getPermissionsState().computeGids(userId);
2488            }
2489        }
2490
2491        return null;
2492    }
2493
2494    static PermissionInfo generatePermissionInfo(
2495            BasePermission bp, int flags) {
2496        if (bp.perm != null) {
2497            return PackageParser.generatePermissionInfo(bp.perm, flags);
2498        }
2499        PermissionInfo pi = new PermissionInfo();
2500        pi.name = bp.name;
2501        pi.packageName = bp.sourcePackage;
2502        pi.nonLocalizedLabel = bp.name;
2503        pi.protectionLevel = bp.protectionLevel;
2504        return pi;
2505    }
2506
2507    @Override
2508    public PermissionInfo getPermissionInfo(String name, int flags) {
2509        // reader
2510        synchronized (mPackages) {
2511            final BasePermission p = mSettings.mPermissions.get(name);
2512            if (p != null) {
2513                return generatePermissionInfo(p, flags);
2514            }
2515            return null;
2516        }
2517    }
2518
2519    @Override
2520    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2521        // reader
2522        synchronized (mPackages) {
2523            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2524            for (BasePermission p : mSettings.mPermissions.values()) {
2525                if (group == null) {
2526                    if (p.perm == null || p.perm.info.group == null) {
2527                        out.add(generatePermissionInfo(p, flags));
2528                    }
2529                } else {
2530                    if (p.perm != null && group.equals(p.perm.info.group)) {
2531                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2532                    }
2533                }
2534            }
2535
2536            if (out.size() > 0) {
2537                return out;
2538            }
2539            return mPermissionGroups.containsKey(group) ? out : null;
2540        }
2541    }
2542
2543    @Override
2544    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2545        // reader
2546        synchronized (mPackages) {
2547            return PackageParser.generatePermissionGroupInfo(
2548                    mPermissionGroups.get(name), flags);
2549        }
2550    }
2551
2552    @Override
2553    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2554        // reader
2555        synchronized (mPackages) {
2556            final int N = mPermissionGroups.size();
2557            ArrayList<PermissionGroupInfo> out
2558                    = new ArrayList<PermissionGroupInfo>(N);
2559            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2560                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2561            }
2562            return out;
2563        }
2564    }
2565
2566    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2567            int userId) {
2568        if (!sUserManager.exists(userId)) return null;
2569        PackageSetting ps = mSettings.mPackages.get(packageName);
2570        if (ps != null) {
2571            if (ps.pkg == null) {
2572                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2573                        flags, userId);
2574                if (pInfo != null) {
2575                    return pInfo.applicationInfo;
2576                }
2577                return null;
2578            }
2579            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2580                    ps.readUserState(userId), userId);
2581        }
2582        return null;
2583    }
2584
2585    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2586            int userId) {
2587        if (!sUserManager.exists(userId)) return null;
2588        PackageSetting ps = mSettings.mPackages.get(packageName);
2589        if (ps != null) {
2590            PackageParser.Package pkg = ps.pkg;
2591            if (pkg == null) {
2592                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2593                    return null;
2594                }
2595                // Only data remains, so we aren't worried about code paths
2596                pkg = new PackageParser.Package(packageName);
2597                pkg.applicationInfo.packageName = packageName;
2598                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2599                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2600                pkg.applicationInfo.dataDir =
2601                        getDataPathForPackage(packageName, 0).getPath();
2602                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2603                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2604            }
2605            return generatePackageInfo(pkg, flags, userId);
2606        }
2607        return null;
2608    }
2609
2610    @Override
2611    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2612        if (!sUserManager.exists(userId)) return null;
2613        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2614        // writer
2615        synchronized (mPackages) {
2616            PackageParser.Package p = mPackages.get(packageName);
2617            if (DEBUG_PACKAGE_INFO) Log.v(
2618                    TAG, "getApplicationInfo " + packageName
2619                    + ": " + p);
2620            if (p != null) {
2621                PackageSetting ps = mSettings.mPackages.get(packageName);
2622                if (ps == null) return null;
2623                // Note: isEnabledLP() does not apply here - always return info
2624                return PackageParser.generateApplicationInfo(
2625                        p, flags, ps.readUserState(userId), userId);
2626            }
2627            if ("android".equals(packageName)||"system".equals(packageName)) {
2628                return mAndroidApplication;
2629            }
2630            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2631                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2632            }
2633        }
2634        return null;
2635    }
2636
2637
2638    @Override
2639    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2640        mContext.enforceCallingOrSelfPermission(
2641                android.Manifest.permission.CLEAR_APP_CACHE, null);
2642        // Queue up an async operation since clearing cache may take a little while.
2643        mHandler.post(new Runnable() {
2644            public void run() {
2645                mHandler.removeCallbacks(this);
2646                int retCode = -1;
2647                synchronized (mInstallLock) {
2648                    retCode = mInstaller.freeCache(freeStorageSize);
2649                    if (retCode < 0) {
2650                        Slog.w(TAG, "Couldn't clear application caches");
2651                    }
2652                }
2653                if (observer != null) {
2654                    try {
2655                        observer.onRemoveCompleted(null, (retCode >= 0));
2656                    } catch (RemoteException e) {
2657                        Slog.w(TAG, "RemoveException when invoking call back");
2658                    }
2659                }
2660            }
2661        });
2662    }
2663
2664    @Override
2665    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2666        mContext.enforceCallingOrSelfPermission(
2667                android.Manifest.permission.CLEAR_APP_CACHE, null);
2668        // Queue up an async operation since clearing cache may take a little while.
2669        mHandler.post(new Runnable() {
2670            public void run() {
2671                mHandler.removeCallbacks(this);
2672                int retCode = -1;
2673                synchronized (mInstallLock) {
2674                    retCode = mInstaller.freeCache(freeStorageSize);
2675                    if (retCode < 0) {
2676                        Slog.w(TAG, "Couldn't clear application caches");
2677                    }
2678                }
2679                if(pi != null) {
2680                    try {
2681                        // Callback via pending intent
2682                        int code = (retCode >= 0) ? 1 : 0;
2683                        pi.sendIntent(null, code, null,
2684                                null, null);
2685                    } catch (SendIntentException e1) {
2686                        Slog.i(TAG, "Failed to send pending intent");
2687                    }
2688                }
2689            }
2690        });
2691    }
2692
2693    void freeStorage(long freeStorageSize) throws IOException {
2694        synchronized (mInstallLock) {
2695            if (mInstaller.freeCache(freeStorageSize) < 0) {
2696                throw new IOException("Failed to free enough space");
2697            }
2698        }
2699    }
2700
2701    @Override
2702    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2703        if (!sUserManager.exists(userId)) return null;
2704        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2705        synchronized (mPackages) {
2706            PackageParser.Activity a = mActivities.mActivities.get(component);
2707
2708            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2709            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2710                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2711                if (ps == null) return null;
2712                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2713                        userId);
2714            }
2715            if (mResolveComponentName.equals(component)) {
2716                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2717                        new PackageUserState(), userId);
2718            }
2719        }
2720        return null;
2721    }
2722
2723    @Override
2724    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2725            String resolvedType) {
2726        synchronized (mPackages) {
2727            PackageParser.Activity a = mActivities.mActivities.get(component);
2728            if (a == null) {
2729                return false;
2730            }
2731            for (int i=0; i<a.intents.size(); i++) {
2732                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2733                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2734                    return true;
2735                }
2736            }
2737            return false;
2738        }
2739    }
2740
2741    @Override
2742    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2743        if (!sUserManager.exists(userId)) return null;
2744        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2745        synchronized (mPackages) {
2746            PackageParser.Activity a = mReceivers.mActivities.get(component);
2747            if (DEBUG_PACKAGE_INFO) Log.v(
2748                TAG, "getReceiverInfo " + component + ": " + a);
2749            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2750                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2751                if (ps == null) return null;
2752                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2753                        userId);
2754            }
2755        }
2756        return null;
2757    }
2758
2759    @Override
2760    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2761        if (!sUserManager.exists(userId)) return null;
2762        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2763        synchronized (mPackages) {
2764            PackageParser.Service s = mServices.mServices.get(component);
2765            if (DEBUG_PACKAGE_INFO) Log.v(
2766                TAG, "getServiceInfo " + component + ": " + s);
2767            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2768                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2769                if (ps == null) return null;
2770                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2771                        userId);
2772            }
2773        }
2774        return null;
2775    }
2776
2777    @Override
2778    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2779        if (!sUserManager.exists(userId)) return null;
2780        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2781        synchronized (mPackages) {
2782            PackageParser.Provider p = mProviders.mProviders.get(component);
2783            if (DEBUG_PACKAGE_INFO) Log.v(
2784                TAG, "getProviderInfo " + component + ": " + p);
2785            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2786                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2787                if (ps == null) return null;
2788                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2789                        userId);
2790            }
2791        }
2792        return null;
2793    }
2794
2795    @Override
2796    public String[] getSystemSharedLibraryNames() {
2797        Set<String> libSet;
2798        synchronized (mPackages) {
2799            libSet = mSharedLibraries.keySet();
2800            int size = libSet.size();
2801            if (size > 0) {
2802                String[] libs = new String[size];
2803                libSet.toArray(libs);
2804                return libs;
2805            }
2806        }
2807        return null;
2808    }
2809
2810    /**
2811     * @hide
2812     */
2813    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2814        synchronized (mPackages) {
2815            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2816            if (lib != null && lib.apk != null) {
2817                return mPackages.get(lib.apk);
2818            }
2819        }
2820        return null;
2821    }
2822
2823    @Override
2824    public FeatureInfo[] getSystemAvailableFeatures() {
2825        Collection<FeatureInfo> featSet;
2826        synchronized (mPackages) {
2827            featSet = mAvailableFeatures.values();
2828            int size = featSet.size();
2829            if (size > 0) {
2830                FeatureInfo[] features = new FeatureInfo[size+1];
2831                featSet.toArray(features);
2832                FeatureInfo fi = new FeatureInfo();
2833                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2834                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2835                features[size] = fi;
2836                return features;
2837            }
2838        }
2839        return null;
2840    }
2841
2842    @Override
2843    public boolean hasSystemFeature(String name) {
2844        synchronized (mPackages) {
2845            return mAvailableFeatures.containsKey(name);
2846        }
2847    }
2848
2849    private void checkValidCaller(int uid, int userId) {
2850        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2851            return;
2852
2853        throw new SecurityException("Caller uid=" + uid
2854                + " is not privileged to communicate with user=" + userId);
2855    }
2856
2857    @Override
2858    public int checkPermission(String permName, String pkgName, int userId) {
2859        if (!sUserManager.exists(userId)) {
2860            return PackageManager.PERMISSION_DENIED;
2861        }
2862
2863        synchronized (mPackages) {
2864            final PackageParser.Package p = mPackages.get(pkgName);
2865            if (p != null && p.mExtras != null) {
2866                final PackageSetting ps = (PackageSetting) p.mExtras;
2867                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2868                    return PackageManager.PERMISSION_GRANTED;
2869                }
2870            }
2871        }
2872
2873        return PackageManager.PERMISSION_DENIED;
2874    }
2875
2876    @Override
2877    public int checkUidPermission(String permName, int uid) {
2878        final int userId = UserHandle.getUserId(uid);
2879
2880        if (!sUserManager.exists(userId)) {
2881            return PackageManager.PERMISSION_DENIED;
2882        }
2883
2884        synchronized (mPackages) {
2885            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2886            if (obj != null) {
2887                final SettingBase ps = (SettingBase) obj;
2888                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2889                    return PackageManager.PERMISSION_GRANTED;
2890                }
2891            } else {
2892                ArraySet<String> perms = mSystemPermissions.get(uid);
2893                if (perms != null && perms.contains(permName)) {
2894                    return PackageManager.PERMISSION_GRANTED;
2895                }
2896            }
2897        }
2898
2899        return PackageManager.PERMISSION_DENIED;
2900    }
2901
2902    /**
2903     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2904     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2905     * @param checkShell TODO(yamasani):
2906     * @param message the message to log on security exception
2907     */
2908    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2909            boolean checkShell, String message) {
2910        if (userId < 0) {
2911            throw new IllegalArgumentException("Invalid userId " + userId);
2912        }
2913        if (checkShell) {
2914            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2915        }
2916        if (userId == UserHandle.getUserId(callingUid)) return;
2917        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2918            if (requireFullPermission) {
2919                mContext.enforceCallingOrSelfPermission(
2920                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2921            } else {
2922                try {
2923                    mContext.enforceCallingOrSelfPermission(
2924                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2925                } catch (SecurityException se) {
2926                    mContext.enforceCallingOrSelfPermission(
2927                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2928                }
2929            }
2930        }
2931    }
2932
2933    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2934        if (callingUid == Process.SHELL_UID) {
2935            if (userHandle >= 0
2936                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2937                throw new SecurityException("Shell does not have permission to access user "
2938                        + userHandle);
2939            } else if (userHandle < 0) {
2940                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2941                        + Debug.getCallers(3));
2942            }
2943        }
2944    }
2945
2946    private BasePermission findPermissionTreeLP(String permName) {
2947        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2948            if (permName.startsWith(bp.name) &&
2949                    permName.length() > bp.name.length() &&
2950                    permName.charAt(bp.name.length()) == '.') {
2951                return bp;
2952            }
2953        }
2954        return null;
2955    }
2956
2957    private BasePermission checkPermissionTreeLP(String permName) {
2958        if (permName != null) {
2959            BasePermission bp = findPermissionTreeLP(permName);
2960            if (bp != null) {
2961                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2962                    return bp;
2963                }
2964                throw new SecurityException("Calling uid "
2965                        + Binder.getCallingUid()
2966                        + " is not allowed to add to permission tree "
2967                        + bp.name + " owned by uid " + bp.uid);
2968            }
2969        }
2970        throw new SecurityException("No permission tree found for " + permName);
2971    }
2972
2973    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2974        if (s1 == null) {
2975            return s2 == null;
2976        }
2977        if (s2 == null) {
2978            return false;
2979        }
2980        if (s1.getClass() != s2.getClass()) {
2981            return false;
2982        }
2983        return s1.equals(s2);
2984    }
2985
2986    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2987        if (pi1.icon != pi2.icon) return false;
2988        if (pi1.logo != pi2.logo) return false;
2989        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2990        if (!compareStrings(pi1.name, pi2.name)) return false;
2991        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2992        // We'll take care of setting this one.
2993        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2994        // These are not currently stored in settings.
2995        //if (!compareStrings(pi1.group, pi2.group)) return false;
2996        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2997        //if (pi1.labelRes != pi2.labelRes) return false;
2998        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2999        return true;
3000    }
3001
3002    int permissionInfoFootprint(PermissionInfo info) {
3003        int size = info.name.length();
3004        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3005        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3006        return size;
3007    }
3008
3009    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3010        int size = 0;
3011        for (BasePermission perm : mSettings.mPermissions.values()) {
3012            if (perm.uid == tree.uid) {
3013                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3014            }
3015        }
3016        return size;
3017    }
3018
3019    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3020        // We calculate the max size of permissions defined by this uid and throw
3021        // if that plus the size of 'info' would exceed our stated maximum.
3022        if (tree.uid != Process.SYSTEM_UID) {
3023            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3024            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3025                throw new SecurityException("Permission tree size cap exceeded");
3026            }
3027        }
3028    }
3029
3030    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3031        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3032            throw new SecurityException("Label must be specified in permission");
3033        }
3034        BasePermission tree = checkPermissionTreeLP(info.name);
3035        BasePermission bp = mSettings.mPermissions.get(info.name);
3036        boolean added = bp == null;
3037        boolean changed = true;
3038        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3039        if (added) {
3040            enforcePermissionCapLocked(info, tree);
3041            bp = new BasePermission(info.name, tree.sourcePackage,
3042                    BasePermission.TYPE_DYNAMIC);
3043        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3044            throw new SecurityException(
3045                    "Not allowed to modify non-dynamic permission "
3046                    + info.name);
3047        } else {
3048            if (bp.protectionLevel == fixedLevel
3049                    && bp.perm.owner.equals(tree.perm.owner)
3050                    && bp.uid == tree.uid
3051                    && comparePermissionInfos(bp.perm.info, info)) {
3052                changed = false;
3053            }
3054        }
3055        bp.protectionLevel = fixedLevel;
3056        info = new PermissionInfo(info);
3057        info.protectionLevel = fixedLevel;
3058        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3059        bp.perm.info.packageName = tree.perm.info.packageName;
3060        bp.uid = tree.uid;
3061        if (added) {
3062            mSettings.mPermissions.put(info.name, bp);
3063        }
3064        if (changed) {
3065            if (!async) {
3066                mSettings.writeLPr();
3067            } else {
3068                scheduleWriteSettingsLocked();
3069            }
3070        }
3071        return added;
3072    }
3073
3074    @Override
3075    public boolean addPermission(PermissionInfo info) {
3076        synchronized (mPackages) {
3077            return addPermissionLocked(info, false);
3078        }
3079    }
3080
3081    @Override
3082    public boolean addPermissionAsync(PermissionInfo info) {
3083        synchronized (mPackages) {
3084            return addPermissionLocked(info, true);
3085        }
3086    }
3087
3088    @Override
3089    public void removePermission(String name) {
3090        synchronized (mPackages) {
3091            checkPermissionTreeLP(name);
3092            BasePermission bp = mSettings.mPermissions.get(name);
3093            if (bp != null) {
3094                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3095                    throw new SecurityException(
3096                            "Not allowed to modify non-dynamic permission "
3097                            + name);
3098                }
3099                mSettings.mPermissions.remove(name);
3100                mSettings.writeLPr();
3101            }
3102        }
3103    }
3104
3105    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3106            BasePermission bp) {
3107        int index = pkg.requestedPermissions.indexOf(bp.name);
3108        if (index == -1) {
3109            throw new SecurityException("Package " + pkg.packageName
3110                    + " has not requested permission " + bp.name);
3111        }
3112        if (!bp.isRuntime()) {
3113            throw new SecurityException("Permission " + bp.name
3114                    + " is not a changeable permission type");
3115        }
3116    }
3117
3118    @Override
3119    public boolean grantPermission(String packageName, String name, int userId) {
3120        if (!RUNTIME_PERMISSIONS_ENABLED) {
3121            return false;
3122        }
3123
3124        if (!sUserManager.exists(userId)) {
3125            return false;
3126        }
3127
3128        mContext.enforceCallingOrSelfPermission(
3129                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3130                "grantPermission");
3131
3132        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3133                "grantPermission");
3134
3135        boolean gidsChanged = false;
3136        final SettingBase sb;
3137
3138        synchronized (mPackages) {
3139            final PackageParser.Package pkg = mPackages.get(packageName);
3140            if (pkg == null) {
3141                throw new IllegalArgumentException("Unknown package: " + packageName);
3142            }
3143
3144            final BasePermission bp = mSettings.mPermissions.get(name);
3145            if (bp == null) {
3146                throw new IllegalArgumentException("Unknown permission: " + name);
3147            }
3148
3149            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3150
3151            sb = (SettingBase) pkg.mExtras;
3152            if (sb == null) {
3153                throw new IllegalArgumentException("Unknown package: " + packageName);
3154            }
3155
3156            final PermissionsState permissionsState = sb.getPermissionsState();
3157
3158            final int result = permissionsState.grantRuntimePermission(bp, userId);
3159            switch (result) {
3160                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3161                    return false;
3162                }
3163
3164                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3165                    gidsChanged = true;
3166                } break;
3167            }
3168
3169            // Not critical if that is lost - app has to request again.
3170            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3171        }
3172
3173        if (gidsChanged) {
3174            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3175        }
3176
3177        return true;
3178    }
3179
3180    @Override
3181    public boolean revokePermission(String packageName, String name, int userId) {
3182        if (!RUNTIME_PERMISSIONS_ENABLED) {
3183            return false;
3184        }
3185
3186        if (!sUserManager.exists(userId)) {
3187            return false;
3188        }
3189
3190        mContext.enforceCallingOrSelfPermission(
3191                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3192                "revokePermission");
3193
3194        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3195                "revokePermission");
3196
3197        final SettingBase sb;
3198
3199        synchronized (mPackages) {
3200            final PackageParser.Package pkg = mPackages.get(packageName);
3201            if (pkg == null) {
3202                throw new IllegalArgumentException("Unknown package: " + packageName);
3203            }
3204
3205            final BasePermission bp = mSettings.mPermissions.get(name);
3206            if (bp == null) {
3207                throw new IllegalArgumentException("Unknown permission: " + name);
3208            }
3209
3210            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3211
3212            sb = (SettingBase) pkg.mExtras;
3213            if (sb == null) {
3214                throw new IllegalArgumentException("Unknown package: " + packageName);
3215            }
3216
3217            final PermissionsState permissionsState = sb.getPermissionsState();
3218
3219            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3220                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3221                return false;
3222            }
3223
3224            // Critical, after this call all should never have the permission.
3225            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3226        }
3227
3228        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3229
3230        return true;
3231    }
3232
3233    @Override
3234    public boolean isProtectedBroadcast(String actionName) {
3235        synchronized (mPackages) {
3236            return mProtectedBroadcasts.contains(actionName);
3237        }
3238    }
3239
3240    @Override
3241    public int checkSignatures(String pkg1, String pkg2) {
3242        synchronized (mPackages) {
3243            final PackageParser.Package p1 = mPackages.get(pkg1);
3244            final PackageParser.Package p2 = mPackages.get(pkg2);
3245            if (p1 == null || p1.mExtras == null
3246                    || p2 == null || p2.mExtras == null) {
3247                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3248            }
3249            return compareSignatures(p1.mSignatures, p2.mSignatures);
3250        }
3251    }
3252
3253    @Override
3254    public int checkUidSignatures(int uid1, int uid2) {
3255        // Map to base uids.
3256        uid1 = UserHandle.getAppId(uid1);
3257        uid2 = UserHandle.getAppId(uid2);
3258        // reader
3259        synchronized (mPackages) {
3260            Signature[] s1;
3261            Signature[] s2;
3262            Object obj = mSettings.getUserIdLPr(uid1);
3263            if (obj != null) {
3264                if (obj instanceof SharedUserSetting) {
3265                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3266                } else if (obj instanceof PackageSetting) {
3267                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3268                } else {
3269                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3270                }
3271            } else {
3272                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3273            }
3274            obj = mSettings.getUserIdLPr(uid2);
3275            if (obj != null) {
3276                if (obj instanceof SharedUserSetting) {
3277                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3278                } else if (obj instanceof PackageSetting) {
3279                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3280                } else {
3281                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3282                }
3283            } else {
3284                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3285            }
3286            return compareSignatures(s1, s2);
3287        }
3288    }
3289
3290    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3291        final long identity = Binder.clearCallingIdentity();
3292        try {
3293            if (sb instanceof SharedUserSetting) {
3294                SharedUserSetting sus = (SharedUserSetting) sb;
3295                final int packageCount = sus.packages.size();
3296                for (int i = 0; i < packageCount; i++) {
3297                    PackageSetting susPs = sus.packages.valueAt(i);
3298                    if (userId == UserHandle.USER_ALL) {
3299                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3300                    } else {
3301                        final int uid = UserHandle.getUid(userId, susPs.appId);
3302                        killUid(uid, reason);
3303                    }
3304                }
3305            } else if (sb instanceof PackageSetting) {
3306                PackageSetting ps = (PackageSetting) sb;
3307                if (userId == UserHandle.USER_ALL) {
3308                    killApplication(ps.pkg.packageName, ps.appId, reason);
3309                } else {
3310                    final int uid = UserHandle.getUid(userId, ps.appId);
3311                    killUid(uid, reason);
3312                }
3313            }
3314        } finally {
3315            Binder.restoreCallingIdentity(identity);
3316        }
3317    }
3318
3319    private static void killUid(int uid, String reason) {
3320        IActivityManager am = ActivityManagerNative.getDefault();
3321        if (am != null) {
3322            try {
3323                am.killUid(uid, reason);
3324            } catch (RemoteException e) {
3325                /* ignore - same process */
3326            }
3327        }
3328    }
3329
3330    /**
3331     * Compares two sets of signatures. Returns:
3332     * <br />
3333     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3334     * <br />
3335     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3336     * <br />
3337     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3338     * <br />
3339     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3340     * <br />
3341     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3342     */
3343    static int compareSignatures(Signature[] s1, Signature[] s2) {
3344        if (s1 == null) {
3345            return s2 == null
3346                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3347                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3348        }
3349
3350        if (s2 == null) {
3351            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3352        }
3353
3354        if (s1.length != s2.length) {
3355            return PackageManager.SIGNATURE_NO_MATCH;
3356        }
3357
3358        // Since both signature sets are of size 1, we can compare without HashSets.
3359        if (s1.length == 1) {
3360            return s1[0].equals(s2[0]) ?
3361                    PackageManager.SIGNATURE_MATCH :
3362                    PackageManager.SIGNATURE_NO_MATCH;
3363        }
3364
3365        ArraySet<Signature> set1 = new ArraySet<Signature>();
3366        for (Signature sig : s1) {
3367            set1.add(sig);
3368        }
3369        ArraySet<Signature> set2 = new ArraySet<Signature>();
3370        for (Signature sig : s2) {
3371            set2.add(sig);
3372        }
3373        // Make sure s2 contains all signatures in s1.
3374        if (set1.equals(set2)) {
3375            return PackageManager.SIGNATURE_MATCH;
3376        }
3377        return PackageManager.SIGNATURE_NO_MATCH;
3378    }
3379
3380    /**
3381     * If the database version for this type of package (internal storage or
3382     * external storage) is less than the version where package signatures
3383     * were updated, return true.
3384     */
3385    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3386        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3387                DatabaseVersion.SIGNATURE_END_ENTITY))
3388                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3389                        DatabaseVersion.SIGNATURE_END_ENTITY));
3390    }
3391
3392    /**
3393     * Used for backward compatibility to make sure any packages with
3394     * certificate chains get upgraded to the new style. {@code existingSigs}
3395     * will be in the old format (since they were stored on disk from before the
3396     * system upgrade) and {@code scannedSigs} will be in the newer format.
3397     */
3398    private int compareSignaturesCompat(PackageSignatures existingSigs,
3399            PackageParser.Package scannedPkg) {
3400        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3401            return PackageManager.SIGNATURE_NO_MATCH;
3402        }
3403
3404        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3405        for (Signature sig : existingSigs.mSignatures) {
3406            existingSet.add(sig);
3407        }
3408        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3409        for (Signature sig : scannedPkg.mSignatures) {
3410            try {
3411                Signature[] chainSignatures = sig.getChainSignatures();
3412                for (Signature chainSig : chainSignatures) {
3413                    scannedCompatSet.add(chainSig);
3414                }
3415            } catch (CertificateEncodingException e) {
3416                scannedCompatSet.add(sig);
3417            }
3418        }
3419        /*
3420         * Make sure the expanded scanned set contains all signatures in the
3421         * existing one.
3422         */
3423        if (scannedCompatSet.equals(existingSet)) {
3424            // Migrate the old signatures to the new scheme.
3425            existingSigs.assignSignatures(scannedPkg.mSignatures);
3426            // The new KeySets will be re-added later in the scanning process.
3427            synchronized (mPackages) {
3428                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3429            }
3430            return PackageManager.SIGNATURE_MATCH;
3431        }
3432        return PackageManager.SIGNATURE_NO_MATCH;
3433    }
3434
3435    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3436        if (isExternal(scannedPkg)) {
3437            return mSettings.isExternalDatabaseVersionOlderThan(
3438                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3439        } else {
3440            return mSettings.isInternalDatabaseVersionOlderThan(
3441                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3442        }
3443    }
3444
3445    private int compareSignaturesRecover(PackageSignatures existingSigs,
3446            PackageParser.Package scannedPkg) {
3447        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3448            return PackageManager.SIGNATURE_NO_MATCH;
3449        }
3450
3451        String msg = null;
3452        try {
3453            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3454                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3455                        + scannedPkg.packageName);
3456                return PackageManager.SIGNATURE_MATCH;
3457            }
3458        } catch (CertificateException e) {
3459            msg = e.getMessage();
3460        }
3461
3462        logCriticalInfo(Log.INFO,
3463                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3464        return PackageManager.SIGNATURE_NO_MATCH;
3465    }
3466
3467    @Override
3468    public String[] getPackagesForUid(int uid) {
3469        uid = UserHandle.getAppId(uid);
3470        // reader
3471        synchronized (mPackages) {
3472            Object obj = mSettings.getUserIdLPr(uid);
3473            if (obj instanceof SharedUserSetting) {
3474                final SharedUserSetting sus = (SharedUserSetting) obj;
3475                final int N = sus.packages.size();
3476                final String[] res = new String[N];
3477                final Iterator<PackageSetting> it = sus.packages.iterator();
3478                int i = 0;
3479                while (it.hasNext()) {
3480                    res[i++] = it.next().name;
3481                }
3482                return res;
3483            } else if (obj instanceof PackageSetting) {
3484                final PackageSetting ps = (PackageSetting) obj;
3485                return new String[] { ps.name };
3486            }
3487        }
3488        return null;
3489    }
3490
3491    @Override
3492    public String getNameForUid(int uid) {
3493        // reader
3494        synchronized (mPackages) {
3495            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3496            if (obj instanceof SharedUserSetting) {
3497                final SharedUserSetting sus = (SharedUserSetting) obj;
3498                return sus.name + ":" + sus.userId;
3499            } else if (obj instanceof PackageSetting) {
3500                final PackageSetting ps = (PackageSetting) obj;
3501                return ps.name;
3502            }
3503        }
3504        return null;
3505    }
3506
3507    @Override
3508    public int getUidForSharedUser(String sharedUserName) {
3509        if(sharedUserName == null) {
3510            return -1;
3511        }
3512        // reader
3513        synchronized (mPackages) {
3514            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3515            if (suid == null) {
3516                return -1;
3517            }
3518            return suid.userId;
3519        }
3520    }
3521
3522    @Override
3523    public int getFlagsForUid(int uid) {
3524        synchronized (mPackages) {
3525            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3526            if (obj instanceof SharedUserSetting) {
3527                final SharedUserSetting sus = (SharedUserSetting) obj;
3528                return sus.pkgFlags;
3529            } else if (obj instanceof PackageSetting) {
3530                final PackageSetting ps = (PackageSetting) obj;
3531                return ps.pkgFlags;
3532            }
3533        }
3534        return 0;
3535    }
3536
3537    @Override
3538    public int getPrivateFlagsForUid(int uid) {
3539        synchronized (mPackages) {
3540            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3541            if (obj instanceof SharedUserSetting) {
3542                final SharedUserSetting sus = (SharedUserSetting) obj;
3543                return sus.pkgPrivateFlags;
3544            } else if (obj instanceof PackageSetting) {
3545                final PackageSetting ps = (PackageSetting) obj;
3546                return ps.pkgPrivateFlags;
3547            }
3548        }
3549        return 0;
3550    }
3551
3552    @Override
3553    public boolean isUidPrivileged(int uid) {
3554        uid = UserHandle.getAppId(uid);
3555        // reader
3556        synchronized (mPackages) {
3557            Object obj = mSettings.getUserIdLPr(uid);
3558            if (obj instanceof SharedUserSetting) {
3559                final SharedUserSetting sus = (SharedUserSetting) obj;
3560                final Iterator<PackageSetting> it = sus.packages.iterator();
3561                while (it.hasNext()) {
3562                    if (it.next().isPrivileged()) {
3563                        return true;
3564                    }
3565                }
3566            } else if (obj instanceof PackageSetting) {
3567                final PackageSetting ps = (PackageSetting) obj;
3568                return ps.isPrivileged();
3569            }
3570        }
3571        return false;
3572    }
3573
3574    @Override
3575    public String[] getAppOpPermissionPackages(String permissionName) {
3576        synchronized (mPackages) {
3577            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3578            if (pkgs == null) {
3579                return null;
3580            }
3581            return pkgs.toArray(new String[pkgs.size()]);
3582        }
3583    }
3584
3585    @Override
3586    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3587            int flags, int userId) {
3588        if (!sUserManager.exists(userId)) return null;
3589        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3590        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3591        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3592    }
3593
3594    @Override
3595    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3596            IntentFilter filter, int match, ComponentName activity) {
3597        final int userId = UserHandle.getCallingUserId();
3598        if (DEBUG_PREFERRED) {
3599            Log.v(TAG, "setLastChosenActivity intent=" + intent
3600                + " resolvedType=" + resolvedType
3601                + " flags=" + flags
3602                + " filter=" + filter
3603                + " match=" + match
3604                + " activity=" + activity);
3605            filter.dump(new PrintStreamPrinter(System.out), "    ");
3606        }
3607        intent.setComponent(null);
3608        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3609        // Find any earlier preferred or last chosen entries and nuke them
3610        findPreferredActivity(intent, resolvedType,
3611                flags, query, 0, false, true, false, userId);
3612        // Add the new activity as the last chosen for this filter
3613        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3614                "Setting last chosen");
3615    }
3616
3617    @Override
3618    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3619        final int userId = UserHandle.getCallingUserId();
3620        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3621        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3622        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3623                false, false, false, userId);
3624    }
3625
3626    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3627            int flags, List<ResolveInfo> query, int userId) {
3628        if (query != null) {
3629            final int N = query.size();
3630            if (N == 1) {
3631                return query.get(0);
3632            } else if (N > 1) {
3633                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3634                // If there is more than one activity with the same priority,
3635                // then let the user decide between them.
3636                ResolveInfo r0 = query.get(0);
3637                ResolveInfo r1 = query.get(1);
3638                if (DEBUG_INTENT_MATCHING || debug) {
3639                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3640                            + r1.activityInfo.name + "=" + r1.priority);
3641                }
3642                // If the first activity has a higher priority, or a different
3643                // default, then it is always desireable to pick it.
3644                if (r0.priority != r1.priority
3645                        || r0.preferredOrder != r1.preferredOrder
3646                        || r0.isDefault != r1.isDefault) {
3647                    return query.get(0);
3648                }
3649                // If we have saved a preference for a preferred activity for
3650                // this Intent, use that.
3651                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3652                        flags, query, r0.priority, true, false, debug, userId);
3653                if (ri != null) {
3654                    return ri;
3655                }
3656                if (userId != 0) {
3657                    ri = new ResolveInfo(mResolveInfo);
3658                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3659                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3660                            ri.activityInfo.applicationInfo);
3661                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3662                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3663                    return ri;
3664                }
3665                return mResolveInfo;
3666            }
3667        }
3668        return null;
3669    }
3670
3671    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3672            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3673        final int N = query.size();
3674        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3675                .get(userId);
3676        // Get the list of persistent preferred activities that handle the intent
3677        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3678        List<PersistentPreferredActivity> pprefs = ppir != null
3679                ? ppir.queryIntent(intent, resolvedType,
3680                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3681                : null;
3682        if (pprefs != null && pprefs.size() > 0) {
3683            final int M = pprefs.size();
3684            for (int i=0; i<M; i++) {
3685                final PersistentPreferredActivity ppa = pprefs.get(i);
3686                if (DEBUG_PREFERRED || debug) {
3687                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3688                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3689                            + "\n  component=" + ppa.mComponent);
3690                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3691                }
3692                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3693                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3694                if (DEBUG_PREFERRED || debug) {
3695                    Slog.v(TAG, "Found persistent preferred activity:");
3696                    if (ai != null) {
3697                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3698                    } else {
3699                        Slog.v(TAG, "  null");
3700                    }
3701                }
3702                if (ai == null) {
3703                    // This previously registered persistent preferred activity
3704                    // component is no longer known. Ignore it and do NOT remove it.
3705                    continue;
3706                }
3707                for (int j=0; j<N; j++) {
3708                    final ResolveInfo ri = query.get(j);
3709                    if (!ri.activityInfo.applicationInfo.packageName
3710                            .equals(ai.applicationInfo.packageName)) {
3711                        continue;
3712                    }
3713                    if (!ri.activityInfo.name.equals(ai.name)) {
3714                        continue;
3715                    }
3716                    //  Found a persistent preference that can handle the intent.
3717                    if (DEBUG_PREFERRED || debug) {
3718                        Slog.v(TAG, "Returning persistent preferred activity: " +
3719                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3720                    }
3721                    return ri;
3722                }
3723            }
3724        }
3725        return null;
3726    }
3727
3728    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3729            List<ResolveInfo> query, int priority, boolean always,
3730            boolean removeMatches, boolean debug, int userId) {
3731        if (!sUserManager.exists(userId)) return null;
3732        // writer
3733        synchronized (mPackages) {
3734            if (intent.getSelector() != null) {
3735                intent = intent.getSelector();
3736            }
3737            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3738
3739            // Try to find a matching persistent preferred activity.
3740            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3741                    debug, userId);
3742
3743            // If a persistent preferred activity matched, use it.
3744            if (pri != null) {
3745                return pri;
3746            }
3747
3748            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3749            // Get the list of preferred activities that handle the intent
3750            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3751            List<PreferredActivity> prefs = pir != null
3752                    ? pir.queryIntent(intent, resolvedType,
3753                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3754                    : null;
3755            if (prefs != null && prefs.size() > 0) {
3756                boolean changed = false;
3757                try {
3758                    // First figure out how good the original match set is.
3759                    // We will only allow preferred activities that came
3760                    // from the same match quality.
3761                    int match = 0;
3762
3763                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3764
3765                    final int N = query.size();
3766                    for (int j=0; j<N; j++) {
3767                        final ResolveInfo ri = query.get(j);
3768                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3769                                + ": 0x" + Integer.toHexString(match));
3770                        if (ri.match > match) {
3771                            match = ri.match;
3772                        }
3773                    }
3774
3775                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3776                            + Integer.toHexString(match));
3777
3778                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3779                    final int M = prefs.size();
3780                    for (int i=0; i<M; i++) {
3781                        final PreferredActivity pa = prefs.get(i);
3782                        if (DEBUG_PREFERRED || debug) {
3783                            Slog.v(TAG, "Checking PreferredActivity ds="
3784                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3785                                    + "\n  component=" + pa.mPref.mComponent);
3786                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3787                        }
3788                        if (pa.mPref.mMatch != match) {
3789                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3790                                    + Integer.toHexString(pa.mPref.mMatch));
3791                            continue;
3792                        }
3793                        // If it's not an "always" type preferred activity and that's what we're
3794                        // looking for, skip it.
3795                        if (always && !pa.mPref.mAlways) {
3796                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3797                            continue;
3798                        }
3799                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3800                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3801                        if (DEBUG_PREFERRED || debug) {
3802                            Slog.v(TAG, "Found preferred activity:");
3803                            if (ai != null) {
3804                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3805                            } else {
3806                                Slog.v(TAG, "  null");
3807                            }
3808                        }
3809                        if (ai == null) {
3810                            // This previously registered preferred activity
3811                            // component is no longer known.  Most likely an update
3812                            // to the app was installed and in the new version this
3813                            // component no longer exists.  Clean it up by removing
3814                            // it from the preferred activities list, and skip it.
3815                            Slog.w(TAG, "Removing dangling preferred activity: "
3816                                    + pa.mPref.mComponent);
3817                            pir.removeFilter(pa);
3818                            changed = true;
3819                            continue;
3820                        }
3821                        for (int j=0; j<N; j++) {
3822                            final ResolveInfo ri = query.get(j);
3823                            if (!ri.activityInfo.applicationInfo.packageName
3824                                    .equals(ai.applicationInfo.packageName)) {
3825                                continue;
3826                            }
3827                            if (!ri.activityInfo.name.equals(ai.name)) {
3828                                continue;
3829                            }
3830
3831                            if (removeMatches) {
3832                                pir.removeFilter(pa);
3833                                changed = true;
3834                                if (DEBUG_PREFERRED) {
3835                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3836                                }
3837                                break;
3838                            }
3839
3840                            // Okay we found a previously set preferred or last chosen app.
3841                            // If the result set is different from when this
3842                            // was created, we need to clear it and re-ask the
3843                            // user their preference, if we're looking for an "always" type entry.
3844                            if (always && !pa.mPref.sameSet(query)) {
3845                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3846                                        + intent + " type " + resolvedType);
3847                                if (DEBUG_PREFERRED) {
3848                                    Slog.v(TAG, "Removing preferred activity since set changed "
3849                                            + pa.mPref.mComponent);
3850                                }
3851                                pir.removeFilter(pa);
3852                                // Re-add the filter as a "last chosen" entry (!always)
3853                                PreferredActivity lastChosen = new PreferredActivity(
3854                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3855                                pir.addFilter(lastChosen);
3856                                changed = true;
3857                                return null;
3858                            }
3859
3860                            // Yay! Either the set matched or we're looking for the last chosen
3861                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3862                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3863                            return ri;
3864                        }
3865                    }
3866                } finally {
3867                    if (changed) {
3868                        if (DEBUG_PREFERRED) {
3869                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3870                        }
3871                        scheduleWritePackageRestrictionsLocked(userId);
3872                    }
3873                }
3874            }
3875        }
3876        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3877        return null;
3878    }
3879
3880    /*
3881     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3882     */
3883    @Override
3884    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3885            int targetUserId) {
3886        mContext.enforceCallingOrSelfPermission(
3887                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3888        List<CrossProfileIntentFilter> matches =
3889                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3890        if (matches != null) {
3891            int size = matches.size();
3892            for (int i = 0; i < size; i++) {
3893                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3894            }
3895        }
3896        return false;
3897    }
3898
3899    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3900            String resolvedType, int userId) {
3901        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3902        if (resolver != null) {
3903            return resolver.queryIntent(intent, resolvedType, false, userId);
3904        }
3905        return null;
3906    }
3907
3908    @Override
3909    public List<ResolveInfo> queryIntentActivities(Intent intent,
3910            String resolvedType, int flags, int userId) {
3911        if (!sUserManager.exists(userId)) return Collections.emptyList();
3912        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3913        ComponentName comp = intent.getComponent();
3914        if (comp == null) {
3915            if (intent.getSelector() != null) {
3916                intent = intent.getSelector();
3917                comp = intent.getComponent();
3918            }
3919        }
3920
3921        if (comp != null) {
3922            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3923            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3924            if (ai != null) {
3925                final ResolveInfo ri = new ResolveInfo();
3926                ri.activityInfo = ai;
3927                list.add(ri);
3928            }
3929            return list;
3930        }
3931
3932        // reader
3933        synchronized (mPackages) {
3934            final String pkgName = intent.getPackage();
3935            if (pkgName == null) {
3936                List<CrossProfileIntentFilter> matchingFilters =
3937                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3938                // Check for results that need to skip the current profile.
3939                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3940                        resolvedType, flags, userId);
3941                if (resolveInfo != null) {
3942                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3943                    result.add(resolveInfo);
3944                    return filterIfNotPrimaryUser(result, userId);
3945                }
3946                // Check for cross profile results.
3947                resolveInfo = queryCrossProfileIntents(
3948                        matchingFilters, intent, resolvedType, flags, userId);
3949
3950                // Check for results in the current profile.
3951                List<ResolveInfo> result = mActivities.queryIntent(
3952                        intent, resolvedType, flags, userId);
3953                if (resolveInfo != null) {
3954                    result.add(resolveInfo);
3955                    Collections.sort(result, mResolvePrioritySorter);
3956                }
3957                result = filterIfNotPrimaryUser(result, userId);
3958                if (result.size() > 1 && hasWebURI(intent)) {
3959                    return filterCandidatesWithDomainPreferedActivitiesLPr(result);
3960                }
3961                return result;
3962            }
3963            final PackageParser.Package pkg = mPackages.get(pkgName);
3964            if (pkg != null) {
3965                return filterIfNotPrimaryUser(
3966                        mActivities.queryIntentForPackage(
3967                                intent, resolvedType, flags, pkg.activities, userId),
3968                        userId);
3969            }
3970            return new ArrayList<ResolveInfo>();
3971        }
3972    }
3973
3974    /**
3975     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
3976     *
3977     * @return filtered list
3978     */
3979    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
3980        if (userId == UserHandle.USER_OWNER) {
3981            return resolveInfos;
3982        }
3983        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
3984            ResolveInfo info = resolveInfos.get(i);
3985            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
3986                resolveInfos.remove(i);
3987            }
3988        }
3989        return resolveInfos;
3990    }
3991
3992    private static boolean hasWebURI(Intent intent) {
3993        if (intent.getData() == null) {
3994            return false;
3995        }
3996        final String scheme = intent.getScheme();
3997        if (TextUtils.isEmpty(scheme)) {
3998            return false;
3999        }
4000        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4001    }
4002
4003    private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr(
4004            List<ResolveInfo> candidates) {
4005        if (DEBUG_PREFERRED) {
4006            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4007                    candidates.size());
4008        }
4009
4010        final int userId = UserHandle.getCallingUserId();
4011        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4012        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4013        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4014        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4015
4016        synchronized (mPackages) {
4017            final int count = candidates.size();
4018            // First, try to use the domain prefered App
4019            for (int n=0; n<count; n++) {
4020                ResolveInfo info = candidates.get(n);
4021                String packageName = info.activityInfo.packageName;
4022                PackageSetting ps = mSettings.mPackages.get(packageName);
4023                if (ps != null) {
4024                    // Try to get the status from User settings first
4025                    int status = getDomainVerificationStatusLPr(ps, userId);
4026                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4027                        result.add(info);
4028                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4029                        neverList.add(info);
4030                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4031                        undefinedList.add(info);
4032                    }
4033                    // Add to the special match all list (Browser use case)
4034                    if (info.handleAllWebDataURI) {
4035                        matchAllList.add(info);
4036                    }
4037                }
4038            }
4039            // If there is nothing selected, add all candidates and remove the ones that the User
4040            // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and
4041            // also remove any Browser Apps ones.
4042            // If there is still none after this pass, add all undefined one and Browser Apps and
4043            // let the User decide with the Disambiguation dialog if there are several ones.
4044            if (result.size() == 0) {
4045                result.addAll(candidates);
4046            }
4047            result.removeAll(neverList);
4048            result.removeAll(matchAllList);
4049            if (result.size() == 0) {
4050                result.addAll(undefinedList);
4051                result.addAll(matchAllList);
4052            }
4053        }
4054        if (DEBUG_PREFERRED) {
4055            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4056                    result.size());
4057        }
4058        return result;
4059    }
4060
4061    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4062        int status = ps.getDomainVerificationStatusForUser(userId);
4063        // if none available, get the master status
4064        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4065            if (ps.getIntentFilterVerificationInfo() != null) {
4066                status = ps.getIntentFilterVerificationInfo().getStatus();
4067            }
4068        }
4069        return status;
4070    }
4071
4072    private ResolveInfo querySkipCurrentProfileIntents(
4073            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4074            int flags, int sourceUserId) {
4075        if (matchingFilters != null) {
4076            int size = matchingFilters.size();
4077            for (int i = 0; i < size; i ++) {
4078                CrossProfileIntentFilter filter = matchingFilters.get(i);
4079                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4080                    // Checking if there are activities in the target user that can handle the
4081                    // intent.
4082                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4083                            flags, sourceUserId);
4084                    if (resolveInfo != null) {
4085                        return resolveInfo;
4086                    }
4087                }
4088            }
4089        }
4090        return null;
4091    }
4092
4093    // Return matching ResolveInfo if any for skip current profile intent filters.
4094    private ResolveInfo queryCrossProfileIntents(
4095            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4096            int flags, int sourceUserId) {
4097        if (matchingFilters != null) {
4098            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4099            // match the same intent. For performance reasons, it is better not to
4100            // run queryIntent twice for the same userId
4101            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4102            int size = matchingFilters.size();
4103            for (int i = 0; i < size; i++) {
4104                CrossProfileIntentFilter filter = matchingFilters.get(i);
4105                int targetUserId = filter.getTargetUserId();
4106                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4107                        && !alreadyTriedUserIds.get(targetUserId)) {
4108                    // Checking if there are activities in the target user that can handle the
4109                    // intent.
4110                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4111                            flags, sourceUserId);
4112                    if (resolveInfo != null) return resolveInfo;
4113                    alreadyTriedUserIds.put(targetUserId, true);
4114                }
4115            }
4116        }
4117        return null;
4118    }
4119
4120    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4121            String resolvedType, int flags, int sourceUserId) {
4122        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4123                resolvedType, flags, filter.getTargetUserId());
4124        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4125            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4126        }
4127        return null;
4128    }
4129
4130    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4131            int sourceUserId, int targetUserId) {
4132        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4133        String className;
4134        if (targetUserId == UserHandle.USER_OWNER) {
4135            className = FORWARD_INTENT_TO_USER_OWNER;
4136        } else {
4137            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4138        }
4139        ComponentName forwardingActivityComponentName = new ComponentName(
4140                mAndroidApplication.packageName, className);
4141        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4142                sourceUserId);
4143        if (targetUserId == UserHandle.USER_OWNER) {
4144            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4145            forwardingResolveInfo.noResourceId = true;
4146        }
4147        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4148        forwardingResolveInfo.priority = 0;
4149        forwardingResolveInfo.preferredOrder = 0;
4150        forwardingResolveInfo.match = 0;
4151        forwardingResolveInfo.isDefault = true;
4152        forwardingResolveInfo.filter = filter;
4153        forwardingResolveInfo.targetUserId = targetUserId;
4154        return forwardingResolveInfo;
4155    }
4156
4157    @Override
4158    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4159            Intent[] specifics, String[] specificTypes, Intent intent,
4160            String resolvedType, int flags, int userId) {
4161        if (!sUserManager.exists(userId)) return Collections.emptyList();
4162        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4163                false, "query intent activity options");
4164        final String resultsAction = intent.getAction();
4165
4166        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4167                | PackageManager.GET_RESOLVED_FILTER, userId);
4168
4169        if (DEBUG_INTENT_MATCHING) {
4170            Log.v(TAG, "Query " + intent + ": " + results);
4171        }
4172
4173        int specificsPos = 0;
4174        int N;
4175
4176        // todo: note that the algorithm used here is O(N^2).  This
4177        // isn't a problem in our current environment, but if we start running
4178        // into situations where we have more than 5 or 10 matches then this
4179        // should probably be changed to something smarter...
4180
4181        // First we go through and resolve each of the specific items
4182        // that were supplied, taking care of removing any corresponding
4183        // duplicate items in the generic resolve list.
4184        if (specifics != null) {
4185            for (int i=0; i<specifics.length; i++) {
4186                final Intent sintent = specifics[i];
4187                if (sintent == null) {
4188                    continue;
4189                }
4190
4191                if (DEBUG_INTENT_MATCHING) {
4192                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4193                }
4194
4195                String action = sintent.getAction();
4196                if (resultsAction != null && resultsAction.equals(action)) {
4197                    // If this action was explicitly requested, then don't
4198                    // remove things that have it.
4199                    action = null;
4200                }
4201
4202                ResolveInfo ri = null;
4203                ActivityInfo ai = null;
4204
4205                ComponentName comp = sintent.getComponent();
4206                if (comp == null) {
4207                    ri = resolveIntent(
4208                        sintent,
4209                        specificTypes != null ? specificTypes[i] : null,
4210                            flags, userId);
4211                    if (ri == null) {
4212                        continue;
4213                    }
4214                    if (ri == mResolveInfo) {
4215                        // ACK!  Must do something better with this.
4216                    }
4217                    ai = ri.activityInfo;
4218                    comp = new ComponentName(ai.applicationInfo.packageName,
4219                            ai.name);
4220                } else {
4221                    ai = getActivityInfo(comp, flags, userId);
4222                    if (ai == null) {
4223                        continue;
4224                    }
4225                }
4226
4227                // Look for any generic query activities that are duplicates
4228                // of this specific one, and remove them from the results.
4229                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4230                N = results.size();
4231                int j;
4232                for (j=specificsPos; j<N; j++) {
4233                    ResolveInfo sri = results.get(j);
4234                    if ((sri.activityInfo.name.equals(comp.getClassName())
4235                            && sri.activityInfo.applicationInfo.packageName.equals(
4236                                    comp.getPackageName()))
4237                        || (action != null && sri.filter.matchAction(action))) {
4238                        results.remove(j);
4239                        if (DEBUG_INTENT_MATCHING) Log.v(
4240                            TAG, "Removing duplicate item from " + j
4241                            + " due to specific " + specificsPos);
4242                        if (ri == null) {
4243                            ri = sri;
4244                        }
4245                        j--;
4246                        N--;
4247                    }
4248                }
4249
4250                // Add this specific item to its proper place.
4251                if (ri == null) {
4252                    ri = new ResolveInfo();
4253                    ri.activityInfo = ai;
4254                }
4255                results.add(specificsPos, ri);
4256                ri.specificIndex = i;
4257                specificsPos++;
4258            }
4259        }
4260
4261        // Now we go through the remaining generic results and remove any
4262        // duplicate actions that are found here.
4263        N = results.size();
4264        for (int i=specificsPos; i<N-1; i++) {
4265            final ResolveInfo rii = results.get(i);
4266            if (rii.filter == null) {
4267                continue;
4268            }
4269
4270            // Iterate over all of the actions of this result's intent
4271            // filter...  typically this should be just one.
4272            final Iterator<String> it = rii.filter.actionsIterator();
4273            if (it == null) {
4274                continue;
4275            }
4276            while (it.hasNext()) {
4277                final String action = it.next();
4278                if (resultsAction != null && resultsAction.equals(action)) {
4279                    // If this action was explicitly requested, then don't
4280                    // remove things that have it.
4281                    continue;
4282                }
4283                for (int j=i+1; j<N; j++) {
4284                    final ResolveInfo rij = results.get(j);
4285                    if (rij.filter != null && rij.filter.hasAction(action)) {
4286                        results.remove(j);
4287                        if (DEBUG_INTENT_MATCHING) Log.v(
4288                            TAG, "Removing duplicate item from " + j
4289                            + " due to action " + action + " at " + i);
4290                        j--;
4291                        N--;
4292                    }
4293                }
4294            }
4295
4296            // If the caller didn't request filter information, drop it now
4297            // so we don't have to marshall/unmarshall it.
4298            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4299                rii.filter = null;
4300            }
4301        }
4302
4303        // Filter out the caller activity if so requested.
4304        if (caller != null) {
4305            N = results.size();
4306            for (int i=0; i<N; i++) {
4307                ActivityInfo ainfo = results.get(i).activityInfo;
4308                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4309                        && caller.getClassName().equals(ainfo.name)) {
4310                    results.remove(i);
4311                    break;
4312                }
4313            }
4314        }
4315
4316        // If the caller didn't request filter information,
4317        // drop them now so we don't have to
4318        // marshall/unmarshall it.
4319        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4320            N = results.size();
4321            for (int i=0; i<N; i++) {
4322                results.get(i).filter = null;
4323            }
4324        }
4325
4326        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4327        return results;
4328    }
4329
4330    @Override
4331    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4332            int userId) {
4333        if (!sUserManager.exists(userId)) return Collections.emptyList();
4334        ComponentName comp = intent.getComponent();
4335        if (comp == null) {
4336            if (intent.getSelector() != null) {
4337                intent = intent.getSelector();
4338                comp = intent.getComponent();
4339            }
4340        }
4341        if (comp != null) {
4342            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4343            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4344            if (ai != null) {
4345                ResolveInfo ri = new ResolveInfo();
4346                ri.activityInfo = ai;
4347                list.add(ri);
4348            }
4349            return list;
4350        }
4351
4352        // reader
4353        synchronized (mPackages) {
4354            String pkgName = intent.getPackage();
4355            if (pkgName == null) {
4356                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4357            }
4358            final PackageParser.Package pkg = mPackages.get(pkgName);
4359            if (pkg != null) {
4360                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4361                        userId);
4362            }
4363            return null;
4364        }
4365    }
4366
4367    @Override
4368    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4369        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4370        if (!sUserManager.exists(userId)) return null;
4371        if (query != null) {
4372            if (query.size() >= 1) {
4373                // If there is more than one service with the same priority,
4374                // just arbitrarily pick the first one.
4375                return query.get(0);
4376            }
4377        }
4378        return null;
4379    }
4380
4381    @Override
4382    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4383            int userId) {
4384        if (!sUserManager.exists(userId)) return Collections.emptyList();
4385        ComponentName comp = intent.getComponent();
4386        if (comp == null) {
4387            if (intent.getSelector() != null) {
4388                intent = intent.getSelector();
4389                comp = intent.getComponent();
4390            }
4391        }
4392        if (comp != null) {
4393            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4394            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4395            if (si != null) {
4396                final ResolveInfo ri = new ResolveInfo();
4397                ri.serviceInfo = si;
4398                list.add(ri);
4399            }
4400            return list;
4401        }
4402
4403        // reader
4404        synchronized (mPackages) {
4405            String pkgName = intent.getPackage();
4406            if (pkgName == null) {
4407                return mServices.queryIntent(intent, resolvedType, flags, userId);
4408            }
4409            final PackageParser.Package pkg = mPackages.get(pkgName);
4410            if (pkg != null) {
4411                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4412                        userId);
4413            }
4414            return null;
4415        }
4416    }
4417
4418    @Override
4419    public List<ResolveInfo> queryIntentContentProviders(
4420            Intent intent, String resolvedType, int flags, int userId) {
4421        if (!sUserManager.exists(userId)) return Collections.emptyList();
4422        ComponentName comp = intent.getComponent();
4423        if (comp == null) {
4424            if (intent.getSelector() != null) {
4425                intent = intent.getSelector();
4426                comp = intent.getComponent();
4427            }
4428        }
4429        if (comp != null) {
4430            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4431            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4432            if (pi != null) {
4433                final ResolveInfo ri = new ResolveInfo();
4434                ri.providerInfo = pi;
4435                list.add(ri);
4436            }
4437            return list;
4438        }
4439
4440        // reader
4441        synchronized (mPackages) {
4442            String pkgName = intent.getPackage();
4443            if (pkgName == null) {
4444                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4445            }
4446            final PackageParser.Package pkg = mPackages.get(pkgName);
4447            if (pkg != null) {
4448                return mProviders.queryIntentForPackage(
4449                        intent, resolvedType, flags, pkg.providers, userId);
4450            }
4451            return null;
4452        }
4453    }
4454
4455    @Override
4456    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4457        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4458
4459        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4460
4461        // writer
4462        synchronized (mPackages) {
4463            ArrayList<PackageInfo> list;
4464            if (listUninstalled) {
4465                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4466                for (PackageSetting ps : mSettings.mPackages.values()) {
4467                    PackageInfo pi;
4468                    if (ps.pkg != null) {
4469                        pi = generatePackageInfo(ps.pkg, flags, userId);
4470                    } else {
4471                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4472                    }
4473                    if (pi != null) {
4474                        list.add(pi);
4475                    }
4476                }
4477            } else {
4478                list = new ArrayList<PackageInfo>(mPackages.size());
4479                for (PackageParser.Package p : mPackages.values()) {
4480                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4481                    if (pi != null) {
4482                        list.add(pi);
4483                    }
4484                }
4485            }
4486
4487            return new ParceledListSlice<PackageInfo>(list);
4488        }
4489    }
4490
4491    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4492            String[] permissions, boolean[] tmp, int flags, int userId) {
4493        int numMatch = 0;
4494        final PermissionsState permissionsState = ps.getPermissionsState();
4495        for (int i=0; i<permissions.length; i++) {
4496            final String permission = permissions[i];
4497            if (permissionsState.hasPermission(permission, userId)) {
4498                tmp[i] = true;
4499                numMatch++;
4500            } else {
4501                tmp[i] = false;
4502            }
4503        }
4504        if (numMatch == 0) {
4505            return;
4506        }
4507        PackageInfo pi;
4508        if (ps.pkg != null) {
4509            pi = generatePackageInfo(ps.pkg, flags, userId);
4510        } else {
4511            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4512        }
4513        // The above might return null in cases of uninstalled apps or install-state
4514        // skew across users/profiles.
4515        if (pi != null) {
4516            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4517                if (numMatch == permissions.length) {
4518                    pi.requestedPermissions = permissions;
4519                } else {
4520                    pi.requestedPermissions = new String[numMatch];
4521                    numMatch = 0;
4522                    for (int i=0; i<permissions.length; i++) {
4523                        if (tmp[i]) {
4524                            pi.requestedPermissions[numMatch] = permissions[i];
4525                            numMatch++;
4526                        }
4527                    }
4528                }
4529            }
4530            list.add(pi);
4531        }
4532    }
4533
4534    @Override
4535    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4536            String[] permissions, int flags, int userId) {
4537        if (!sUserManager.exists(userId)) return null;
4538        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4539
4540        // writer
4541        synchronized (mPackages) {
4542            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4543            boolean[] tmpBools = new boolean[permissions.length];
4544            if (listUninstalled) {
4545                for (PackageSetting ps : mSettings.mPackages.values()) {
4546                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4547                }
4548            } else {
4549                for (PackageParser.Package pkg : mPackages.values()) {
4550                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4551                    if (ps != null) {
4552                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4553                                userId);
4554                    }
4555                }
4556            }
4557
4558            return new ParceledListSlice<PackageInfo>(list);
4559        }
4560    }
4561
4562    @Override
4563    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4564        if (!sUserManager.exists(userId)) return null;
4565        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4566
4567        // writer
4568        synchronized (mPackages) {
4569            ArrayList<ApplicationInfo> list;
4570            if (listUninstalled) {
4571                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4572                for (PackageSetting ps : mSettings.mPackages.values()) {
4573                    ApplicationInfo ai;
4574                    if (ps.pkg != null) {
4575                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4576                                ps.readUserState(userId), userId);
4577                    } else {
4578                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4579                    }
4580                    if (ai != null) {
4581                        list.add(ai);
4582                    }
4583                }
4584            } else {
4585                list = new ArrayList<ApplicationInfo>(mPackages.size());
4586                for (PackageParser.Package p : mPackages.values()) {
4587                    if (p.mExtras != null) {
4588                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4589                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4590                        if (ai != null) {
4591                            list.add(ai);
4592                        }
4593                    }
4594                }
4595            }
4596
4597            return new ParceledListSlice<ApplicationInfo>(list);
4598        }
4599    }
4600
4601    public List<ApplicationInfo> getPersistentApplications(int flags) {
4602        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4603
4604        // reader
4605        synchronized (mPackages) {
4606            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4607            final int userId = UserHandle.getCallingUserId();
4608            while (i.hasNext()) {
4609                final PackageParser.Package p = i.next();
4610                if (p.applicationInfo != null
4611                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4612                        && (!mSafeMode || isSystemApp(p))) {
4613                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4614                    if (ps != null) {
4615                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4616                                ps.readUserState(userId), userId);
4617                        if (ai != null) {
4618                            finalList.add(ai);
4619                        }
4620                    }
4621                }
4622            }
4623        }
4624
4625        return finalList;
4626    }
4627
4628    @Override
4629    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4630        if (!sUserManager.exists(userId)) return null;
4631        // reader
4632        synchronized (mPackages) {
4633            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4634            PackageSetting ps = provider != null
4635                    ? mSettings.mPackages.get(provider.owner.packageName)
4636                    : null;
4637            return ps != null
4638                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4639                    && (!mSafeMode || (provider.info.applicationInfo.flags
4640                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4641                    ? PackageParser.generateProviderInfo(provider, flags,
4642                            ps.readUserState(userId), userId)
4643                    : null;
4644        }
4645    }
4646
4647    /**
4648     * @deprecated
4649     */
4650    @Deprecated
4651    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4652        // reader
4653        synchronized (mPackages) {
4654            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4655                    .entrySet().iterator();
4656            final int userId = UserHandle.getCallingUserId();
4657            while (i.hasNext()) {
4658                Map.Entry<String, PackageParser.Provider> entry = i.next();
4659                PackageParser.Provider p = entry.getValue();
4660                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4661
4662                if (ps != null && p.syncable
4663                        && (!mSafeMode || (p.info.applicationInfo.flags
4664                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4665                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4666                            ps.readUserState(userId), userId);
4667                    if (info != null) {
4668                        outNames.add(entry.getKey());
4669                        outInfo.add(info);
4670                    }
4671                }
4672            }
4673        }
4674    }
4675
4676    @Override
4677    public List<ProviderInfo> queryContentProviders(String processName,
4678            int uid, int flags) {
4679        ArrayList<ProviderInfo> finalList = null;
4680        // reader
4681        synchronized (mPackages) {
4682            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4683            final int userId = processName != null ?
4684                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4685            while (i.hasNext()) {
4686                final PackageParser.Provider p = i.next();
4687                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4688                if (ps != null && p.info.authority != null
4689                        && (processName == null
4690                                || (p.info.processName.equals(processName)
4691                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4692                        && mSettings.isEnabledLPr(p.info, flags, userId)
4693                        && (!mSafeMode
4694                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4695                    if (finalList == null) {
4696                        finalList = new ArrayList<ProviderInfo>(3);
4697                    }
4698                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4699                            ps.readUserState(userId), userId);
4700                    if (info != null) {
4701                        finalList.add(info);
4702                    }
4703                }
4704            }
4705        }
4706
4707        if (finalList != null) {
4708            Collections.sort(finalList, mProviderInitOrderSorter);
4709        }
4710
4711        return finalList;
4712    }
4713
4714    @Override
4715    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4716            int flags) {
4717        // reader
4718        synchronized (mPackages) {
4719            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4720            return PackageParser.generateInstrumentationInfo(i, flags);
4721        }
4722    }
4723
4724    @Override
4725    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4726            int flags) {
4727        ArrayList<InstrumentationInfo> finalList =
4728            new ArrayList<InstrumentationInfo>();
4729
4730        // reader
4731        synchronized (mPackages) {
4732            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4733            while (i.hasNext()) {
4734                final PackageParser.Instrumentation p = i.next();
4735                if (targetPackage == null
4736                        || targetPackage.equals(p.info.targetPackage)) {
4737                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4738                            flags);
4739                    if (ii != null) {
4740                        finalList.add(ii);
4741                    }
4742                }
4743            }
4744        }
4745
4746        return finalList;
4747    }
4748
4749    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4750        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4751        if (overlays == null) {
4752            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4753            return;
4754        }
4755        for (PackageParser.Package opkg : overlays.values()) {
4756            // Not much to do if idmap fails: we already logged the error
4757            // and we certainly don't want to abort installation of pkg simply
4758            // because an overlay didn't fit properly. For these reasons,
4759            // ignore the return value of createIdmapForPackagePairLI.
4760            createIdmapForPackagePairLI(pkg, opkg);
4761        }
4762    }
4763
4764    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4765            PackageParser.Package opkg) {
4766        if (!opkg.mTrustedOverlay) {
4767            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4768                    opkg.baseCodePath + ": overlay not trusted");
4769            return false;
4770        }
4771        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4772        if (overlaySet == null) {
4773            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4774                    opkg.baseCodePath + " but target package has no known overlays");
4775            return false;
4776        }
4777        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4778        // TODO: generate idmap for split APKs
4779        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4780            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4781                    + opkg.baseCodePath);
4782            return false;
4783        }
4784        PackageParser.Package[] overlayArray =
4785            overlaySet.values().toArray(new PackageParser.Package[0]);
4786        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4787            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4788                return p1.mOverlayPriority - p2.mOverlayPriority;
4789            }
4790        };
4791        Arrays.sort(overlayArray, cmp);
4792
4793        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4794        int i = 0;
4795        for (PackageParser.Package p : overlayArray) {
4796            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4797        }
4798        return true;
4799    }
4800
4801    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4802        final File[] files = dir.listFiles();
4803        if (ArrayUtils.isEmpty(files)) {
4804            Log.d(TAG, "No files in app dir " + dir);
4805            return;
4806        }
4807
4808        if (DEBUG_PACKAGE_SCANNING) {
4809            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4810                    + " flags=0x" + Integer.toHexString(parseFlags));
4811        }
4812
4813        for (File file : files) {
4814            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4815                    && !PackageInstallerService.isStageName(file.getName());
4816            if (!isPackage) {
4817                // Ignore entries which are not packages
4818                continue;
4819            }
4820            try {
4821                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4822                        scanFlags, currentTime, null);
4823            } catch (PackageManagerException e) {
4824                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4825
4826                // Delete invalid userdata apps
4827                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4828                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4829                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4830                    if (file.isDirectory()) {
4831                        mInstaller.rmPackageDir(file.getAbsolutePath());
4832                    } else {
4833                        file.delete();
4834                    }
4835                }
4836            }
4837        }
4838    }
4839
4840    private static File getSettingsProblemFile() {
4841        File dataDir = Environment.getDataDirectory();
4842        File systemDir = new File(dataDir, "system");
4843        File fname = new File(systemDir, "uiderrors.txt");
4844        return fname;
4845    }
4846
4847    static void reportSettingsProblem(int priority, String msg) {
4848        logCriticalInfo(priority, msg);
4849    }
4850
4851    static void logCriticalInfo(int priority, String msg) {
4852        Slog.println(priority, TAG, msg);
4853        EventLogTags.writePmCriticalInfo(msg);
4854        try {
4855            File fname = getSettingsProblemFile();
4856            FileOutputStream out = new FileOutputStream(fname, true);
4857            PrintWriter pw = new FastPrintWriter(out);
4858            SimpleDateFormat formatter = new SimpleDateFormat();
4859            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4860            pw.println(dateString + ": " + msg);
4861            pw.close();
4862            FileUtils.setPermissions(
4863                    fname.toString(),
4864                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4865                    -1, -1);
4866        } catch (java.io.IOException e) {
4867        }
4868    }
4869
4870    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4871            PackageParser.Package pkg, File srcFile, int parseFlags)
4872            throws PackageManagerException {
4873        if (ps != null
4874                && ps.codePath.equals(srcFile)
4875                && ps.timeStamp == srcFile.lastModified()
4876                && !isCompatSignatureUpdateNeeded(pkg)
4877                && !isRecoverSignatureUpdateNeeded(pkg)) {
4878            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4879            if (ps.signatures.mSignatures != null
4880                    && ps.signatures.mSignatures.length != 0
4881                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4882                // Optimization: reuse the existing cached certificates
4883                // if the package appears to be unchanged.
4884                pkg.mSignatures = ps.signatures.mSignatures;
4885                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4886                synchronized (mPackages) {
4887                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4888                }
4889                return;
4890            }
4891
4892            Slog.w(TAG, "PackageSetting for " + ps.name
4893                    + " is missing signatures.  Collecting certs again to recover them.");
4894        } else {
4895            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4896        }
4897
4898        try {
4899            pp.collectCertificates(pkg, parseFlags);
4900            pp.collectManifestDigest(pkg);
4901        } catch (PackageParserException e) {
4902            throw PackageManagerException.from(e);
4903        }
4904    }
4905
4906    /*
4907     *  Scan a package and return the newly parsed package.
4908     *  Returns null in case of errors and the error code is stored in mLastScanError
4909     */
4910    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4911            long currentTime, UserHandle user) throws PackageManagerException {
4912        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4913        parseFlags |= mDefParseFlags;
4914        PackageParser pp = new PackageParser();
4915        pp.setSeparateProcesses(mSeparateProcesses);
4916        pp.setOnlyCoreApps(mOnlyCore);
4917        pp.setDisplayMetrics(mMetrics);
4918
4919        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4920            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4921        }
4922
4923        final PackageParser.Package pkg;
4924        try {
4925            pkg = pp.parsePackage(scanFile, parseFlags);
4926        } catch (PackageParserException e) {
4927            throw PackageManagerException.from(e);
4928        }
4929
4930        PackageSetting ps = null;
4931        PackageSetting updatedPkg;
4932        // reader
4933        synchronized (mPackages) {
4934            // Look to see if we already know about this package.
4935            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4936            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4937                // This package has been renamed to its original name.  Let's
4938                // use that.
4939                ps = mSettings.peekPackageLPr(oldName);
4940            }
4941            // If there was no original package, see one for the real package name.
4942            if (ps == null) {
4943                ps = mSettings.peekPackageLPr(pkg.packageName);
4944            }
4945            // Check to see if this package could be hiding/updating a system
4946            // package.  Must look for it either under the original or real
4947            // package name depending on our state.
4948            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4949            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4950        }
4951        boolean updatedPkgBetter = false;
4952        // First check if this is a system package that may involve an update
4953        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4954            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
4955            // it needs to drop FLAG_PRIVILEGED.
4956            if (locationIsPrivileged(scanFile)) {
4957                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4958            } else {
4959                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4960            }
4961
4962            if (ps != null && !ps.codePath.equals(scanFile)) {
4963                // The path has changed from what was last scanned...  check the
4964                // version of the new path against what we have stored to determine
4965                // what to do.
4966                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4967                if (pkg.mVersionCode <= ps.versionCode) {
4968                    // The system package has been updated and the code path does not match
4969                    // Ignore entry. Skip it.
4970                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
4971                            + " ignored: updated version " + ps.versionCode
4972                            + " better than this " + pkg.mVersionCode);
4973                    if (!updatedPkg.codePath.equals(scanFile)) {
4974                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4975                                + ps.name + " changing from " + updatedPkg.codePathString
4976                                + " to " + scanFile);
4977                        updatedPkg.codePath = scanFile;
4978                        updatedPkg.codePathString = scanFile.toString();
4979                        updatedPkg.resourcePath = scanFile;
4980                        updatedPkg.resourcePathString = scanFile.toString();
4981                    }
4982                    updatedPkg.pkg = pkg;
4983                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4984                } else {
4985                    // The current app on the system partition is better than
4986                    // what we have updated to on the data partition; switch
4987                    // back to the system partition version.
4988                    // At this point, its safely assumed that package installation for
4989                    // apps in system partition will go through. If not there won't be a working
4990                    // version of the app
4991                    // writer
4992                    synchronized (mPackages) {
4993                        // Just remove the loaded entries from package lists.
4994                        mPackages.remove(ps.name);
4995                    }
4996
4997                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4998                            + " reverting from " + ps.codePathString
4999                            + ": new version " + pkg.mVersionCode
5000                            + " better than installed " + ps.versionCode);
5001
5002                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5003                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
5004                            getAppDexInstructionSets(ps));
5005                    synchronized (mInstallLock) {
5006                        args.cleanUpResourcesLI();
5007                    }
5008                    synchronized (mPackages) {
5009                        mSettings.enableSystemPackageLPw(ps.name);
5010                    }
5011                    updatedPkgBetter = true;
5012                }
5013            }
5014        }
5015
5016        if (updatedPkg != null) {
5017            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5018            // initially
5019            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5020
5021            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5022            // flag set initially
5023            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5024                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5025            }
5026        }
5027
5028        // Verify certificates against what was last scanned
5029        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5030
5031        /*
5032         * A new system app appeared, but we already had a non-system one of the
5033         * same name installed earlier.
5034         */
5035        boolean shouldHideSystemApp = false;
5036        if (updatedPkg == null && ps != null
5037                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5038            /*
5039             * Check to make sure the signatures match first. If they don't,
5040             * wipe the installed application and its data.
5041             */
5042            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5043                    != PackageManager.SIGNATURE_MATCH) {
5044                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5045                        + " signatures don't match existing userdata copy; removing");
5046                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5047                ps = null;
5048            } else {
5049                /*
5050                 * If the newly-added system app is an older version than the
5051                 * already installed version, hide it. It will be scanned later
5052                 * and re-added like an update.
5053                 */
5054                if (pkg.mVersionCode <= ps.versionCode) {
5055                    shouldHideSystemApp = true;
5056                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5057                            + " but new version " + pkg.mVersionCode + " better than installed "
5058                            + ps.versionCode + "; hiding system");
5059                } else {
5060                    /*
5061                     * The newly found system app is a newer version that the
5062                     * one previously installed. Simply remove the
5063                     * already-installed application and replace it with our own
5064                     * while keeping the application data.
5065                     */
5066                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5067                            + " reverting from " + ps.codePathString + ": new version "
5068                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5069                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5070                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
5071                            getAppDexInstructionSets(ps));
5072                    synchronized (mInstallLock) {
5073                        args.cleanUpResourcesLI();
5074                    }
5075                }
5076            }
5077        }
5078
5079        // The apk is forward locked (not public) if its code and resources
5080        // are kept in different files. (except for app in either system or
5081        // vendor path).
5082        // TODO grab this value from PackageSettings
5083        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5084            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5085                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5086            }
5087        }
5088
5089        // TODO: extend to support forward-locked splits
5090        String resourcePath = null;
5091        String baseResourcePath = null;
5092        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5093            if (ps != null && ps.resourcePathString != null) {
5094                resourcePath = ps.resourcePathString;
5095                baseResourcePath = ps.resourcePathString;
5096            } else {
5097                // Should not happen at all. Just log an error.
5098                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5099            }
5100        } else {
5101            resourcePath = pkg.codePath;
5102            baseResourcePath = pkg.baseCodePath;
5103        }
5104
5105        // Set application objects path explicitly.
5106        pkg.applicationInfo.setCodePath(pkg.codePath);
5107        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5108        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5109        pkg.applicationInfo.setResourcePath(resourcePath);
5110        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5111        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5112
5113        // Note that we invoke the following method only if we are about to unpack an application
5114        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5115                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5116
5117        /*
5118         * If the system app should be overridden by a previously installed
5119         * data, hide the system app now and let the /data/app scan pick it up
5120         * again.
5121         */
5122        if (shouldHideSystemApp) {
5123            synchronized (mPackages) {
5124                /*
5125                 * We have to grant systems permissions before we hide, because
5126                 * grantPermissions will assume the package update is trying to
5127                 * expand its permissions.
5128                 */
5129                grantPermissionsLPw(pkg, true, pkg.packageName);
5130                mSettings.disableSystemPackageLPw(pkg.packageName);
5131            }
5132        }
5133
5134        return scannedPkg;
5135    }
5136
5137    private static String fixProcessName(String defProcessName,
5138            String processName, int uid) {
5139        if (processName == null) {
5140            return defProcessName;
5141        }
5142        return processName;
5143    }
5144
5145    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5146            throws PackageManagerException {
5147        if (pkgSetting.signatures.mSignatures != null) {
5148            // Already existing package. Make sure signatures match
5149            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5150                    == PackageManager.SIGNATURE_MATCH;
5151            if (!match) {
5152                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5153                        == PackageManager.SIGNATURE_MATCH;
5154            }
5155            if (!match) {
5156                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5157                        == PackageManager.SIGNATURE_MATCH;
5158            }
5159            if (!match) {
5160                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5161                        + pkg.packageName + " signatures do not match the "
5162                        + "previously installed version; ignoring!");
5163            }
5164        }
5165
5166        // Check for shared user signatures
5167        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5168            // Already existing package. Make sure signatures match
5169            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5170                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5171            if (!match) {
5172                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5173                        == PackageManager.SIGNATURE_MATCH;
5174            }
5175            if (!match) {
5176                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5177                        == PackageManager.SIGNATURE_MATCH;
5178            }
5179            if (!match) {
5180                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5181                        "Package " + pkg.packageName
5182                        + " has no signatures that match those in shared user "
5183                        + pkgSetting.sharedUser.name + "; ignoring!");
5184            }
5185        }
5186    }
5187
5188    /**
5189     * Enforces that only the system UID or root's UID can call a method exposed
5190     * via Binder.
5191     *
5192     * @param message used as message if SecurityException is thrown
5193     * @throws SecurityException if the caller is not system or root
5194     */
5195    private static final void enforceSystemOrRoot(String message) {
5196        final int uid = Binder.getCallingUid();
5197        if (uid != Process.SYSTEM_UID && uid != 0) {
5198            throw new SecurityException(message);
5199        }
5200    }
5201
5202    @Override
5203    public void performBootDexOpt() {
5204        enforceSystemOrRoot("Only the system can request dexopt be performed");
5205
5206        // Before everything else, see whether we need to fstrim.
5207        try {
5208            IMountService ms = PackageHelper.getMountService();
5209            if (ms != null) {
5210                final boolean isUpgrade = isUpgrade();
5211                boolean doTrim = isUpgrade;
5212                if (doTrim) {
5213                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5214                } else {
5215                    final long interval = android.provider.Settings.Global.getLong(
5216                            mContext.getContentResolver(),
5217                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5218                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5219                    if (interval > 0) {
5220                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5221                        if (timeSinceLast > interval) {
5222                            doTrim = true;
5223                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5224                                    + "; running immediately");
5225                        }
5226                    }
5227                }
5228                if (doTrim) {
5229                    if (!isFirstBoot()) {
5230                        try {
5231                            ActivityManagerNative.getDefault().showBootMessage(
5232                                    mContext.getResources().getString(
5233                                            R.string.android_upgrading_fstrim), true);
5234                        } catch (RemoteException e) {
5235                        }
5236                    }
5237                    ms.runMaintenance();
5238                }
5239            } else {
5240                Slog.e(TAG, "Mount service unavailable!");
5241            }
5242        } catch (RemoteException e) {
5243            // Can't happen; MountService is local
5244        }
5245
5246        final ArraySet<PackageParser.Package> pkgs;
5247        synchronized (mPackages) {
5248            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5249        }
5250
5251        if (pkgs != null) {
5252            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5253            // in case the device runs out of space.
5254            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5255            // Give priority to core apps.
5256            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5257                PackageParser.Package pkg = it.next();
5258                if (pkg.coreApp) {
5259                    if (DEBUG_DEXOPT) {
5260                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5261                    }
5262                    sortedPkgs.add(pkg);
5263                    it.remove();
5264                }
5265            }
5266            // Give priority to system apps that listen for pre boot complete.
5267            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5268            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5269            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5270                PackageParser.Package pkg = it.next();
5271                if (pkgNames.contains(pkg.packageName)) {
5272                    if (DEBUG_DEXOPT) {
5273                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5274                    }
5275                    sortedPkgs.add(pkg);
5276                    it.remove();
5277                }
5278            }
5279            // Give priority to system apps.
5280            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5281                PackageParser.Package pkg = it.next();
5282                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5283                    if (DEBUG_DEXOPT) {
5284                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5285                    }
5286                    sortedPkgs.add(pkg);
5287                    it.remove();
5288                }
5289            }
5290            // Give priority to updated system apps.
5291            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5292                PackageParser.Package pkg = it.next();
5293                if (pkg.isUpdatedSystemApp()) {
5294                    if (DEBUG_DEXOPT) {
5295                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5296                    }
5297                    sortedPkgs.add(pkg);
5298                    it.remove();
5299                }
5300            }
5301            // Give priority to apps that listen for boot complete.
5302            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5303            pkgNames = getPackageNamesForIntent(intent);
5304            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5305                PackageParser.Package pkg = it.next();
5306                if (pkgNames.contains(pkg.packageName)) {
5307                    if (DEBUG_DEXOPT) {
5308                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5309                    }
5310                    sortedPkgs.add(pkg);
5311                    it.remove();
5312                }
5313            }
5314            // Filter out packages that aren't recently used.
5315            filterRecentlyUsedApps(pkgs);
5316            // Add all remaining apps.
5317            for (PackageParser.Package pkg : pkgs) {
5318                if (DEBUG_DEXOPT) {
5319                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5320                }
5321                sortedPkgs.add(pkg);
5322            }
5323
5324            // If we want to be lazy, filter everything that wasn't recently used.
5325            if (mLazyDexOpt) {
5326                filterRecentlyUsedApps(sortedPkgs);
5327            }
5328
5329            int i = 0;
5330            int total = sortedPkgs.size();
5331            File dataDir = Environment.getDataDirectory();
5332            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5333            if (lowThreshold == 0) {
5334                throw new IllegalStateException("Invalid low memory threshold");
5335            }
5336            for (PackageParser.Package pkg : sortedPkgs) {
5337                long usableSpace = dataDir.getUsableSpace();
5338                if (usableSpace < lowThreshold) {
5339                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5340                    break;
5341                }
5342                performBootDexOpt(pkg, ++i, total);
5343            }
5344        }
5345    }
5346
5347    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5348        // Filter out packages that aren't recently used.
5349        //
5350        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5351        // should do a full dexopt.
5352        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5353            int total = pkgs.size();
5354            int skipped = 0;
5355            long now = System.currentTimeMillis();
5356            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5357                PackageParser.Package pkg = i.next();
5358                long then = pkg.mLastPackageUsageTimeInMills;
5359                if (then + mDexOptLRUThresholdInMills < now) {
5360                    if (DEBUG_DEXOPT) {
5361                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5362                              ((then == 0) ? "never" : new Date(then)));
5363                    }
5364                    i.remove();
5365                    skipped++;
5366                }
5367            }
5368            if (DEBUG_DEXOPT) {
5369                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5370            }
5371        }
5372    }
5373
5374    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5375        List<ResolveInfo> ris = null;
5376        try {
5377            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5378                    intent, null, 0, UserHandle.USER_OWNER);
5379        } catch (RemoteException e) {
5380        }
5381        ArraySet<String> pkgNames = new ArraySet<String>();
5382        if (ris != null) {
5383            for (ResolveInfo ri : ris) {
5384                pkgNames.add(ri.activityInfo.packageName);
5385            }
5386        }
5387        return pkgNames;
5388    }
5389
5390    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5391        if (DEBUG_DEXOPT) {
5392            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5393        }
5394        if (!isFirstBoot()) {
5395            try {
5396                ActivityManagerNative.getDefault().showBootMessage(
5397                        mContext.getResources().getString(R.string.android_upgrading_apk,
5398                                curr, total), true);
5399            } catch (RemoteException e) {
5400            }
5401        }
5402        PackageParser.Package p = pkg;
5403        synchronized (mInstallLock) {
5404            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5405                    false /* force dex */, false /* defer */, true /* include dependencies */);
5406        }
5407    }
5408
5409    @Override
5410    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5411        return performDexOpt(packageName, instructionSet, false);
5412    }
5413
5414    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5415        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5416        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5417        if (!dexopt && !updateUsage) {
5418            // We aren't going to dexopt or update usage, so bail early.
5419            return false;
5420        }
5421        PackageParser.Package p;
5422        final String targetInstructionSet;
5423        synchronized (mPackages) {
5424            p = mPackages.get(packageName);
5425            if (p == null) {
5426                return false;
5427            }
5428            if (updateUsage) {
5429                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5430            }
5431            mPackageUsage.write(false);
5432            if (!dexopt) {
5433                // We aren't going to dexopt, so bail early.
5434                return false;
5435            }
5436
5437            targetInstructionSet = instructionSet != null ? instructionSet :
5438                    getPrimaryInstructionSet(p.applicationInfo);
5439            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5440                return false;
5441            }
5442        }
5443
5444        synchronized (mInstallLock) {
5445            final String[] instructionSets = new String[] { targetInstructionSet };
5446            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5447                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5448            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5449        }
5450    }
5451
5452    public ArraySet<String> getPackagesThatNeedDexOpt() {
5453        ArraySet<String> pkgs = null;
5454        synchronized (mPackages) {
5455            for (PackageParser.Package p : mPackages.values()) {
5456                if (DEBUG_DEXOPT) {
5457                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5458                }
5459                if (!p.mDexOptPerformed.isEmpty()) {
5460                    continue;
5461                }
5462                if (pkgs == null) {
5463                    pkgs = new ArraySet<String>();
5464                }
5465                pkgs.add(p.packageName);
5466            }
5467        }
5468        return pkgs;
5469    }
5470
5471    public void shutdown() {
5472        mPackageUsage.write(true);
5473    }
5474
5475    @Override
5476    public void forceDexOpt(String packageName) {
5477        enforceSystemOrRoot("forceDexOpt");
5478
5479        PackageParser.Package pkg;
5480        synchronized (mPackages) {
5481            pkg = mPackages.get(packageName);
5482            if (pkg == null) {
5483                throw new IllegalArgumentException("Missing package: " + packageName);
5484            }
5485        }
5486
5487        synchronized (mInstallLock) {
5488            final String[] instructionSets = new String[] {
5489                    getPrimaryInstructionSet(pkg.applicationInfo) };
5490            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5491                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5492            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5493                throw new IllegalStateException("Failed to dexopt: " + res);
5494            }
5495        }
5496    }
5497
5498    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5499        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5500            Slog.w(TAG, "Unable to update from " + oldPkg.name
5501                    + " to " + newPkg.packageName
5502                    + ": old package not in system partition");
5503            return false;
5504        } else if (mPackages.get(oldPkg.name) != null) {
5505            Slog.w(TAG, "Unable to update from " + oldPkg.name
5506                    + " to " + newPkg.packageName
5507                    + ": old package still exists");
5508            return false;
5509        }
5510        return true;
5511    }
5512
5513    private File getDataPathForPackage(String packageName, int userId) {
5514        /*
5515         * Until we fully support multiple users, return the directory we
5516         * previously would have. The PackageManagerTests will need to be
5517         * revised when this is changed back..
5518         */
5519        if (userId == 0) {
5520            return new File(mAppDataDir, packageName);
5521        } else {
5522            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
5523                + File.separator + packageName);
5524        }
5525    }
5526
5527    private int createDataDirsLI(String packageName, int uid, String seinfo) {
5528        int[] users = sUserManager.getUserIds();
5529        int res = mInstaller.install(packageName, uid, uid, seinfo);
5530        if (res < 0) {
5531            return res;
5532        }
5533        for (int user : users) {
5534            if (user != 0) {
5535                res = mInstaller.createUserData(packageName,
5536                        UserHandle.getUid(user, uid), user, seinfo);
5537                if (res < 0) {
5538                    return res;
5539                }
5540            }
5541        }
5542        return res;
5543    }
5544
5545    private int removeDataDirsLI(String packageName) {
5546        int[] users = sUserManager.getUserIds();
5547        int res = 0;
5548        for (int user : users) {
5549            int resInner = mInstaller.remove(packageName, user);
5550            if (resInner < 0) {
5551                res = resInner;
5552            }
5553        }
5554
5555        return res;
5556    }
5557
5558    private int deleteCodeCacheDirsLI(String packageName) {
5559        int[] users = sUserManager.getUserIds();
5560        int res = 0;
5561        for (int user : users) {
5562            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
5563            if (resInner < 0) {
5564                res = resInner;
5565            }
5566        }
5567        return res;
5568    }
5569
5570    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5571            PackageParser.Package changingLib) {
5572        if (file.path != null) {
5573            usesLibraryFiles.add(file.path);
5574            return;
5575        }
5576        PackageParser.Package p = mPackages.get(file.apk);
5577        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5578            // If we are doing this while in the middle of updating a library apk,
5579            // then we need to make sure to use that new apk for determining the
5580            // dependencies here.  (We haven't yet finished committing the new apk
5581            // to the package manager state.)
5582            if (p == null || p.packageName.equals(changingLib.packageName)) {
5583                p = changingLib;
5584            }
5585        }
5586        if (p != null) {
5587            usesLibraryFiles.addAll(p.getAllCodePaths());
5588        }
5589    }
5590
5591    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5592            PackageParser.Package changingLib) throws PackageManagerException {
5593        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5594            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5595            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5596            for (int i=0; i<N; i++) {
5597                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5598                if (file == null) {
5599                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5600                            "Package " + pkg.packageName + " requires unavailable shared library "
5601                            + pkg.usesLibraries.get(i) + "; failing!");
5602                }
5603                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5604            }
5605            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5606            for (int i=0; i<N; i++) {
5607                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5608                if (file == null) {
5609                    Slog.w(TAG, "Package " + pkg.packageName
5610                            + " desires unavailable shared library "
5611                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5612                } else {
5613                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5614                }
5615            }
5616            N = usesLibraryFiles.size();
5617            if (N > 0) {
5618                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5619            } else {
5620                pkg.usesLibraryFiles = null;
5621            }
5622        }
5623    }
5624
5625    private static boolean hasString(List<String> list, List<String> which) {
5626        if (list == null) {
5627            return false;
5628        }
5629        for (int i=list.size()-1; i>=0; i--) {
5630            for (int j=which.size()-1; j>=0; j--) {
5631                if (which.get(j).equals(list.get(i))) {
5632                    return true;
5633                }
5634            }
5635        }
5636        return false;
5637    }
5638
5639    private void updateAllSharedLibrariesLPw() {
5640        for (PackageParser.Package pkg : mPackages.values()) {
5641            try {
5642                updateSharedLibrariesLPw(pkg, null);
5643            } catch (PackageManagerException e) {
5644                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5645            }
5646        }
5647    }
5648
5649    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5650            PackageParser.Package changingPkg) {
5651        ArrayList<PackageParser.Package> res = null;
5652        for (PackageParser.Package pkg : mPackages.values()) {
5653            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5654                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5655                if (res == null) {
5656                    res = new ArrayList<PackageParser.Package>();
5657                }
5658                res.add(pkg);
5659                try {
5660                    updateSharedLibrariesLPw(pkg, changingPkg);
5661                } catch (PackageManagerException e) {
5662                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5663                }
5664            }
5665        }
5666        return res;
5667    }
5668
5669    /**
5670     * Derive the value of the {@code cpuAbiOverride} based on the provided
5671     * value and an optional stored value from the package settings.
5672     */
5673    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5674        String cpuAbiOverride = null;
5675
5676        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5677            cpuAbiOverride = null;
5678        } else if (abiOverride != null) {
5679            cpuAbiOverride = abiOverride;
5680        } else if (settings != null) {
5681            cpuAbiOverride = settings.cpuAbiOverrideString;
5682        }
5683
5684        return cpuAbiOverride;
5685    }
5686
5687    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5688            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5689        boolean success = false;
5690        try {
5691            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5692                    currentTime, user);
5693            success = true;
5694            return res;
5695        } finally {
5696            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5697                removeDataDirsLI(pkg.packageName);
5698            }
5699        }
5700    }
5701
5702    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5703            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5704        final File scanFile = new File(pkg.codePath);
5705        if (pkg.applicationInfo.getCodePath() == null ||
5706                pkg.applicationInfo.getResourcePath() == null) {
5707            // Bail out. The resource and code paths haven't been set.
5708            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5709                    "Code and resource paths haven't been set correctly");
5710        }
5711
5712        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5713            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5714        } else {
5715            // Only allow system apps to be flagged as core apps.
5716            pkg.coreApp = false;
5717        }
5718
5719        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5720            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5721        }
5722
5723        if (mCustomResolverComponentName != null &&
5724                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5725            setUpCustomResolverActivity(pkg);
5726        }
5727
5728        if (pkg.packageName.equals("android")) {
5729            synchronized (mPackages) {
5730                if (mAndroidApplication != null) {
5731                    Slog.w(TAG, "*************************************************");
5732                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5733                    Slog.w(TAG, " file=" + scanFile);
5734                    Slog.w(TAG, "*************************************************");
5735                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5736                            "Core android package being redefined.  Skipping.");
5737                }
5738
5739                // Set up information for our fall-back user intent resolution activity.
5740                mPlatformPackage = pkg;
5741                pkg.mVersionCode = mSdkVersion;
5742                mAndroidApplication = pkg.applicationInfo;
5743
5744                if (!mResolverReplaced) {
5745                    mResolveActivity.applicationInfo = mAndroidApplication;
5746                    mResolveActivity.name = ResolverActivity.class.getName();
5747                    mResolveActivity.packageName = mAndroidApplication.packageName;
5748                    mResolveActivity.processName = "system:ui";
5749                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5750                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5751                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5752                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5753                    mResolveActivity.exported = true;
5754                    mResolveActivity.enabled = true;
5755                    mResolveInfo.activityInfo = mResolveActivity;
5756                    mResolveInfo.priority = 0;
5757                    mResolveInfo.preferredOrder = 0;
5758                    mResolveInfo.match = 0;
5759                    mResolveComponentName = new ComponentName(
5760                            mAndroidApplication.packageName, mResolveActivity.name);
5761                }
5762            }
5763        }
5764
5765        if (DEBUG_PACKAGE_SCANNING) {
5766            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5767                Log.d(TAG, "Scanning package " + pkg.packageName);
5768        }
5769
5770        if (mPackages.containsKey(pkg.packageName)
5771                || mSharedLibraries.containsKey(pkg.packageName)) {
5772            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5773                    "Application package " + pkg.packageName
5774                    + " already installed.  Skipping duplicate.");
5775        }
5776
5777        // If we're only installing presumed-existing packages, require that the
5778        // scanned APK is both already known and at the path previously established
5779        // for it.  Previously unknown packages we pick up normally, but if we have an
5780        // a priori expectation about this package's install presence, enforce it.
5781        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
5782            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
5783            if (known != null) {
5784                if (DEBUG_PACKAGE_SCANNING) {
5785                    Log.d(TAG, "Examining " + pkg.codePath
5786                            + " and requiring known paths " + known.codePathString
5787                            + " & " + known.resourcePathString);
5788                }
5789                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
5790                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
5791                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
5792                            "Application package " + pkg.packageName
5793                            + " found at " + pkg.applicationInfo.getCodePath()
5794                            + " but expected at " + known.codePathString + "; ignoring.");
5795                }
5796            }
5797        }
5798
5799        // Initialize package source and resource directories
5800        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5801        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5802
5803        SharedUserSetting suid = null;
5804        PackageSetting pkgSetting = null;
5805
5806        if (!isSystemApp(pkg)) {
5807            // Only system apps can use these features.
5808            pkg.mOriginalPackages = null;
5809            pkg.mRealPackage = null;
5810            pkg.mAdoptPermissions = null;
5811        }
5812
5813        // writer
5814        synchronized (mPackages) {
5815            if (pkg.mSharedUserId != null) {
5816                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5817                if (suid == null) {
5818                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5819                            "Creating application package " + pkg.packageName
5820                            + " for shared user failed");
5821                }
5822                if (DEBUG_PACKAGE_SCANNING) {
5823                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5824                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5825                                + "): packages=" + suid.packages);
5826                }
5827            }
5828
5829            // Check if we are renaming from an original package name.
5830            PackageSetting origPackage = null;
5831            String realName = null;
5832            if (pkg.mOriginalPackages != null) {
5833                // This package may need to be renamed to a previously
5834                // installed name.  Let's check on that...
5835                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5836                if (pkg.mOriginalPackages.contains(renamed)) {
5837                    // This package had originally been installed as the
5838                    // original name, and we have already taken care of
5839                    // transitioning to the new one.  Just update the new
5840                    // one to continue using the old name.
5841                    realName = pkg.mRealPackage;
5842                    if (!pkg.packageName.equals(renamed)) {
5843                        // Callers into this function may have already taken
5844                        // care of renaming the package; only do it here if
5845                        // it is not already done.
5846                        pkg.setPackageName(renamed);
5847                    }
5848
5849                } else {
5850                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5851                        if ((origPackage = mSettings.peekPackageLPr(
5852                                pkg.mOriginalPackages.get(i))) != null) {
5853                            // We do have the package already installed under its
5854                            // original name...  should we use it?
5855                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5856                                // New package is not compatible with original.
5857                                origPackage = null;
5858                                continue;
5859                            } else if (origPackage.sharedUser != null) {
5860                                // Make sure uid is compatible between packages.
5861                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5862                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5863                                            + " to " + pkg.packageName + ": old uid "
5864                                            + origPackage.sharedUser.name
5865                                            + " differs from " + pkg.mSharedUserId);
5866                                    origPackage = null;
5867                                    continue;
5868                                }
5869                            } else {
5870                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5871                                        + pkg.packageName + " to old name " + origPackage.name);
5872                            }
5873                            break;
5874                        }
5875                    }
5876                }
5877            }
5878
5879            if (mTransferedPackages.contains(pkg.packageName)) {
5880                Slog.w(TAG, "Package " + pkg.packageName
5881                        + " was transferred to another, but its .apk remains");
5882            }
5883
5884            // Just create the setting, don't add it yet. For already existing packages
5885            // the PkgSetting exists already and doesn't have to be created.
5886            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5887                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5888                    pkg.applicationInfo.primaryCpuAbi,
5889                    pkg.applicationInfo.secondaryCpuAbi,
5890                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
5891                    user, false);
5892            if (pkgSetting == null) {
5893                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5894                        "Creating application package " + pkg.packageName + " failed");
5895            }
5896
5897            if (pkgSetting.origPackage != null) {
5898                // If we are first transitioning from an original package,
5899                // fix up the new package's name now.  We need to do this after
5900                // looking up the package under its new name, so getPackageLP
5901                // can take care of fiddling things correctly.
5902                pkg.setPackageName(origPackage.name);
5903
5904                // File a report about this.
5905                String msg = "New package " + pkgSetting.realName
5906                        + " renamed to replace old package " + pkgSetting.name;
5907                reportSettingsProblem(Log.WARN, msg);
5908
5909                // Make a note of it.
5910                mTransferedPackages.add(origPackage.name);
5911
5912                // No longer need to retain this.
5913                pkgSetting.origPackage = null;
5914            }
5915
5916            if (realName != null) {
5917                // Make a note of it.
5918                mTransferedPackages.add(pkg.packageName);
5919            }
5920
5921            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5922                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5923            }
5924
5925            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5926                // Check all shared libraries and map to their actual file path.
5927                // We only do this here for apps not on a system dir, because those
5928                // are the only ones that can fail an install due to this.  We
5929                // will take care of the system apps by updating all of their
5930                // library paths after the scan is done.
5931                updateSharedLibrariesLPw(pkg, null);
5932            }
5933
5934            if (mFoundPolicyFile) {
5935                SELinuxMMAC.assignSeinfoValue(pkg);
5936            }
5937
5938            pkg.applicationInfo.uid = pkgSetting.appId;
5939            pkg.mExtras = pkgSetting;
5940            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5941                try {
5942                    verifySignaturesLP(pkgSetting, pkg);
5943                    // We just determined the app is signed correctly, so bring
5944                    // over the latest parsed certs.
5945                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5946                } catch (PackageManagerException e) {
5947                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5948                        throw e;
5949                    }
5950                    // The signature has changed, but this package is in the system
5951                    // image...  let's recover!
5952                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5953                    // However...  if this package is part of a shared user, but it
5954                    // doesn't match the signature of the shared user, let's fail.
5955                    // What this means is that you can't change the signatures
5956                    // associated with an overall shared user, which doesn't seem all
5957                    // that unreasonable.
5958                    if (pkgSetting.sharedUser != null) {
5959                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5960                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5961                            throw new PackageManagerException(
5962                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5963                                            "Signature mismatch for shared user : "
5964                                            + pkgSetting.sharedUser);
5965                        }
5966                    }
5967                    // File a report about this.
5968                    String msg = "System package " + pkg.packageName
5969                        + " signature changed; retaining data.";
5970                    reportSettingsProblem(Log.WARN, msg);
5971                }
5972            } else {
5973                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5974                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5975                            + pkg.packageName + " upgrade keys do not match the "
5976                            + "previously installed version");
5977                } else {
5978                    // We just determined the app is signed correctly, so bring
5979                    // over the latest parsed certs.
5980                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5981                }
5982            }
5983            // Verify that this new package doesn't have any content providers
5984            // that conflict with existing packages.  Only do this if the
5985            // package isn't already installed, since we don't want to break
5986            // things that are installed.
5987            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5988                final int N = pkg.providers.size();
5989                int i;
5990                for (i=0; i<N; i++) {
5991                    PackageParser.Provider p = pkg.providers.get(i);
5992                    if (p.info.authority != null) {
5993                        String names[] = p.info.authority.split(";");
5994                        for (int j = 0; j < names.length; j++) {
5995                            if (mProvidersByAuthority.containsKey(names[j])) {
5996                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5997                                final String otherPackageName =
5998                                        ((other != null && other.getComponentName() != null) ?
5999                                                other.getComponentName().getPackageName() : "?");
6000                                throw new PackageManagerException(
6001                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6002                                                "Can't install because provider name " + names[j]
6003                                                + " (in package " + pkg.applicationInfo.packageName
6004                                                + ") is already used by " + otherPackageName);
6005                            }
6006                        }
6007                    }
6008                }
6009            }
6010
6011            if (pkg.mAdoptPermissions != null) {
6012                // This package wants to adopt ownership of permissions from
6013                // another package.
6014                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6015                    final String origName = pkg.mAdoptPermissions.get(i);
6016                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6017                    if (orig != null) {
6018                        if (verifyPackageUpdateLPr(orig, pkg)) {
6019                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6020                                    + pkg.packageName);
6021                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6022                        }
6023                    }
6024                }
6025            }
6026        }
6027
6028        final String pkgName = pkg.packageName;
6029
6030        final long scanFileTime = scanFile.lastModified();
6031        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6032        pkg.applicationInfo.processName = fixProcessName(
6033                pkg.applicationInfo.packageName,
6034                pkg.applicationInfo.processName,
6035                pkg.applicationInfo.uid);
6036
6037        File dataPath;
6038        if (mPlatformPackage == pkg) {
6039            // The system package is special.
6040            dataPath = new File(Environment.getDataDirectory(), "system");
6041
6042            pkg.applicationInfo.dataDir = dataPath.getPath();
6043
6044        } else {
6045            // This is a normal package, need to make its data directory.
6046            dataPath = getDataPathForPackage(pkg.packageName, 0);
6047
6048            boolean uidError = false;
6049            if (dataPath.exists()) {
6050                int currentUid = 0;
6051                try {
6052                    StructStat stat = Os.stat(dataPath.getPath());
6053                    currentUid = stat.st_uid;
6054                } catch (ErrnoException e) {
6055                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6056                }
6057
6058                // If we have mismatched owners for the data path, we have a problem.
6059                if (currentUid != pkg.applicationInfo.uid) {
6060                    boolean recovered = false;
6061                    if (currentUid == 0) {
6062                        // The directory somehow became owned by root.  Wow.
6063                        // This is probably because the system was stopped while
6064                        // installd was in the middle of messing with its libs
6065                        // directory.  Ask installd to fix that.
6066                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
6067                                pkg.applicationInfo.uid);
6068                        if (ret >= 0) {
6069                            recovered = true;
6070                            String msg = "Package " + pkg.packageName
6071                                    + " unexpectedly changed to uid 0; recovered to " +
6072                                    + pkg.applicationInfo.uid;
6073                            reportSettingsProblem(Log.WARN, msg);
6074                        }
6075                    }
6076                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6077                            || (scanFlags&SCAN_BOOTING) != 0)) {
6078                        // If this is a system app, we can at least delete its
6079                        // current data so the application will still work.
6080                        int ret = removeDataDirsLI(pkgName);
6081                        if (ret >= 0) {
6082                            // TODO: Kill the processes first
6083                            // Old data gone!
6084                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6085                                    ? "System package " : "Third party package ";
6086                            String msg = prefix + pkg.packageName
6087                                    + " has changed from uid: "
6088                                    + currentUid + " to "
6089                                    + pkg.applicationInfo.uid + "; old data erased";
6090                            reportSettingsProblem(Log.WARN, msg);
6091                            recovered = true;
6092
6093                            // And now re-install the app.
6094                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
6095                                                   pkg.applicationInfo.seinfo);
6096                            if (ret == -1) {
6097                                // Ack should not happen!
6098                                msg = prefix + pkg.packageName
6099                                        + " could not have data directory re-created after delete.";
6100                                reportSettingsProblem(Log.WARN, msg);
6101                                throw new PackageManagerException(
6102                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6103                            }
6104                        }
6105                        if (!recovered) {
6106                            mHasSystemUidErrors = true;
6107                        }
6108                    } else if (!recovered) {
6109                        // If we allow this install to proceed, we will be broken.
6110                        // Abort, abort!
6111                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6112                                "scanPackageLI");
6113                    }
6114                    if (!recovered) {
6115                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6116                            + pkg.applicationInfo.uid + "/fs_"
6117                            + currentUid;
6118                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6119                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6120                        String msg = "Package " + pkg.packageName
6121                                + " has mismatched uid: "
6122                                + currentUid + " on disk, "
6123                                + pkg.applicationInfo.uid + " in settings";
6124                        // writer
6125                        synchronized (mPackages) {
6126                            mSettings.mReadMessages.append(msg);
6127                            mSettings.mReadMessages.append('\n');
6128                            uidError = true;
6129                            if (!pkgSetting.uidError) {
6130                                reportSettingsProblem(Log.ERROR, msg);
6131                            }
6132                        }
6133                    }
6134                }
6135                pkg.applicationInfo.dataDir = dataPath.getPath();
6136                if (mShouldRestoreconData) {
6137                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6138                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
6139                                pkg.applicationInfo.uid);
6140                }
6141            } else {
6142                if (DEBUG_PACKAGE_SCANNING) {
6143                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6144                        Log.v(TAG, "Want this data dir: " + dataPath);
6145                }
6146                //invoke installer to do the actual installation
6147                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
6148                                           pkg.applicationInfo.seinfo);
6149                if (ret < 0) {
6150                    // Error from installer
6151                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6152                            "Unable to create data dirs [errorCode=" + ret + "]");
6153                }
6154
6155                if (dataPath.exists()) {
6156                    pkg.applicationInfo.dataDir = dataPath.getPath();
6157                } else {
6158                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6159                    pkg.applicationInfo.dataDir = null;
6160                }
6161            }
6162
6163            pkgSetting.uidError = uidError;
6164        }
6165
6166        final String path = scanFile.getPath();
6167        final String codePath = pkg.applicationInfo.getCodePath();
6168        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6169        if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6170            setBundledAppAbisAndRoots(pkg, pkgSetting);
6171
6172            // If we haven't found any native libraries for the app, check if it has
6173            // renderscript code. We'll need to force the app to 32 bit if it has
6174            // renderscript bitcode.
6175            if (pkg.applicationInfo.primaryCpuAbi == null
6176                    && pkg.applicationInfo.secondaryCpuAbi == null
6177                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
6178                NativeLibraryHelper.Handle handle = null;
6179                try {
6180                    handle = NativeLibraryHelper.Handle.create(scanFile);
6181                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6182                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6183                    }
6184                } catch (IOException ioe) {
6185                    Slog.w(TAG, "Error scanning system app : " + ioe);
6186                } finally {
6187                    IoUtils.closeQuietly(handle);
6188                }
6189            }
6190
6191            setNativeLibraryPaths(pkg);
6192        } else {
6193            // TODO: We can probably be smarter about this stuff. For installed apps,
6194            // we can calculate this information at install time once and for all. For
6195            // system apps, we can probably assume that this information doesn't change
6196            // after the first boot scan. As things stand, we do lots of unnecessary work.
6197
6198            // Give ourselves some initial paths; we'll come back for another
6199            // pass once we've determined ABI below.
6200            setNativeLibraryPaths(pkg);
6201
6202            final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg);
6203            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6204            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6205
6206            NativeLibraryHelper.Handle handle = null;
6207            try {
6208                handle = NativeLibraryHelper.Handle.create(scanFile);
6209                // TODO(multiArch): This can be null for apps that didn't go through the
6210                // usual installation process. We can calculate it again, like we
6211                // do during install time.
6212                //
6213                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6214                // unnecessary.
6215                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6216
6217                // Null out the abis so that they can be recalculated.
6218                pkg.applicationInfo.primaryCpuAbi = null;
6219                pkg.applicationInfo.secondaryCpuAbi = null;
6220                if (isMultiArch(pkg.applicationInfo)) {
6221                    // Warn if we've set an abiOverride for multi-lib packages..
6222                    // By definition, we need to copy both 32 and 64 bit libraries for
6223                    // such packages.
6224                    if (pkg.cpuAbiOverride != null
6225                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
6226                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
6227                    }
6228
6229                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
6230                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
6231                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
6232                        if (isAsec) {
6233                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
6234                        } else {
6235                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6236                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
6237                                    useIsaSpecificSubdirs);
6238                        }
6239                    }
6240
6241                    maybeThrowExceptionForMultiArchCopy(
6242                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
6243
6244                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
6245                        if (isAsec) {
6246                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
6247                        } else {
6248                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6249                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
6250                                    useIsaSpecificSubdirs);
6251                        }
6252                    }
6253
6254                    maybeThrowExceptionForMultiArchCopy(
6255                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
6256
6257                    if (abi64 >= 0) {
6258                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
6259                    }
6260
6261                    if (abi32 >= 0) {
6262                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
6263                        if (abi64 >= 0) {
6264                            pkg.applicationInfo.secondaryCpuAbi = abi;
6265                        } else {
6266                            pkg.applicationInfo.primaryCpuAbi = abi;
6267                        }
6268                    }
6269                } else {
6270                    String[] abiList = (cpuAbiOverride != null) ?
6271                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
6272
6273                    // Enable gross and lame hacks for apps that are built with old
6274                    // SDK tools. We must scan their APKs for renderscript bitcode and
6275                    // not launch them if it's present. Don't bother checking on devices
6276                    // that don't have 64 bit support.
6277                    boolean needsRenderScriptOverride = false;
6278                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
6279                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6280                        abiList = Build.SUPPORTED_32_BIT_ABIS;
6281                        needsRenderScriptOverride = true;
6282                    }
6283
6284                    final int copyRet;
6285                    if (isAsec) {
6286                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6287                    } else {
6288                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6289                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
6290                    }
6291
6292                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
6293                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6294                                "Error unpackaging native libs for app, errorCode=" + copyRet);
6295                    }
6296
6297                    if (copyRet >= 0) {
6298                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
6299                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
6300                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
6301                    } else if (needsRenderScriptOverride) {
6302                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
6303                    }
6304                }
6305            } catch (IOException ioe) {
6306                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
6307            } finally {
6308                IoUtils.closeQuietly(handle);
6309            }
6310
6311            // Now that we've calculated the ABIs and determined if it's an internal app,
6312            // we will go ahead and populate the nativeLibraryPath.
6313            setNativeLibraryPaths(pkg);
6314
6315            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6316            final int[] userIds = sUserManager.getUserIds();
6317            synchronized (mInstallLock) {
6318                // Create a native library symlink only if we have native libraries
6319                // and if the native libraries are 32 bit libraries. We do not provide
6320                // this symlink for 64 bit libraries.
6321                if (pkg.applicationInfo.primaryCpuAbi != null &&
6322                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6323                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6324                    for (int userId : userIds) {
6325                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
6326                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6327                                    "Failed linking native library dir (user=" + userId + ")");
6328                        }
6329                    }
6330                }
6331            }
6332        }
6333
6334        // This is a special case for the "system" package, where the ABI is
6335        // dictated by the zygote configuration (and init.rc). We should keep track
6336        // of this ABI so that we can deal with "normal" applications that run under
6337        // the same UID correctly.
6338        if (mPlatformPackage == pkg) {
6339            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6340                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6341        }
6342
6343        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6344        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6345        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6346        // Copy the derived override back to the parsed package, so that we can
6347        // update the package settings accordingly.
6348        pkg.cpuAbiOverride = cpuAbiOverride;
6349
6350        if (DEBUG_ABI_SELECTION) {
6351            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6352                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6353                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6354        }
6355
6356        // Push the derived path down into PackageSettings so we know what to
6357        // clean up at uninstall time.
6358        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6359
6360        if (DEBUG_ABI_SELECTION) {
6361            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6362                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6363                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6364        }
6365
6366        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6367            // We don't do this here during boot because we can do it all
6368            // at once after scanning all existing packages.
6369            //
6370            // We also do this *before* we perform dexopt on this package, so that
6371            // we can avoid redundant dexopts, and also to make sure we've got the
6372            // code and package path correct.
6373            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6374                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6375        }
6376
6377        if ((scanFlags & SCAN_NO_DEX) == 0) {
6378            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6379                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6380            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6381                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6382            }
6383        }
6384        if (mFactoryTest && pkg.requestedPermissions.contains(
6385                android.Manifest.permission.FACTORY_TEST)) {
6386            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6387        }
6388
6389        ArrayList<PackageParser.Package> clientLibPkgs = null;
6390
6391        // writer
6392        synchronized (mPackages) {
6393            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6394                // Only system apps can add new shared libraries.
6395                if (pkg.libraryNames != null) {
6396                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6397                        String name = pkg.libraryNames.get(i);
6398                        boolean allowed = false;
6399                        if (pkg.isUpdatedSystemApp()) {
6400                            // New library entries can only be added through the
6401                            // system image.  This is important to get rid of a lot
6402                            // of nasty edge cases: for example if we allowed a non-
6403                            // system update of the app to add a library, then uninstalling
6404                            // the update would make the library go away, and assumptions
6405                            // we made such as through app install filtering would now
6406                            // have allowed apps on the device which aren't compatible
6407                            // with it.  Better to just have the restriction here, be
6408                            // conservative, and create many fewer cases that can negatively
6409                            // impact the user experience.
6410                            final PackageSetting sysPs = mSettings
6411                                    .getDisabledSystemPkgLPr(pkg.packageName);
6412                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6413                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6414                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6415                                        allowed = true;
6416                                        allowed = true;
6417                                        break;
6418                                    }
6419                                }
6420                            }
6421                        } else {
6422                            allowed = true;
6423                        }
6424                        if (allowed) {
6425                            if (!mSharedLibraries.containsKey(name)) {
6426                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6427                            } else if (!name.equals(pkg.packageName)) {
6428                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6429                                        + name + " already exists; skipping");
6430                            }
6431                        } else {
6432                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6433                                    + name + " that is not declared on system image; skipping");
6434                        }
6435                    }
6436                    if ((scanFlags&SCAN_BOOTING) == 0) {
6437                        // If we are not booting, we need to update any applications
6438                        // that are clients of our shared library.  If we are booting,
6439                        // this will all be done once the scan is complete.
6440                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6441                    }
6442                }
6443            }
6444        }
6445
6446        // We also need to dexopt any apps that are dependent on this library.  Note that
6447        // if these fail, we should abort the install since installing the library will
6448        // result in some apps being broken.
6449        if (clientLibPkgs != null) {
6450            if ((scanFlags & SCAN_NO_DEX) == 0) {
6451                for (int i = 0; i < clientLibPkgs.size(); i++) {
6452                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6453                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6454                            null /* instruction sets */, forceDex,
6455                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6456                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6457                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6458                                "scanPackageLI failed to dexopt clientLibPkgs");
6459                    }
6460                }
6461            }
6462        }
6463
6464        // Request the ActivityManager to kill the process(only for existing packages)
6465        // so that we do not end up in a confused state while the user is still using the older
6466        // version of the application while the new one gets installed.
6467        if ((scanFlags & SCAN_REPLACING) != 0) {
6468            killApplication(pkg.applicationInfo.packageName,
6469                        pkg.applicationInfo.uid, "update pkg");
6470        }
6471
6472        // Also need to kill any apps that are dependent on the library.
6473        if (clientLibPkgs != null) {
6474            for (int i=0; i<clientLibPkgs.size(); i++) {
6475                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6476                killApplication(clientPkg.applicationInfo.packageName,
6477                        clientPkg.applicationInfo.uid, "update lib");
6478            }
6479        }
6480
6481        // writer
6482        synchronized (mPackages) {
6483            // We don't expect installation to fail beyond this point
6484
6485            // Add the new setting to mSettings
6486            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6487            // Add the new setting to mPackages
6488            mPackages.put(pkg.applicationInfo.packageName, pkg);
6489            // Make sure we don't accidentally delete its data.
6490            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6491            while (iter.hasNext()) {
6492                PackageCleanItem item = iter.next();
6493                if (pkgName.equals(item.packageName)) {
6494                    iter.remove();
6495                }
6496            }
6497
6498            // Take care of first install / last update times.
6499            if (currentTime != 0) {
6500                if (pkgSetting.firstInstallTime == 0) {
6501                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6502                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6503                    pkgSetting.lastUpdateTime = currentTime;
6504                }
6505            } else if (pkgSetting.firstInstallTime == 0) {
6506                // We need *something*.  Take time time stamp of the file.
6507                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6508            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6509                if (scanFileTime != pkgSetting.timeStamp) {
6510                    // A package on the system image has changed; consider this
6511                    // to be an update.
6512                    pkgSetting.lastUpdateTime = scanFileTime;
6513                }
6514            }
6515
6516            // Add the package's KeySets to the global KeySetManagerService
6517            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6518            try {
6519                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6520                if (pkg.mKeySetMapping != null) {
6521                    ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping);
6522                    if (pkg.mUpgradeKeySets != null) {
6523                        ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets);
6524                    }
6525                }
6526            } catch (NullPointerException e) {
6527                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6528            } catch (IllegalArgumentException e) {
6529                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6530            }
6531
6532            int N = pkg.providers.size();
6533            StringBuilder r = null;
6534            int i;
6535            for (i=0; i<N; i++) {
6536                PackageParser.Provider p = pkg.providers.get(i);
6537                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6538                        p.info.processName, pkg.applicationInfo.uid);
6539                mProviders.addProvider(p);
6540                p.syncable = p.info.isSyncable;
6541                if (p.info.authority != null) {
6542                    String names[] = p.info.authority.split(";");
6543                    p.info.authority = null;
6544                    for (int j = 0; j < names.length; j++) {
6545                        if (j == 1 && p.syncable) {
6546                            // We only want the first authority for a provider to possibly be
6547                            // syncable, so if we already added this provider using a different
6548                            // authority clear the syncable flag. We copy the provider before
6549                            // changing it because the mProviders object contains a reference
6550                            // to a provider that we don't want to change.
6551                            // Only do this for the second authority since the resulting provider
6552                            // object can be the same for all future authorities for this provider.
6553                            p = new PackageParser.Provider(p);
6554                            p.syncable = false;
6555                        }
6556                        if (!mProvidersByAuthority.containsKey(names[j])) {
6557                            mProvidersByAuthority.put(names[j], p);
6558                            if (p.info.authority == null) {
6559                                p.info.authority = names[j];
6560                            } else {
6561                                p.info.authority = p.info.authority + ";" + names[j];
6562                            }
6563                            if (DEBUG_PACKAGE_SCANNING) {
6564                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6565                                    Log.d(TAG, "Registered content provider: " + names[j]
6566                                            + ", className = " + p.info.name + ", isSyncable = "
6567                                            + p.info.isSyncable);
6568                            }
6569                        } else {
6570                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6571                            Slog.w(TAG, "Skipping provider name " + names[j] +
6572                                    " (in package " + pkg.applicationInfo.packageName +
6573                                    "): name already used by "
6574                                    + ((other != null && other.getComponentName() != null)
6575                                            ? other.getComponentName().getPackageName() : "?"));
6576                        }
6577                    }
6578                }
6579                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6580                    if (r == null) {
6581                        r = new StringBuilder(256);
6582                    } else {
6583                        r.append(' ');
6584                    }
6585                    r.append(p.info.name);
6586                }
6587            }
6588            if (r != null) {
6589                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6590            }
6591
6592            N = pkg.services.size();
6593            r = null;
6594            for (i=0; i<N; i++) {
6595                PackageParser.Service s = pkg.services.get(i);
6596                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6597                        s.info.processName, pkg.applicationInfo.uid);
6598                mServices.addService(s);
6599                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6600                    if (r == null) {
6601                        r = new StringBuilder(256);
6602                    } else {
6603                        r.append(' ');
6604                    }
6605                    r.append(s.info.name);
6606                }
6607            }
6608            if (r != null) {
6609                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6610            }
6611
6612            N = pkg.receivers.size();
6613            r = null;
6614            for (i=0; i<N; i++) {
6615                PackageParser.Activity a = pkg.receivers.get(i);
6616                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6617                        a.info.processName, pkg.applicationInfo.uid);
6618                mReceivers.addActivity(a, "receiver");
6619                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6620                    if (r == null) {
6621                        r = new StringBuilder(256);
6622                    } else {
6623                        r.append(' ');
6624                    }
6625                    r.append(a.info.name);
6626                }
6627            }
6628            if (r != null) {
6629                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6630            }
6631
6632            N = pkg.activities.size();
6633            r = null;
6634            for (i=0; i<N; i++) {
6635                PackageParser.Activity a = pkg.activities.get(i);
6636                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6637                        a.info.processName, pkg.applicationInfo.uid);
6638                mActivities.addActivity(a, "activity");
6639                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6640                    if (r == null) {
6641                        r = new StringBuilder(256);
6642                    } else {
6643                        r.append(' ');
6644                    }
6645                    r.append(a.info.name);
6646                }
6647            }
6648            if (r != null) {
6649                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6650            }
6651
6652            N = pkg.permissionGroups.size();
6653            r = null;
6654            for (i=0; i<N; i++) {
6655                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6656                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6657                if (cur == null) {
6658                    mPermissionGroups.put(pg.info.name, pg);
6659                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6660                        if (r == null) {
6661                            r = new StringBuilder(256);
6662                        } else {
6663                            r.append(' ');
6664                        }
6665                        r.append(pg.info.name);
6666                    }
6667                } else {
6668                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6669                            + pg.info.packageName + " ignored: original from "
6670                            + cur.info.packageName);
6671                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6672                        if (r == null) {
6673                            r = new StringBuilder(256);
6674                        } else {
6675                            r.append(' ');
6676                        }
6677                        r.append("DUP:");
6678                        r.append(pg.info.name);
6679                    }
6680                }
6681            }
6682            if (r != null) {
6683                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6684            }
6685
6686            N = pkg.permissions.size();
6687            r = null;
6688            for (i=0; i<N; i++) {
6689                PackageParser.Permission p = pkg.permissions.get(i);
6690                ArrayMap<String, BasePermission> permissionMap =
6691                        p.tree ? mSettings.mPermissionTrees
6692                        : mSettings.mPermissions;
6693                p.group = mPermissionGroups.get(p.info.group);
6694                if (p.info.group == null || p.group != null) {
6695                    BasePermission bp = permissionMap.get(p.info.name);
6696
6697                    // Allow system apps to redefine non-system permissions
6698                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6699                        final boolean currentOwnerIsSystem = (bp.perm != null
6700                                && isSystemApp(bp.perm.owner));
6701                        if (isSystemApp(p.owner)) {
6702                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6703                                // It's a built-in permission and no owner, take ownership now
6704                                bp.packageSetting = pkgSetting;
6705                                bp.perm = p;
6706                                bp.uid = pkg.applicationInfo.uid;
6707                                bp.sourcePackage = p.info.packageName;
6708                            } else if (!currentOwnerIsSystem) {
6709                                String msg = "New decl " + p.owner + " of permission  "
6710                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6711                                reportSettingsProblem(Log.WARN, msg);
6712                                bp = null;
6713                            }
6714                        }
6715                    }
6716
6717                    if (bp == null) {
6718                        bp = new BasePermission(p.info.name, p.info.packageName,
6719                                BasePermission.TYPE_NORMAL);
6720                        permissionMap.put(p.info.name, bp);
6721                    }
6722
6723                    if (bp.perm == null) {
6724                        if (bp.sourcePackage == null
6725                                || bp.sourcePackage.equals(p.info.packageName)) {
6726                            BasePermission tree = findPermissionTreeLP(p.info.name);
6727                            if (tree == null
6728                                    || tree.sourcePackage.equals(p.info.packageName)) {
6729                                bp.packageSetting = pkgSetting;
6730                                bp.perm = p;
6731                                bp.uid = pkg.applicationInfo.uid;
6732                                bp.sourcePackage = p.info.packageName;
6733                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6734                                    if (r == null) {
6735                                        r = new StringBuilder(256);
6736                                    } else {
6737                                        r.append(' ');
6738                                    }
6739                                    r.append(p.info.name);
6740                                }
6741                            } else {
6742                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6743                                        + p.info.packageName + " ignored: base tree "
6744                                        + tree.name + " is from package "
6745                                        + tree.sourcePackage);
6746                            }
6747                        } else {
6748                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6749                                    + p.info.packageName + " ignored: original from "
6750                                    + bp.sourcePackage);
6751                        }
6752                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6753                        if (r == null) {
6754                            r = new StringBuilder(256);
6755                        } else {
6756                            r.append(' ');
6757                        }
6758                        r.append("DUP:");
6759                        r.append(p.info.name);
6760                    }
6761                    if (bp.perm == p) {
6762                        bp.protectionLevel = p.info.protectionLevel;
6763                    }
6764                } else {
6765                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6766                            + p.info.packageName + " ignored: no group "
6767                            + p.group);
6768                }
6769            }
6770            if (r != null) {
6771                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6772            }
6773
6774            N = pkg.instrumentation.size();
6775            r = null;
6776            for (i=0; i<N; i++) {
6777                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6778                a.info.packageName = pkg.applicationInfo.packageName;
6779                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6780                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6781                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6782                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6783                a.info.dataDir = pkg.applicationInfo.dataDir;
6784
6785                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6786                // need other information about the application, like the ABI and what not ?
6787                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6788                mInstrumentation.put(a.getComponentName(), a);
6789                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6790                    if (r == null) {
6791                        r = new StringBuilder(256);
6792                    } else {
6793                        r.append(' ');
6794                    }
6795                    r.append(a.info.name);
6796                }
6797            }
6798            if (r != null) {
6799                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6800            }
6801
6802            if (pkg.protectedBroadcasts != null) {
6803                N = pkg.protectedBroadcasts.size();
6804                for (i=0; i<N; i++) {
6805                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6806                }
6807            }
6808
6809            pkgSetting.setTimeStamp(scanFileTime);
6810
6811            // Create idmap files for pairs of (packages, overlay packages).
6812            // Note: "android", ie framework-res.apk, is handled by native layers.
6813            if (pkg.mOverlayTarget != null) {
6814                // This is an overlay package.
6815                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6816                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6817                        mOverlays.put(pkg.mOverlayTarget,
6818                                new ArrayMap<String, PackageParser.Package>());
6819                    }
6820                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6821                    map.put(pkg.packageName, pkg);
6822                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6823                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6824                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6825                                "scanPackageLI failed to createIdmap");
6826                    }
6827                }
6828            } else if (mOverlays.containsKey(pkg.packageName) &&
6829                    !pkg.packageName.equals("android")) {
6830                // This is a regular package, with one or more known overlay packages.
6831                createIdmapsForPackageLI(pkg);
6832            }
6833        }
6834
6835        return pkg;
6836    }
6837
6838    /**
6839     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6840     * i.e, so that all packages can be run inside a single process if required.
6841     *
6842     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6843     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6844     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6845     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6846     * updating a package that belongs to a shared user.
6847     *
6848     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6849     * adds unnecessary complexity.
6850     */
6851    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6852            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6853        String requiredInstructionSet = null;
6854        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6855            requiredInstructionSet = VMRuntime.getInstructionSet(
6856                     scannedPackage.applicationInfo.primaryCpuAbi);
6857        }
6858
6859        PackageSetting requirer = null;
6860        for (PackageSetting ps : packagesForUser) {
6861            // If packagesForUser contains scannedPackage, we skip it. This will happen
6862            // when scannedPackage is an update of an existing package. Without this check,
6863            // we will never be able to change the ABI of any package belonging to a shared
6864            // user, even if it's compatible with other packages.
6865            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6866                if (ps.primaryCpuAbiString == null) {
6867                    continue;
6868                }
6869
6870                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6871                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6872                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6873                    // this but there's not much we can do.
6874                    String errorMessage = "Instruction set mismatch, "
6875                            + ((requirer == null) ? "[caller]" : requirer)
6876                            + " requires " + requiredInstructionSet + " whereas " + ps
6877                            + " requires " + instructionSet;
6878                    Slog.w(TAG, errorMessage);
6879                }
6880
6881                if (requiredInstructionSet == null) {
6882                    requiredInstructionSet = instructionSet;
6883                    requirer = ps;
6884                }
6885            }
6886        }
6887
6888        if (requiredInstructionSet != null) {
6889            String adjustedAbi;
6890            if (requirer != null) {
6891                // requirer != null implies that either scannedPackage was null or that scannedPackage
6892                // did not require an ABI, in which case we have to adjust scannedPackage to match
6893                // the ABI of the set (which is the same as requirer's ABI)
6894                adjustedAbi = requirer.primaryCpuAbiString;
6895                if (scannedPackage != null) {
6896                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6897                }
6898            } else {
6899                // requirer == null implies that we're updating all ABIs in the set to
6900                // match scannedPackage.
6901                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6902            }
6903
6904            for (PackageSetting ps : packagesForUser) {
6905                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6906                    if (ps.primaryCpuAbiString != null) {
6907                        continue;
6908                    }
6909
6910                    ps.primaryCpuAbiString = adjustedAbi;
6911                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6912                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6913                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6914
6915                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
6916                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
6917                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6918                            ps.primaryCpuAbiString = null;
6919                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6920                            return;
6921                        } else {
6922                            mInstaller.rmdex(ps.codePathString,
6923                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
6924                        }
6925                    }
6926                }
6927            }
6928        }
6929    }
6930
6931    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6932        synchronized (mPackages) {
6933            mResolverReplaced = true;
6934            // Set up information for custom user intent resolution activity.
6935            mResolveActivity.applicationInfo = pkg.applicationInfo;
6936            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6937            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6938            mResolveActivity.processName = pkg.applicationInfo.packageName;
6939            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6940            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6941                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6942            mResolveActivity.theme = 0;
6943            mResolveActivity.exported = true;
6944            mResolveActivity.enabled = true;
6945            mResolveInfo.activityInfo = mResolveActivity;
6946            mResolveInfo.priority = 0;
6947            mResolveInfo.preferredOrder = 0;
6948            mResolveInfo.match = 0;
6949            mResolveComponentName = mCustomResolverComponentName;
6950            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6951                    mResolveComponentName);
6952        }
6953    }
6954
6955    private static String calculateBundledApkRoot(final String codePathString) {
6956        final File codePath = new File(codePathString);
6957        final File codeRoot;
6958        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6959            codeRoot = Environment.getRootDirectory();
6960        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6961            codeRoot = Environment.getOemDirectory();
6962        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6963            codeRoot = Environment.getVendorDirectory();
6964        } else {
6965            // Unrecognized code path; take its top real segment as the apk root:
6966            // e.g. /something/app/blah.apk => /something
6967            try {
6968                File f = codePath.getCanonicalFile();
6969                File parent = f.getParentFile();    // non-null because codePath is a file
6970                File tmp;
6971                while ((tmp = parent.getParentFile()) != null) {
6972                    f = parent;
6973                    parent = tmp;
6974                }
6975                codeRoot = f;
6976                Slog.w(TAG, "Unrecognized code path "
6977                        + codePath + " - using " + codeRoot);
6978            } catch (IOException e) {
6979                // Can't canonicalize the code path -- shenanigans?
6980                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6981                return Environment.getRootDirectory().getPath();
6982            }
6983        }
6984        return codeRoot.getPath();
6985    }
6986
6987    /**
6988     * Derive and set the location of native libraries for the given package,
6989     * which varies depending on where and how the package was installed.
6990     */
6991    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6992        final ApplicationInfo info = pkg.applicationInfo;
6993        final String codePath = pkg.codePath;
6994        final File codeFile = new File(codePath);
6995        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
6996        final boolean asecApp = info.isForwardLocked() || isExternal(info);
6997
6998        info.nativeLibraryRootDir = null;
6999        info.nativeLibraryRootRequiresIsa = false;
7000        info.nativeLibraryDir = null;
7001        info.secondaryNativeLibraryDir = null;
7002
7003        if (isApkFile(codeFile)) {
7004            // Monolithic install
7005            if (bundledApp) {
7006                // If "/system/lib64/apkname" exists, assume that is the per-package
7007                // native library directory to use; otherwise use "/system/lib/apkname".
7008                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7009                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7010                        getPrimaryInstructionSet(info));
7011
7012                // This is a bundled system app so choose the path based on the ABI.
7013                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7014                // is just the default path.
7015                final String apkName = deriveCodePathName(codePath);
7016                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7017                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7018                        apkName).getAbsolutePath();
7019
7020                if (info.secondaryCpuAbi != null) {
7021                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7022                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7023                            secondaryLibDir, apkName).getAbsolutePath();
7024                }
7025            } else if (asecApp) {
7026                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7027                        .getAbsolutePath();
7028            } else {
7029                final String apkName = deriveCodePathName(codePath);
7030                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7031                        .getAbsolutePath();
7032            }
7033
7034            info.nativeLibraryRootRequiresIsa = false;
7035            info.nativeLibraryDir = info.nativeLibraryRootDir;
7036        } else {
7037            // Cluster install
7038            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7039            info.nativeLibraryRootRequiresIsa = true;
7040
7041            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7042                    getPrimaryInstructionSet(info)).getAbsolutePath();
7043
7044            if (info.secondaryCpuAbi != null) {
7045                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7046                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7047            }
7048        }
7049    }
7050
7051    /**
7052     * Calculate the abis and roots for a bundled app. These can uniquely
7053     * be determined from the contents of the system partition, i.e whether
7054     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7055     * of this information, and instead assume that the system was built
7056     * sensibly.
7057     */
7058    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7059                                           PackageSetting pkgSetting) {
7060        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7061
7062        // If "/system/lib64/apkname" exists, assume that is the per-package
7063        // native library directory to use; otherwise use "/system/lib/apkname".
7064        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7065        setBundledAppAbi(pkg, apkRoot, apkName);
7066        // pkgSetting might be null during rescan following uninstall of updates
7067        // to a bundled app, so accommodate that possibility.  The settings in
7068        // that case will be established later from the parsed package.
7069        //
7070        // If the settings aren't null, sync them up with what we've just derived.
7071        // note that apkRoot isn't stored in the package settings.
7072        if (pkgSetting != null) {
7073            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7074            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7075        }
7076    }
7077
7078    /**
7079     * Deduces the ABI of a bundled app and sets the relevant fields on the
7080     * parsed pkg object.
7081     *
7082     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7083     *        under which system libraries are installed.
7084     * @param apkName the name of the installed package.
7085     */
7086    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7087        final File codeFile = new File(pkg.codePath);
7088
7089        final boolean has64BitLibs;
7090        final boolean has32BitLibs;
7091        if (isApkFile(codeFile)) {
7092            // Monolithic install
7093            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7094            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7095        } else {
7096            // Cluster install
7097            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7098            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7099                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7100                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7101                has64BitLibs = (new File(rootDir, isa)).exists();
7102            } else {
7103                has64BitLibs = false;
7104            }
7105            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7106                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7107                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7108                has32BitLibs = (new File(rootDir, isa)).exists();
7109            } else {
7110                has32BitLibs = false;
7111            }
7112        }
7113
7114        if (has64BitLibs && !has32BitLibs) {
7115            // The package has 64 bit libs, but not 32 bit libs. Its primary
7116            // ABI should be 64 bit. We can safely assume here that the bundled
7117            // native libraries correspond to the most preferred ABI in the list.
7118
7119            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7120            pkg.applicationInfo.secondaryCpuAbi = null;
7121        } else if (has32BitLibs && !has64BitLibs) {
7122            // The package has 32 bit libs but not 64 bit libs. Its primary
7123            // ABI should be 32 bit.
7124
7125            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7126            pkg.applicationInfo.secondaryCpuAbi = null;
7127        } else if (has32BitLibs && has64BitLibs) {
7128            // The application has both 64 and 32 bit bundled libraries. We check
7129            // here that the app declares multiArch support, and warn if it doesn't.
7130            //
7131            // We will be lenient here and record both ABIs. The primary will be the
7132            // ABI that's higher on the list, i.e, a device that's configured to prefer
7133            // 64 bit apps will see a 64 bit primary ABI,
7134
7135            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7136                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7137            }
7138
7139            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7140                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7141                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7142            } else {
7143                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7144                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7145            }
7146        } else {
7147            pkg.applicationInfo.primaryCpuAbi = null;
7148            pkg.applicationInfo.secondaryCpuAbi = null;
7149        }
7150    }
7151
7152    private void killApplication(String pkgName, int appId, String reason) {
7153        // Request the ActivityManager to kill the process(only for existing packages)
7154        // so that we do not end up in a confused state while the user is still using the older
7155        // version of the application while the new one gets installed.
7156        IActivityManager am = ActivityManagerNative.getDefault();
7157        if (am != null) {
7158            try {
7159                am.killApplicationWithAppId(pkgName, appId, reason);
7160            } catch (RemoteException e) {
7161            }
7162        }
7163    }
7164
7165    void removePackageLI(PackageSetting ps, boolean chatty) {
7166        if (DEBUG_INSTALL) {
7167            if (chatty)
7168                Log.d(TAG, "Removing package " + ps.name);
7169        }
7170
7171        // writer
7172        synchronized (mPackages) {
7173            mPackages.remove(ps.name);
7174            final PackageParser.Package pkg = ps.pkg;
7175            if (pkg != null) {
7176                cleanPackageDataStructuresLILPw(pkg, chatty);
7177            }
7178        }
7179    }
7180
7181    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7182        if (DEBUG_INSTALL) {
7183            if (chatty)
7184                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7185        }
7186
7187        // writer
7188        synchronized (mPackages) {
7189            mPackages.remove(pkg.applicationInfo.packageName);
7190            cleanPackageDataStructuresLILPw(pkg, chatty);
7191        }
7192    }
7193
7194    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7195        int N = pkg.providers.size();
7196        StringBuilder r = null;
7197        int i;
7198        for (i=0; i<N; i++) {
7199            PackageParser.Provider p = pkg.providers.get(i);
7200            mProviders.removeProvider(p);
7201            if (p.info.authority == null) {
7202
7203                /* There was another ContentProvider with this authority when
7204                 * this app was installed so this authority is null,
7205                 * Ignore it as we don't have to unregister the provider.
7206                 */
7207                continue;
7208            }
7209            String names[] = p.info.authority.split(";");
7210            for (int j = 0; j < names.length; j++) {
7211                if (mProvidersByAuthority.get(names[j]) == p) {
7212                    mProvidersByAuthority.remove(names[j]);
7213                    if (DEBUG_REMOVE) {
7214                        if (chatty)
7215                            Log.d(TAG, "Unregistered content provider: " + names[j]
7216                                    + ", className = " + p.info.name + ", isSyncable = "
7217                                    + p.info.isSyncable);
7218                    }
7219                }
7220            }
7221            if (DEBUG_REMOVE && chatty) {
7222                if (r == null) {
7223                    r = new StringBuilder(256);
7224                } else {
7225                    r.append(' ');
7226                }
7227                r.append(p.info.name);
7228            }
7229        }
7230        if (r != null) {
7231            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7232        }
7233
7234        N = pkg.services.size();
7235        r = null;
7236        for (i=0; i<N; i++) {
7237            PackageParser.Service s = pkg.services.get(i);
7238            mServices.removeService(s);
7239            if (chatty) {
7240                if (r == null) {
7241                    r = new StringBuilder(256);
7242                } else {
7243                    r.append(' ');
7244                }
7245                r.append(s.info.name);
7246            }
7247        }
7248        if (r != null) {
7249            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7250        }
7251
7252        N = pkg.receivers.size();
7253        r = null;
7254        for (i=0; i<N; i++) {
7255            PackageParser.Activity a = pkg.receivers.get(i);
7256            mReceivers.removeActivity(a, "receiver");
7257            if (DEBUG_REMOVE && chatty) {
7258                if (r == null) {
7259                    r = new StringBuilder(256);
7260                } else {
7261                    r.append(' ');
7262                }
7263                r.append(a.info.name);
7264            }
7265        }
7266        if (r != null) {
7267            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7268        }
7269
7270        N = pkg.activities.size();
7271        r = null;
7272        for (i=0; i<N; i++) {
7273            PackageParser.Activity a = pkg.activities.get(i);
7274            mActivities.removeActivity(a, "activity");
7275            if (DEBUG_REMOVE && chatty) {
7276                if (r == null) {
7277                    r = new StringBuilder(256);
7278                } else {
7279                    r.append(' ');
7280                }
7281                r.append(a.info.name);
7282            }
7283        }
7284        if (r != null) {
7285            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7286        }
7287
7288        N = pkg.permissions.size();
7289        r = null;
7290        for (i=0; i<N; i++) {
7291            PackageParser.Permission p = pkg.permissions.get(i);
7292            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7293            if (bp == null) {
7294                bp = mSettings.mPermissionTrees.get(p.info.name);
7295            }
7296            if (bp != null && bp.perm == p) {
7297                bp.perm = null;
7298                if (DEBUG_REMOVE && chatty) {
7299                    if (r == null) {
7300                        r = new StringBuilder(256);
7301                    } else {
7302                        r.append(' ');
7303                    }
7304                    r.append(p.info.name);
7305                }
7306            }
7307            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7308                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7309                if (appOpPerms != null) {
7310                    appOpPerms.remove(pkg.packageName);
7311                }
7312            }
7313        }
7314        if (r != null) {
7315            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7316        }
7317
7318        N = pkg.requestedPermissions.size();
7319        r = null;
7320        for (i=0; i<N; i++) {
7321            String perm = pkg.requestedPermissions.get(i);
7322            BasePermission bp = mSettings.mPermissions.get(perm);
7323            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7324                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7325                if (appOpPerms != null) {
7326                    appOpPerms.remove(pkg.packageName);
7327                    if (appOpPerms.isEmpty()) {
7328                        mAppOpPermissionPackages.remove(perm);
7329                    }
7330                }
7331            }
7332        }
7333        if (r != null) {
7334            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7335        }
7336
7337        N = pkg.instrumentation.size();
7338        r = null;
7339        for (i=0; i<N; i++) {
7340            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7341            mInstrumentation.remove(a.getComponentName());
7342            if (DEBUG_REMOVE && chatty) {
7343                if (r == null) {
7344                    r = new StringBuilder(256);
7345                } else {
7346                    r.append(' ');
7347                }
7348                r.append(a.info.name);
7349            }
7350        }
7351        if (r != null) {
7352            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7353        }
7354
7355        r = null;
7356        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7357            // Only system apps can hold shared libraries.
7358            if (pkg.libraryNames != null) {
7359                for (i=0; i<pkg.libraryNames.size(); i++) {
7360                    String name = pkg.libraryNames.get(i);
7361                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7362                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7363                        mSharedLibraries.remove(name);
7364                        if (DEBUG_REMOVE && chatty) {
7365                            if (r == null) {
7366                                r = new StringBuilder(256);
7367                            } else {
7368                                r.append(' ');
7369                            }
7370                            r.append(name);
7371                        }
7372                    }
7373                }
7374            }
7375        }
7376        if (r != null) {
7377            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7378        }
7379    }
7380
7381    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7382        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7383            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7384                return true;
7385            }
7386        }
7387        return false;
7388    }
7389
7390    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7391    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7392    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7393
7394    private void updatePermissionsLPw(String changingPkg,
7395            PackageParser.Package pkgInfo, int flags) {
7396        // Make sure there are no dangling permission trees.
7397        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7398        while (it.hasNext()) {
7399            final BasePermission bp = it.next();
7400            if (bp.packageSetting == null) {
7401                // We may not yet have parsed the package, so just see if
7402                // we still know about its settings.
7403                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7404            }
7405            if (bp.packageSetting == null) {
7406                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7407                        + " from package " + bp.sourcePackage);
7408                it.remove();
7409            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7410                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7411                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7412                            + " from package " + bp.sourcePackage);
7413                    flags |= UPDATE_PERMISSIONS_ALL;
7414                    it.remove();
7415                }
7416            }
7417        }
7418
7419        // Make sure all dynamic permissions have been assigned to a package,
7420        // and make sure there are no dangling permissions.
7421        it = mSettings.mPermissions.values().iterator();
7422        while (it.hasNext()) {
7423            final BasePermission bp = it.next();
7424            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7425                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7426                        + bp.name + " pkg=" + bp.sourcePackage
7427                        + " info=" + bp.pendingInfo);
7428                if (bp.packageSetting == null && bp.pendingInfo != null) {
7429                    final BasePermission tree = findPermissionTreeLP(bp.name);
7430                    if (tree != null && tree.perm != null) {
7431                        bp.packageSetting = tree.packageSetting;
7432                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7433                                new PermissionInfo(bp.pendingInfo));
7434                        bp.perm.info.packageName = tree.perm.info.packageName;
7435                        bp.perm.info.name = bp.name;
7436                        bp.uid = tree.uid;
7437                    }
7438                }
7439            }
7440            if (bp.packageSetting == null) {
7441                // We may not yet have parsed the package, so just see if
7442                // we still know about its settings.
7443                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7444            }
7445            if (bp.packageSetting == null) {
7446                Slog.w(TAG, "Removing dangling permission: " + bp.name
7447                        + " from package " + bp.sourcePackage);
7448                it.remove();
7449            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7450                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7451                    Slog.i(TAG, "Removing old permission: " + bp.name
7452                            + " from package " + bp.sourcePackage);
7453                    flags |= UPDATE_PERMISSIONS_ALL;
7454                    it.remove();
7455                }
7456            }
7457        }
7458
7459        // Now update the permissions for all packages, in particular
7460        // replace the granted permissions of the system packages.
7461        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7462            for (PackageParser.Package pkg : mPackages.values()) {
7463                if (pkg != pkgInfo) {
7464                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7465                            changingPkg);
7466                }
7467            }
7468        }
7469
7470        if (pkgInfo != null) {
7471            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7472        }
7473    }
7474
7475    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7476            String packageOfInterest) {
7477        // IMPORTANT: There are two types of permissions: install and runtime.
7478        // Install time permissions are granted when the app is installed to
7479        // all device users and users added in the future. Runtime permissions
7480        // are granted at runtime explicitly to specific users. Normal and signature
7481        // protected permissions are install time permissions. Dangerous permissions
7482        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7483        // otherwise they are runtime permissions. This function does not manage
7484        // runtime permissions except for the case an app targeting Lollipop MR1
7485        // being upgraded to target a newer SDK, in which case dangerous permissions
7486        // are transformed from install time to runtime ones.
7487
7488        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7489        if (ps == null) {
7490            return;
7491        }
7492
7493        PermissionsState permissionsState = ps.getPermissionsState();
7494        PermissionsState origPermissions = permissionsState;
7495
7496        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7497
7498        int[] upgradeUserIds = PermissionsState.USERS_NONE;
7499        int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE;
7500
7501        boolean changedInstallPermission = false;
7502
7503        if (replace) {
7504            ps.installPermissionsFixed = false;
7505            if (!ps.isSharedUser()) {
7506                origPermissions = new PermissionsState(permissionsState);
7507                permissionsState.reset();
7508            }
7509        }
7510
7511        permissionsState.setGlobalGids(mGlobalGids);
7512
7513        final int N = pkg.requestedPermissions.size();
7514        for (int i=0; i<N; i++) {
7515            final String name = pkg.requestedPermissions.get(i);
7516            final BasePermission bp = mSettings.mPermissions.get(name);
7517
7518            if (DEBUG_INSTALL) {
7519                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7520            }
7521
7522            if (bp == null || bp.packageSetting == null) {
7523                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7524                    Slog.w(TAG, "Unknown permission " + name
7525                            + " in package " + pkg.packageName);
7526                }
7527                continue;
7528            }
7529
7530            final String perm = bp.name;
7531            boolean allowedSig = false;
7532            int grant = GRANT_DENIED;
7533
7534            // Keep track of app op permissions.
7535            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7536                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7537                if (pkgs == null) {
7538                    pkgs = new ArraySet<>();
7539                    mAppOpPermissionPackages.put(bp.name, pkgs);
7540                }
7541                pkgs.add(pkg.packageName);
7542            }
7543
7544            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7545            switch (level) {
7546                case PermissionInfo.PROTECTION_NORMAL: {
7547                    // For all apps normal permissions are install time ones.
7548                    grant = GRANT_INSTALL;
7549                } break;
7550
7551                case PermissionInfo.PROTECTION_DANGEROUS: {
7552                    if (!RUNTIME_PERMISSIONS_ENABLED
7553                            || pkg.applicationInfo.targetSdkVersion
7554                                    <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7555                        // For legacy apps dangerous permissions are install time ones.
7556                        grant = GRANT_INSTALL;
7557                    } else if (ps.isSystem()) {
7558                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7559                        if (origPermissions.hasInstallPermission(bp.name)) {
7560                            // If a system app had an install permission, then the app was
7561                            // upgraded and we grant the permissions as runtime to all users.
7562                            grant = GRANT_UPGRADE;
7563                            upgradeUserIds = currentUserIds;
7564                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7565                            // If users changed since the last permissions update for a
7566                            // system app, we grant the permission as runtime to the new users.
7567                            grant = GRANT_UPGRADE;
7568                            upgradeUserIds = currentUserIds;
7569                            for (int userId : updatedUserIds) {
7570                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7571                            }
7572                        } else {
7573                            // Otherwise, we grant the permission as runtime if the app
7574                            // already had it, i.e. we preserve runtime permissions.
7575                            grant = GRANT_RUNTIME;
7576                        }
7577                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7578                        // For legacy apps that became modern, install becomes runtime.
7579                        grant = GRANT_UPGRADE;
7580                        upgradeUserIds = currentUserIds;
7581                    } else if (replace) {
7582                        // For upgraded modern apps keep runtime permissions unchanged.
7583                        grant = GRANT_RUNTIME;
7584                    }
7585                } break;
7586
7587                case PermissionInfo.PROTECTION_SIGNATURE: {
7588                    // For all apps signature permissions are install time ones.
7589                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7590                    if (allowedSig) {
7591                        grant = GRANT_INSTALL;
7592                    }
7593                } break;
7594            }
7595
7596            if (DEBUG_INSTALL) {
7597                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7598            }
7599
7600            if (grant != GRANT_DENIED) {
7601                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7602                    // If this is an existing, non-system package, then
7603                    // we can't add any new permissions to it.
7604                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7605                        // Except...  if this is a permission that was added
7606                        // to the platform (note: need to only do this when
7607                        // updating the platform).
7608                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7609                            grant = GRANT_DENIED;
7610                        }
7611                    }
7612                }
7613
7614                switch (grant) {
7615                    case GRANT_INSTALL: {
7616                        // Grant an install permission.
7617                        if (permissionsState.grantInstallPermission(bp) !=
7618                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7619                            changedInstallPermission = true;
7620                        }
7621                    } break;
7622
7623                    case GRANT_RUNTIME: {
7624                        // Grant previously granted runtime permissions.
7625                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7626                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7627                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7628                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7629                                    // If we cannot put the permission as it was, we have to write.
7630                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7631                                            changedRuntimePermissionUserIds, userId);
7632                                }
7633                            }
7634                        }
7635                    } break;
7636
7637                    case GRANT_UPGRADE: {
7638                        // Grant runtime permissions for a previously held install permission.
7639                        permissionsState.revokeInstallPermission(bp);
7640                        for (int userId : upgradeUserIds) {
7641                            if (permissionsState.grantRuntimePermission(bp, userId) !=
7642                                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
7643                                // If we granted the permission, we have to write.
7644                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7645                                        changedRuntimePermissionUserIds, userId);
7646                            }
7647                        }
7648                    } break;
7649
7650                    default: {
7651                        if (packageOfInterest == null
7652                                || packageOfInterest.equals(pkg.packageName)) {
7653                            Slog.w(TAG, "Not granting permission " + perm
7654                                    + " to package " + pkg.packageName
7655                                    + " because it was previously installed without");
7656                        }
7657                    } break;
7658                }
7659            } else {
7660                if (permissionsState.revokeInstallPermission(bp) !=
7661                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7662                    changedInstallPermission = true;
7663                    Slog.i(TAG, "Un-granting permission " + perm
7664                            + " from package " + pkg.packageName
7665                            + " (protectionLevel=" + bp.protectionLevel
7666                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7667                            + ")");
7668                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7669                    // Don't print warning for app op permissions, since it is fine for them
7670                    // not to be granted, there is a UI for the user to decide.
7671                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7672                        Slog.w(TAG, "Not granting permission " + perm
7673                                + " to package " + pkg.packageName
7674                                + " (protectionLevel=" + bp.protectionLevel
7675                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7676                                + ")");
7677                    }
7678                }
7679            }
7680        }
7681
7682        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7683                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7684            // This is the first that we have heard about this package, so the
7685            // permissions we have now selected are fixed until explicitly
7686            // changed.
7687            ps.installPermissionsFixed = true;
7688        }
7689
7690        ps.setPermissionsUpdatedForUserIds(currentUserIds);
7691
7692        // Persist the runtime permissions state for users with changes.
7693        if (RUNTIME_PERMISSIONS_ENABLED) {
7694            for (int userId : changedRuntimePermissionUserIds) {
7695                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
7696            }
7697        }
7698    }
7699
7700    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7701        boolean allowed = false;
7702        final int NP = PackageParser.NEW_PERMISSIONS.length;
7703        for (int ip=0; ip<NP; ip++) {
7704            final PackageParser.NewPermissionInfo npi
7705                    = PackageParser.NEW_PERMISSIONS[ip];
7706            if (npi.name.equals(perm)
7707                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7708                allowed = true;
7709                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7710                        + pkg.packageName);
7711                break;
7712            }
7713        }
7714        return allowed;
7715    }
7716
7717    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7718            BasePermission bp, PermissionsState origPermissions) {
7719        boolean allowed;
7720        allowed = (compareSignatures(
7721                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7722                        == PackageManager.SIGNATURE_MATCH)
7723                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7724                        == PackageManager.SIGNATURE_MATCH);
7725        if (!allowed && (bp.protectionLevel
7726                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7727            if (isSystemApp(pkg)) {
7728                // For updated system applications, a system permission
7729                // is granted only if it had been defined by the original application.
7730                if (pkg.isUpdatedSystemApp()) {
7731                    final PackageSetting sysPs = mSettings
7732                            .getDisabledSystemPkgLPr(pkg.packageName);
7733                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
7734                        // If the original was granted this permission, we take
7735                        // that grant decision as read and propagate it to the
7736                        // update.
7737                        if (sysPs.isPrivileged()) {
7738                            allowed = true;
7739                        }
7740                    } else {
7741                        // The system apk may have been updated with an older
7742                        // version of the one on the data partition, but which
7743                        // granted a new system permission that it didn't have
7744                        // before.  In this case we do want to allow the app to
7745                        // now get the new permission if the ancestral apk is
7746                        // privileged to get it.
7747                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7748                            for (int j=0;
7749                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7750                                if (perm.equals(
7751                                        sysPs.pkg.requestedPermissions.get(j))) {
7752                                    allowed = true;
7753                                    break;
7754                                }
7755                            }
7756                        }
7757                    }
7758                } else {
7759                    allowed = isPrivilegedApp(pkg);
7760                }
7761            }
7762        }
7763        if (!allowed && (bp.protectionLevel
7764                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7765            // For development permissions, a development permission
7766            // is granted only if it was already granted.
7767            allowed = origPermissions.hasInstallPermission(perm);
7768        }
7769        return allowed;
7770    }
7771
7772    final class ActivityIntentResolver
7773            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7774        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7775                boolean defaultOnly, int userId) {
7776            if (!sUserManager.exists(userId)) return null;
7777            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7778            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7779        }
7780
7781        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7782                int userId) {
7783            if (!sUserManager.exists(userId)) return null;
7784            mFlags = flags;
7785            return super.queryIntent(intent, resolvedType,
7786                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7787        }
7788
7789        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7790                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7791            if (!sUserManager.exists(userId)) return null;
7792            if (packageActivities == null) {
7793                return null;
7794            }
7795            mFlags = flags;
7796            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7797            final int N = packageActivities.size();
7798            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7799                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7800
7801            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7802            for (int i = 0; i < N; ++i) {
7803                intentFilters = packageActivities.get(i).intents;
7804                if (intentFilters != null && intentFilters.size() > 0) {
7805                    PackageParser.ActivityIntentInfo[] array =
7806                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7807                    intentFilters.toArray(array);
7808                    listCut.add(array);
7809                }
7810            }
7811            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7812        }
7813
7814        public final void addActivity(PackageParser.Activity a, String type) {
7815            final boolean systemApp = a.info.applicationInfo.isSystemApp();
7816            mActivities.put(a.getComponentName(), a);
7817            if (DEBUG_SHOW_INFO)
7818                Log.v(
7819                TAG, "  " + type + " " +
7820                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7821            if (DEBUG_SHOW_INFO)
7822                Log.v(TAG, "    Class=" + a.info.name);
7823            final int NI = a.intents.size();
7824            for (int j=0; j<NI; j++) {
7825                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7826                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7827                    intent.setPriority(0);
7828                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7829                            + a.className + " with priority > 0, forcing to 0");
7830                }
7831                if (DEBUG_SHOW_INFO) {
7832                    Log.v(TAG, "    IntentFilter:");
7833                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7834                }
7835                if (!intent.debugCheck()) {
7836                    Log.w(TAG, "==> For Activity " + a.info.name);
7837                }
7838                addFilter(intent);
7839            }
7840        }
7841
7842        public final void removeActivity(PackageParser.Activity a, String type) {
7843            mActivities.remove(a.getComponentName());
7844            if (DEBUG_SHOW_INFO) {
7845                Log.v(TAG, "  " + type + " "
7846                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7847                                : a.info.name) + ":");
7848                Log.v(TAG, "    Class=" + a.info.name);
7849            }
7850            final int NI = a.intents.size();
7851            for (int j=0; j<NI; j++) {
7852                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7853                if (DEBUG_SHOW_INFO) {
7854                    Log.v(TAG, "    IntentFilter:");
7855                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7856                }
7857                removeFilter(intent);
7858            }
7859        }
7860
7861        @Override
7862        protected boolean allowFilterResult(
7863                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7864            ActivityInfo filterAi = filter.activity.info;
7865            for (int i=dest.size()-1; i>=0; i--) {
7866                ActivityInfo destAi = dest.get(i).activityInfo;
7867                if (destAi.name == filterAi.name
7868                        && destAi.packageName == filterAi.packageName) {
7869                    return false;
7870                }
7871            }
7872            return true;
7873        }
7874
7875        @Override
7876        protected ActivityIntentInfo[] newArray(int size) {
7877            return new ActivityIntentInfo[size];
7878        }
7879
7880        @Override
7881        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7882            if (!sUserManager.exists(userId)) return true;
7883            PackageParser.Package p = filter.activity.owner;
7884            if (p != null) {
7885                PackageSetting ps = (PackageSetting)p.mExtras;
7886                if (ps != null) {
7887                    // System apps are never considered stopped for purposes of
7888                    // filtering, because there may be no way for the user to
7889                    // actually re-launch them.
7890                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7891                            && ps.getStopped(userId);
7892                }
7893            }
7894            return false;
7895        }
7896
7897        @Override
7898        protected boolean isPackageForFilter(String packageName,
7899                PackageParser.ActivityIntentInfo info) {
7900            return packageName.equals(info.activity.owner.packageName);
7901        }
7902
7903        @Override
7904        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7905                int match, int userId) {
7906            if (!sUserManager.exists(userId)) return null;
7907            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7908                return null;
7909            }
7910            final PackageParser.Activity activity = info.activity;
7911            if (mSafeMode && (activity.info.applicationInfo.flags
7912                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7913                return null;
7914            }
7915            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7916            if (ps == null) {
7917                return null;
7918            }
7919            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7920                    ps.readUserState(userId), userId);
7921            if (ai == null) {
7922                return null;
7923            }
7924            final ResolveInfo res = new ResolveInfo();
7925            res.activityInfo = ai;
7926            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7927                res.filter = info;
7928            }
7929            if (info != null) {
7930                res.handleAllWebDataURI = info.handleAllWebDataURI();
7931            }
7932            res.priority = info.getPriority();
7933            res.preferredOrder = activity.owner.mPreferredOrder;
7934            //System.out.println("Result: " + res.activityInfo.className +
7935            //                   " = " + res.priority);
7936            res.match = match;
7937            res.isDefault = info.hasDefault;
7938            res.labelRes = info.labelRes;
7939            res.nonLocalizedLabel = info.nonLocalizedLabel;
7940            if (userNeedsBadging(userId)) {
7941                res.noResourceId = true;
7942            } else {
7943                res.icon = info.icon;
7944            }
7945            res.system = res.activityInfo.applicationInfo.isSystemApp();
7946            return res;
7947        }
7948
7949        @Override
7950        protected void sortResults(List<ResolveInfo> results) {
7951            Collections.sort(results, mResolvePrioritySorter);
7952        }
7953
7954        @Override
7955        protected void dumpFilter(PrintWriter out, String prefix,
7956                PackageParser.ActivityIntentInfo filter) {
7957            out.print(prefix); out.print(
7958                    Integer.toHexString(System.identityHashCode(filter.activity)));
7959                    out.print(' ');
7960                    filter.activity.printComponentShortName(out);
7961                    out.print(" filter ");
7962                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7963        }
7964
7965        @Override
7966        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
7967            return filter.activity;
7968        }
7969
7970        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7971            PackageParser.Activity activity = (PackageParser.Activity)label;
7972            out.print(prefix); out.print(
7973                    Integer.toHexString(System.identityHashCode(activity)));
7974                    out.print(' ');
7975                    activity.printComponentShortName(out);
7976            if (count > 1) {
7977                out.print(" ("); out.print(count); out.print(" filters)");
7978            }
7979            out.println();
7980        }
7981
7982//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7983//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7984//            final List<ResolveInfo> retList = Lists.newArrayList();
7985//            while (i.hasNext()) {
7986//                final ResolveInfo resolveInfo = i.next();
7987//                if (isEnabledLP(resolveInfo.activityInfo)) {
7988//                    retList.add(resolveInfo);
7989//                }
7990//            }
7991//            return retList;
7992//        }
7993
7994        // Keys are String (activity class name), values are Activity.
7995        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
7996                = new ArrayMap<ComponentName, PackageParser.Activity>();
7997        private int mFlags;
7998    }
7999
8000    private final class ServiceIntentResolver
8001            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8002        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8003                boolean defaultOnly, int userId) {
8004            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8005            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8006        }
8007
8008        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8009                int userId) {
8010            if (!sUserManager.exists(userId)) return null;
8011            mFlags = flags;
8012            return super.queryIntent(intent, resolvedType,
8013                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8014        }
8015
8016        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8017                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8018            if (!sUserManager.exists(userId)) return null;
8019            if (packageServices == null) {
8020                return null;
8021            }
8022            mFlags = flags;
8023            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8024            final int N = packageServices.size();
8025            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8026                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8027
8028            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8029            for (int i = 0; i < N; ++i) {
8030                intentFilters = packageServices.get(i).intents;
8031                if (intentFilters != null && intentFilters.size() > 0) {
8032                    PackageParser.ServiceIntentInfo[] array =
8033                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8034                    intentFilters.toArray(array);
8035                    listCut.add(array);
8036                }
8037            }
8038            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8039        }
8040
8041        public final void addService(PackageParser.Service s) {
8042            mServices.put(s.getComponentName(), s);
8043            if (DEBUG_SHOW_INFO) {
8044                Log.v(TAG, "  "
8045                        + (s.info.nonLocalizedLabel != null
8046                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8047                Log.v(TAG, "    Class=" + s.info.name);
8048            }
8049            final int NI = s.intents.size();
8050            int j;
8051            for (j=0; j<NI; j++) {
8052                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8053                if (DEBUG_SHOW_INFO) {
8054                    Log.v(TAG, "    IntentFilter:");
8055                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8056                }
8057                if (!intent.debugCheck()) {
8058                    Log.w(TAG, "==> For Service " + s.info.name);
8059                }
8060                addFilter(intent);
8061            }
8062        }
8063
8064        public final void removeService(PackageParser.Service s) {
8065            mServices.remove(s.getComponentName());
8066            if (DEBUG_SHOW_INFO) {
8067                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8068                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8069                Log.v(TAG, "    Class=" + s.info.name);
8070            }
8071            final int NI = s.intents.size();
8072            int j;
8073            for (j=0; j<NI; j++) {
8074                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8075                if (DEBUG_SHOW_INFO) {
8076                    Log.v(TAG, "    IntentFilter:");
8077                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8078                }
8079                removeFilter(intent);
8080            }
8081        }
8082
8083        @Override
8084        protected boolean allowFilterResult(
8085                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8086            ServiceInfo filterSi = filter.service.info;
8087            for (int i=dest.size()-1; i>=0; i--) {
8088                ServiceInfo destAi = dest.get(i).serviceInfo;
8089                if (destAi.name == filterSi.name
8090                        && destAi.packageName == filterSi.packageName) {
8091                    return false;
8092                }
8093            }
8094            return true;
8095        }
8096
8097        @Override
8098        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8099            return new PackageParser.ServiceIntentInfo[size];
8100        }
8101
8102        @Override
8103        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8104            if (!sUserManager.exists(userId)) return true;
8105            PackageParser.Package p = filter.service.owner;
8106            if (p != null) {
8107                PackageSetting ps = (PackageSetting)p.mExtras;
8108                if (ps != null) {
8109                    // System apps are never considered stopped for purposes of
8110                    // filtering, because there may be no way for the user to
8111                    // actually re-launch them.
8112                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8113                            && ps.getStopped(userId);
8114                }
8115            }
8116            return false;
8117        }
8118
8119        @Override
8120        protected boolean isPackageForFilter(String packageName,
8121                PackageParser.ServiceIntentInfo info) {
8122            return packageName.equals(info.service.owner.packageName);
8123        }
8124
8125        @Override
8126        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8127                int match, int userId) {
8128            if (!sUserManager.exists(userId)) return null;
8129            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8130            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8131                return null;
8132            }
8133            final PackageParser.Service service = info.service;
8134            if (mSafeMode && (service.info.applicationInfo.flags
8135                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8136                return null;
8137            }
8138            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8139            if (ps == null) {
8140                return null;
8141            }
8142            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8143                    ps.readUserState(userId), userId);
8144            if (si == null) {
8145                return null;
8146            }
8147            final ResolveInfo res = new ResolveInfo();
8148            res.serviceInfo = si;
8149            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8150                res.filter = filter;
8151            }
8152            res.priority = info.getPriority();
8153            res.preferredOrder = service.owner.mPreferredOrder;
8154            res.match = match;
8155            res.isDefault = info.hasDefault;
8156            res.labelRes = info.labelRes;
8157            res.nonLocalizedLabel = info.nonLocalizedLabel;
8158            res.icon = info.icon;
8159            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8160            return res;
8161        }
8162
8163        @Override
8164        protected void sortResults(List<ResolveInfo> results) {
8165            Collections.sort(results, mResolvePrioritySorter);
8166        }
8167
8168        @Override
8169        protected void dumpFilter(PrintWriter out, String prefix,
8170                PackageParser.ServiceIntentInfo filter) {
8171            out.print(prefix); out.print(
8172                    Integer.toHexString(System.identityHashCode(filter.service)));
8173                    out.print(' ');
8174                    filter.service.printComponentShortName(out);
8175                    out.print(" filter ");
8176                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8177        }
8178
8179        @Override
8180        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8181            return filter.service;
8182        }
8183
8184        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8185            PackageParser.Service service = (PackageParser.Service)label;
8186            out.print(prefix); out.print(
8187                    Integer.toHexString(System.identityHashCode(service)));
8188                    out.print(' ');
8189                    service.printComponentShortName(out);
8190            if (count > 1) {
8191                out.print(" ("); out.print(count); out.print(" filters)");
8192            }
8193            out.println();
8194        }
8195
8196//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8197//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8198//            final List<ResolveInfo> retList = Lists.newArrayList();
8199//            while (i.hasNext()) {
8200//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8201//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8202//                    retList.add(resolveInfo);
8203//                }
8204//            }
8205//            return retList;
8206//        }
8207
8208        // Keys are String (activity class name), values are Activity.
8209        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8210                = new ArrayMap<ComponentName, PackageParser.Service>();
8211        private int mFlags;
8212    };
8213
8214    private final class ProviderIntentResolver
8215            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8216        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8217                boolean defaultOnly, int userId) {
8218            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8219            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8220        }
8221
8222        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8223                int userId) {
8224            if (!sUserManager.exists(userId))
8225                return null;
8226            mFlags = flags;
8227            return super.queryIntent(intent, resolvedType,
8228                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8229        }
8230
8231        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8232                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8233            if (!sUserManager.exists(userId))
8234                return null;
8235            if (packageProviders == null) {
8236                return null;
8237            }
8238            mFlags = flags;
8239            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8240            final int N = packageProviders.size();
8241            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8242                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8243
8244            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8245            for (int i = 0; i < N; ++i) {
8246                intentFilters = packageProviders.get(i).intents;
8247                if (intentFilters != null && intentFilters.size() > 0) {
8248                    PackageParser.ProviderIntentInfo[] array =
8249                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8250                    intentFilters.toArray(array);
8251                    listCut.add(array);
8252                }
8253            }
8254            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8255        }
8256
8257        public final void addProvider(PackageParser.Provider p) {
8258            if (mProviders.containsKey(p.getComponentName())) {
8259                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8260                return;
8261            }
8262
8263            mProviders.put(p.getComponentName(), p);
8264            if (DEBUG_SHOW_INFO) {
8265                Log.v(TAG, "  "
8266                        + (p.info.nonLocalizedLabel != null
8267                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8268                Log.v(TAG, "    Class=" + p.info.name);
8269            }
8270            final int NI = p.intents.size();
8271            int j;
8272            for (j = 0; j < NI; j++) {
8273                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8274                if (DEBUG_SHOW_INFO) {
8275                    Log.v(TAG, "    IntentFilter:");
8276                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8277                }
8278                if (!intent.debugCheck()) {
8279                    Log.w(TAG, "==> For Provider " + p.info.name);
8280                }
8281                addFilter(intent);
8282            }
8283        }
8284
8285        public final void removeProvider(PackageParser.Provider p) {
8286            mProviders.remove(p.getComponentName());
8287            if (DEBUG_SHOW_INFO) {
8288                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8289                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8290                Log.v(TAG, "    Class=" + p.info.name);
8291            }
8292            final int NI = p.intents.size();
8293            int j;
8294            for (j = 0; j < NI; j++) {
8295                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8296                if (DEBUG_SHOW_INFO) {
8297                    Log.v(TAG, "    IntentFilter:");
8298                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8299                }
8300                removeFilter(intent);
8301            }
8302        }
8303
8304        @Override
8305        protected boolean allowFilterResult(
8306                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8307            ProviderInfo filterPi = filter.provider.info;
8308            for (int i = dest.size() - 1; i >= 0; i--) {
8309                ProviderInfo destPi = dest.get(i).providerInfo;
8310                if (destPi.name == filterPi.name
8311                        && destPi.packageName == filterPi.packageName) {
8312                    return false;
8313                }
8314            }
8315            return true;
8316        }
8317
8318        @Override
8319        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8320            return new PackageParser.ProviderIntentInfo[size];
8321        }
8322
8323        @Override
8324        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8325            if (!sUserManager.exists(userId))
8326                return true;
8327            PackageParser.Package p = filter.provider.owner;
8328            if (p != null) {
8329                PackageSetting ps = (PackageSetting) p.mExtras;
8330                if (ps != null) {
8331                    // System apps are never considered stopped for purposes of
8332                    // filtering, because there may be no way for the user to
8333                    // actually re-launch them.
8334                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8335                            && ps.getStopped(userId);
8336                }
8337            }
8338            return false;
8339        }
8340
8341        @Override
8342        protected boolean isPackageForFilter(String packageName,
8343                PackageParser.ProviderIntentInfo info) {
8344            return packageName.equals(info.provider.owner.packageName);
8345        }
8346
8347        @Override
8348        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8349                int match, int userId) {
8350            if (!sUserManager.exists(userId))
8351                return null;
8352            final PackageParser.ProviderIntentInfo info = filter;
8353            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8354                return null;
8355            }
8356            final PackageParser.Provider provider = info.provider;
8357            if (mSafeMode && (provider.info.applicationInfo.flags
8358                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8359                return null;
8360            }
8361            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8362            if (ps == null) {
8363                return null;
8364            }
8365            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8366                    ps.readUserState(userId), userId);
8367            if (pi == null) {
8368                return null;
8369            }
8370            final ResolveInfo res = new ResolveInfo();
8371            res.providerInfo = pi;
8372            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8373                res.filter = filter;
8374            }
8375            res.priority = info.getPriority();
8376            res.preferredOrder = provider.owner.mPreferredOrder;
8377            res.match = match;
8378            res.isDefault = info.hasDefault;
8379            res.labelRes = info.labelRes;
8380            res.nonLocalizedLabel = info.nonLocalizedLabel;
8381            res.icon = info.icon;
8382            res.system = res.providerInfo.applicationInfo.isSystemApp();
8383            return res;
8384        }
8385
8386        @Override
8387        protected void sortResults(List<ResolveInfo> results) {
8388            Collections.sort(results, mResolvePrioritySorter);
8389        }
8390
8391        @Override
8392        protected void dumpFilter(PrintWriter out, String prefix,
8393                PackageParser.ProviderIntentInfo filter) {
8394            out.print(prefix);
8395            out.print(
8396                    Integer.toHexString(System.identityHashCode(filter.provider)));
8397            out.print(' ');
8398            filter.provider.printComponentShortName(out);
8399            out.print(" filter ");
8400            out.println(Integer.toHexString(System.identityHashCode(filter)));
8401        }
8402
8403        @Override
8404        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8405            return filter.provider;
8406        }
8407
8408        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8409            PackageParser.Provider provider = (PackageParser.Provider)label;
8410            out.print(prefix); out.print(
8411                    Integer.toHexString(System.identityHashCode(provider)));
8412                    out.print(' ');
8413                    provider.printComponentShortName(out);
8414            if (count > 1) {
8415                out.print(" ("); out.print(count); out.print(" filters)");
8416            }
8417            out.println();
8418        }
8419
8420        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8421                = new ArrayMap<ComponentName, PackageParser.Provider>();
8422        private int mFlags;
8423    };
8424
8425    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8426            new Comparator<ResolveInfo>() {
8427        public int compare(ResolveInfo r1, ResolveInfo r2) {
8428            int v1 = r1.priority;
8429            int v2 = r2.priority;
8430            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8431            if (v1 != v2) {
8432                return (v1 > v2) ? -1 : 1;
8433            }
8434            v1 = r1.preferredOrder;
8435            v2 = r2.preferredOrder;
8436            if (v1 != v2) {
8437                return (v1 > v2) ? -1 : 1;
8438            }
8439            if (r1.isDefault != r2.isDefault) {
8440                return r1.isDefault ? -1 : 1;
8441            }
8442            v1 = r1.match;
8443            v2 = r2.match;
8444            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8445            if (v1 != v2) {
8446                return (v1 > v2) ? -1 : 1;
8447            }
8448            if (r1.system != r2.system) {
8449                return r1.system ? -1 : 1;
8450            }
8451            return 0;
8452        }
8453    };
8454
8455    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8456            new Comparator<ProviderInfo>() {
8457        public int compare(ProviderInfo p1, ProviderInfo p2) {
8458            final int v1 = p1.initOrder;
8459            final int v2 = p2.initOrder;
8460            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8461        }
8462    };
8463
8464    static final void sendPackageBroadcast(String action, String pkg,
8465            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
8466            int[] userIds) {
8467        IActivityManager am = ActivityManagerNative.getDefault();
8468        if (am != null) {
8469            try {
8470                if (userIds == null) {
8471                    userIds = am.getRunningUserIds();
8472                }
8473                for (int id : userIds) {
8474                    final Intent intent = new Intent(action,
8475                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
8476                    if (extras != null) {
8477                        intent.putExtras(extras);
8478                    }
8479                    if (targetPkg != null) {
8480                        intent.setPackage(targetPkg);
8481                    }
8482                    // Modify the UID when posting to other users
8483                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8484                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
8485                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8486                        intent.putExtra(Intent.EXTRA_UID, uid);
8487                    }
8488                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8489                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8490                    if (DEBUG_BROADCASTS) {
8491                        RuntimeException here = new RuntimeException("here");
8492                        here.fillInStackTrace();
8493                        Slog.d(TAG, "Sending to user " + id + ": "
8494                                + intent.toShortString(false, true, false, false)
8495                                + " " + intent.getExtras(), here);
8496                    }
8497                    am.broadcastIntent(null, intent, null, finishedReceiver,
8498                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
8499                            finishedReceiver != null, false, id);
8500                }
8501            } catch (RemoteException ex) {
8502            }
8503        }
8504    }
8505
8506    /**
8507     * Check if the external storage media is available. This is true if there
8508     * is a mounted external storage medium or if the external storage is
8509     * emulated.
8510     */
8511    private boolean isExternalMediaAvailable() {
8512        return mMediaMounted || Environment.isExternalStorageEmulated();
8513    }
8514
8515    @Override
8516    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8517        // writer
8518        synchronized (mPackages) {
8519            if (!isExternalMediaAvailable()) {
8520                // If the external storage is no longer mounted at this point,
8521                // the caller may not have been able to delete all of this
8522                // packages files and can not delete any more.  Bail.
8523                return null;
8524            }
8525            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8526            if (lastPackage != null) {
8527                pkgs.remove(lastPackage);
8528            }
8529            if (pkgs.size() > 0) {
8530                return pkgs.get(0);
8531            }
8532        }
8533        return null;
8534    }
8535
8536    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8537        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8538                userId, andCode ? 1 : 0, packageName);
8539        if (mSystemReady) {
8540            msg.sendToTarget();
8541        } else {
8542            if (mPostSystemReadyMessages == null) {
8543                mPostSystemReadyMessages = new ArrayList<>();
8544            }
8545            mPostSystemReadyMessages.add(msg);
8546        }
8547    }
8548
8549    void startCleaningPackages() {
8550        // reader
8551        synchronized (mPackages) {
8552            if (!isExternalMediaAvailable()) {
8553                return;
8554            }
8555            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8556                return;
8557            }
8558        }
8559        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8560        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8561        IActivityManager am = ActivityManagerNative.getDefault();
8562        if (am != null) {
8563            try {
8564                am.startService(null, intent, null, UserHandle.USER_OWNER);
8565            } catch (RemoteException e) {
8566            }
8567        }
8568    }
8569
8570    @Override
8571    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8572            int installFlags, String installerPackageName, VerificationParams verificationParams,
8573            String packageAbiOverride) {
8574        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8575                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8576    }
8577
8578    @Override
8579    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8580            int installFlags, String installerPackageName, VerificationParams verificationParams,
8581            String packageAbiOverride, int userId) {
8582        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8583
8584        final int callingUid = Binder.getCallingUid();
8585        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8586
8587        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8588            try {
8589                if (observer != null) {
8590                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8591                }
8592            } catch (RemoteException re) {
8593            }
8594            return;
8595        }
8596
8597        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8598            installFlags |= PackageManager.INSTALL_FROM_ADB;
8599
8600        } else {
8601            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8602            // about installerPackageName.
8603
8604            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8605            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8606        }
8607
8608        UserHandle user;
8609        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8610            user = UserHandle.ALL;
8611        } else {
8612            user = new UserHandle(userId);
8613        }
8614
8615        // Only system components can circumvent runtime permissions when installing.
8616        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
8617                && mContext.checkCallingOrSelfPermission(Manifest.permission
8618                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
8619            throw new SecurityException("You need the "
8620                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
8621                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
8622        }
8623
8624        verificationParams.setInstallerUid(callingUid);
8625
8626        final File originFile = new File(originPath);
8627        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8628
8629        final Message msg = mHandler.obtainMessage(INIT_COPY);
8630        msg.obj = new InstallParams(origin, observer, installFlags,
8631                installerPackageName, null, verificationParams, user, packageAbiOverride);
8632        mHandler.sendMessage(msg);
8633    }
8634
8635    void installStage(String packageName, File stagedDir, String stagedCid,
8636            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8637            String installerPackageName, int installerUid, UserHandle user) {
8638        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8639                params.referrerUri, installerUid, null);
8640
8641        final OriginInfo origin;
8642        if (stagedDir != null) {
8643            origin = OriginInfo.fromStagedFile(stagedDir);
8644        } else {
8645            origin = OriginInfo.fromStagedContainer(stagedCid);
8646        }
8647
8648        final Message msg = mHandler.obtainMessage(INIT_COPY);
8649        msg.obj = new InstallParams(origin, observer, params.installFlags,
8650                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8651        mHandler.sendMessage(msg);
8652    }
8653
8654    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8655        Bundle extras = new Bundle(1);
8656        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8657
8658        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8659                packageName, extras, null, null, new int[] {userId});
8660        try {
8661            IActivityManager am = ActivityManagerNative.getDefault();
8662            final boolean isSystem =
8663                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8664            if (isSystem && am.isUserRunning(userId, false)) {
8665                // The just-installed/enabled app is bundled on the system, so presumed
8666                // to be able to run automatically without needing an explicit launch.
8667                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8668                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8669                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8670                        .setPackage(packageName);
8671                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8672                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8673            }
8674        } catch (RemoteException e) {
8675            // shouldn't happen
8676            Slog.w(TAG, "Unable to bootstrap installed package", e);
8677        }
8678    }
8679
8680    @Override
8681    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8682            int userId) {
8683        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8684        PackageSetting pkgSetting;
8685        final int uid = Binder.getCallingUid();
8686        enforceCrossUserPermission(uid, userId, true, true,
8687                "setApplicationHiddenSetting for user " + userId);
8688
8689        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8690            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8691            return false;
8692        }
8693
8694        long callingId = Binder.clearCallingIdentity();
8695        try {
8696            boolean sendAdded = false;
8697            boolean sendRemoved = false;
8698            // writer
8699            synchronized (mPackages) {
8700                pkgSetting = mSettings.mPackages.get(packageName);
8701                if (pkgSetting == null) {
8702                    return false;
8703                }
8704                if (pkgSetting.getHidden(userId) != hidden) {
8705                    pkgSetting.setHidden(hidden, userId);
8706                    mSettings.writePackageRestrictionsLPr(userId);
8707                    if (hidden) {
8708                        sendRemoved = true;
8709                    } else {
8710                        sendAdded = true;
8711                    }
8712                }
8713            }
8714            if (sendAdded) {
8715                sendPackageAddedForUser(packageName, pkgSetting, userId);
8716                return true;
8717            }
8718            if (sendRemoved) {
8719                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8720                        "hiding pkg");
8721                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8722            }
8723        } finally {
8724            Binder.restoreCallingIdentity(callingId);
8725        }
8726        return false;
8727    }
8728
8729    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8730            int userId) {
8731        final PackageRemovedInfo info = new PackageRemovedInfo();
8732        info.removedPackage = packageName;
8733        info.removedUsers = new int[] {userId};
8734        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8735        info.sendBroadcast(false, false, false);
8736    }
8737
8738    /**
8739     * Returns true if application is not found or there was an error. Otherwise it returns
8740     * the hidden state of the package for the given user.
8741     */
8742    @Override
8743    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8744        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8745        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8746                false, "getApplicationHidden for user " + userId);
8747        PackageSetting pkgSetting;
8748        long callingId = Binder.clearCallingIdentity();
8749        try {
8750            // writer
8751            synchronized (mPackages) {
8752                pkgSetting = mSettings.mPackages.get(packageName);
8753                if (pkgSetting == null) {
8754                    return true;
8755                }
8756                return pkgSetting.getHidden(userId);
8757            }
8758        } finally {
8759            Binder.restoreCallingIdentity(callingId);
8760        }
8761    }
8762
8763    /**
8764     * @hide
8765     */
8766    @Override
8767    public int installExistingPackageAsUser(String packageName, int userId) {
8768        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8769                null);
8770        PackageSetting pkgSetting;
8771        final int uid = Binder.getCallingUid();
8772        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8773                + userId);
8774        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8775            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8776        }
8777
8778        long callingId = Binder.clearCallingIdentity();
8779        try {
8780            boolean sendAdded = false;
8781
8782            // writer
8783            synchronized (mPackages) {
8784                pkgSetting = mSettings.mPackages.get(packageName);
8785                if (pkgSetting == null) {
8786                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8787                }
8788                if (!pkgSetting.getInstalled(userId)) {
8789                    pkgSetting.setInstalled(true, userId);
8790                    pkgSetting.setHidden(false, userId);
8791                    mSettings.writePackageRestrictionsLPr(userId);
8792                    sendAdded = true;
8793                }
8794            }
8795
8796            if (sendAdded) {
8797                sendPackageAddedForUser(packageName, pkgSetting, userId);
8798            }
8799        } finally {
8800            Binder.restoreCallingIdentity(callingId);
8801        }
8802
8803        return PackageManager.INSTALL_SUCCEEDED;
8804    }
8805
8806    boolean isUserRestricted(int userId, String restrictionKey) {
8807        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8808        if (restrictions.getBoolean(restrictionKey, false)) {
8809            Log.w(TAG, "User is restricted: " + restrictionKey);
8810            return true;
8811        }
8812        return false;
8813    }
8814
8815    @Override
8816    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8817        mContext.enforceCallingOrSelfPermission(
8818                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8819                "Only package verification agents can verify applications");
8820
8821        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8822        final PackageVerificationResponse response = new PackageVerificationResponse(
8823                verificationCode, Binder.getCallingUid());
8824        msg.arg1 = id;
8825        msg.obj = response;
8826        mHandler.sendMessage(msg);
8827    }
8828
8829    @Override
8830    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8831            long millisecondsToDelay) {
8832        mContext.enforceCallingOrSelfPermission(
8833                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8834                "Only package verification agents can extend verification timeouts");
8835
8836        final PackageVerificationState state = mPendingVerification.get(id);
8837        final PackageVerificationResponse response = new PackageVerificationResponse(
8838                verificationCodeAtTimeout, Binder.getCallingUid());
8839
8840        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8841            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8842        }
8843        if (millisecondsToDelay < 0) {
8844            millisecondsToDelay = 0;
8845        }
8846        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8847                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8848            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8849        }
8850
8851        if ((state != null) && !state.timeoutExtended()) {
8852            state.extendTimeout();
8853
8854            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8855            msg.arg1 = id;
8856            msg.obj = response;
8857            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8858        }
8859    }
8860
8861    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8862            int verificationCode, UserHandle user) {
8863        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8864        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8865        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8866        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8867        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8868
8869        mContext.sendBroadcastAsUser(intent, user,
8870                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8871    }
8872
8873    private ComponentName matchComponentForVerifier(String packageName,
8874            List<ResolveInfo> receivers) {
8875        ActivityInfo targetReceiver = null;
8876
8877        final int NR = receivers.size();
8878        for (int i = 0; i < NR; i++) {
8879            final ResolveInfo info = receivers.get(i);
8880            if (info.activityInfo == null) {
8881                continue;
8882            }
8883
8884            if (packageName.equals(info.activityInfo.packageName)) {
8885                targetReceiver = info.activityInfo;
8886                break;
8887            }
8888        }
8889
8890        if (targetReceiver == null) {
8891            return null;
8892        }
8893
8894        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8895    }
8896
8897    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8898            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8899        if (pkgInfo.verifiers.length == 0) {
8900            return null;
8901        }
8902
8903        final int N = pkgInfo.verifiers.length;
8904        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8905        for (int i = 0; i < N; i++) {
8906            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8907
8908            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8909                    receivers);
8910            if (comp == null) {
8911                continue;
8912            }
8913
8914            final int verifierUid = getUidForVerifier(verifierInfo);
8915            if (verifierUid == -1) {
8916                continue;
8917            }
8918
8919            if (DEBUG_VERIFY) {
8920                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8921                        + " with the correct signature");
8922            }
8923            sufficientVerifiers.add(comp);
8924            verificationState.addSufficientVerifier(verifierUid);
8925        }
8926
8927        return sufficientVerifiers;
8928    }
8929
8930    private int getUidForVerifier(VerifierInfo verifierInfo) {
8931        synchronized (mPackages) {
8932            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8933            if (pkg == null) {
8934                return -1;
8935            } else if (pkg.mSignatures.length != 1) {
8936                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8937                        + " has more than one signature; ignoring");
8938                return -1;
8939            }
8940
8941            /*
8942             * If the public key of the package's signature does not match
8943             * our expected public key, then this is a different package and
8944             * we should skip.
8945             */
8946
8947            final byte[] expectedPublicKey;
8948            try {
8949                final Signature verifierSig = pkg.mSignatures[0];
8950                final PublicKey publicKey = verifierSig.getPublicKey();
8951                expectedPublicKey = publicKey.getEncoded();
8952            } catch (CertificateException e) {
8953                return -1;
8954            }
8955
8956            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8957
8958            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8959                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8960                        + " does not have the expected public key; ignoring");
8961                return -1;
8962            }
8963
8964            return pkg.applicationInfo.uid;
8965        }
8966    }
8967
8968    @Override
8969    public void finishPackageInstall(int token) {
8970        enforceSystemOrRoot("Only the system is allowed to finish installs");
8971
8972        if (DEBUG_INSTALL) {
8973            Slog.v(TAG, "BM finishing package install for " + token);
8974        }
8975
8976        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8977        mHandler.sendMessage(msg);
8978    }
8979
8980    /**
8981     * Get the verification agent timeout.
8982     *
8983     * @return verification timeout in milliseconds
8984     */
8985    private long getVerificationTimeout() {
8986        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8987                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8988                DEFAULT_VERIFICATION_TIMEOUT);
8989    }
8990
8991    /**
8992     * Get the default verification agent response code.
8993     *
8994     * @return default verification response code
8995     */
8996    private int getDefaultVerificationResponse() {
8997        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8998                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8999                DEFAULT_VERIFICATION_RESPONSE);
9000    }
9001
9002    /**
9003     * Check whether or not package verification has been enabled.
9004     *
9005     * @return true if verification should be performed
9006     */
9007    private boolean isVerificationEnabled(int userId, int installFlags) {
9008        if (!DEFAULT_VERIFY_ENABLE) {
9009            return false;
9010        }
9011
9012        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9013
9014        // Check if installing from ADB
9015        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9016            // Do not run verification in a test harness environment
9017            if (ActivityManager.isRunningInTestHarness()) {
9018                return false;
9019            }
9020            if (ensureVerifyAppsEnabled) {
9021                return true;
9022            }
9023            // Check if the developer does not want package verification for ADB installs
9024            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9025                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9026                return false;
9027            }
9028        }
9029
9030        if (ensureVerifyAppsEnabled) {
9031            return true;
9032        }
9033
9034        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9035                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9036    }
9037
9038    @Override
9039    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9040            throws RemoteException {
9041        mContext.enforceCallingOrSelfPermission(
9042                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9043                "Only intentfilter verification agents can verify applications");
9044
9045        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9046        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9047                Binder.getCallingUid(), verificationCode, failedDomains);
9048        msg.arg1 = id;
9049        msg.obj = response;
9050        mHandler.sendMessage(msg);
9051    }
9052
9053    @Override
9054    public int getIntentVerificationStatus(String packageName, int userId) {
9055        synchronized (mPackages) {
9056            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9057        }
9058    }
9059
9060    @Override
9061    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9062        boolean result = false;
9063        synchronized (mPackages) {
9064            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9065        }
9066        scheduleWritePackageRestrictionsLocked(userId);
9067        return result;
9068    }
9069
9070    @Override
9071    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9072        synchronized (mPackages) {
9073            return mSettings.getIntentFilterVerificationsLPr(packageName);
9074        }
9075    }
9076
9077    @Override
9078    public List<IntentFilter> getAllIntentFilters(String packageName) {
9079        if (TextUtils.isEmpty(packageName)) {
9080            return Collections.<IntentFilter>emptyList();
9081        }
9082        synchronized (mPackages) {
9083            PackageParser.Package pkg = mPackages.get(packageName);
9084            if (pkg == null || pkg.activities == null) {
9085                return Collections.<IntentFilter>emptyList();
9086            }
9087            final int count = pkg.activities.size();
9088            ArrayList<IntentFilter> result = new ArrayList<>();
9089            for (int n=0; n<count; n++) {
9090                PackageParser.Activity activity = pkg.activities.get(n);
9091                if (activity.intents != null || activity.intents.size() > 0) {
9092                    result.addAll(activity.intents);
9093                }
9094            }
9095            return result;
9096        }
9097    }
9098
9099    /**
9100     * Get the "allow unknown sources" setting.
9101     *
9102     * @return the current "allow unknown sources" setting
9103     */
9104    private int getUnknownSourcesSettings() {
9105        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9106                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9107                -1);
9108    }
9109
9110    @Override
9111    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9112        final int uid = Binder.getCallingUid();
9113        // writer
9114        synchronized (mPackages) {
9115            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9116            if (targetPackageSetting == null) {
9117                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9118            }
9119
9120            PackageSetting installerPackageSetting;
9121            if (installerPackageName != null) {
9122                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9123                if (installerPackageSetting == null) {
9124                    throw new IllegalArgumentException("Unknown installer package: "
9125                            + installerPackageName);
9126                }
9127            } else {
9128                installerPackageSetting = null;
9129            }
9130
9131            Signature[] callerSignature;
9132            Object obj = mSettings.getUserIdLPr(uid);
9133            if (obj != null) {
9134                if (obj instanceof SharedUserSetting) {
9135                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9136                } else if (obj instanceof PackageSetting) {
9137                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9138                } else {
9139                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9140                }
9141            } else {
9142                throw new SecurityException("Unknown calling uid " + uid);
9143            }
9144
9145            // Verify: can't set installerPackageName to a package that is
9146            // not signed with the same cert as the caller.
9147            if (installerPackageSetting != null) {
9148                if (compareSignatures(callerSignature,
9149                        installerPackageSetting.signatures.mSignatures)
9150                        != PackageManager.SIGNATURE_MATCH) {
9151                    throw new SecurityException(
9152                            "Caller does not have same cert as new installer package "
9153                            + installerPackageName);
9154                }
9155            }
9156
9157            // Verify: if target already has an installer package, it must
9158            // be signed with the same cert as the caller.
9159            if (targetPackageSetting.installerPackageName != null) {
9160                PackageSetting setting = mSettings.mPackages.get(
9161                        targetPackageSetting.installerPackageName);
9162                // If the currently set package isn't valid, then it's always
9163                // okay to change it.
9164                if (setting != null) {
9165                    if (compareSignatures(callerSignature,
9166                            setting.signatures.mSignatures)
9167                            != PackageManager.SIGNATURE_MATCH) {
9168                        throw new SecurityException(
9169                                "Caller does not have same cert as old installer package "
9170                                + targetPackageSetting.installerPackageName);
9171                    }
9172                }
9173            }
9174
9175            // Okay!
9176            targetPackageSetting.installerPackageName = installerPackageName;
9177            scheduleWriteSettingsLocked();
9178        }
9179    }
9180
9181    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9182        // Queue up an async operation since the package installation may take a little while.
9183        mHandler.post(new Runnable() {
9184            public void run() {
9185                mHandler.removeCallbacks(this);
9186                 // Result object to be returned
9187                PackageInstalledInfo res = new PackageInstalledInfo();
9188                res.returnCode = currentStatus;
9189                res.uid = -1;
9190                res.pkg = null;
9191                res.removedInfo = new PackageRemovedInfo();
9192                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9193                    args.doPreInstall(res.returnCode);
9194                    synchronized (mInstallLock) {
9195                        installPackageLI(args, res);
9196                    }
9197                    args.doPostInstall(res.returnCode, res.uid);
9198                }
9199
9200                // A restore should be performed at this point if (a) the install
9201                // succeeded, (b) the operation is not an update, and (c) the new
9202                // package has not opted out of backup participation.
9203                final boolean update = res.removedInfo.removedPackage != null;
9204                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9205                boolean doRestore = !update
9206                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9207
9208                // Set up the post-install work request bookkeeping.  This will be used
9209                // and cleaned up by the post-install event handling regardless of whether
9210                // there's a restore pass performed.  Token values are >= 1.
9211                int token;
9212                if (mNextInstallToken < 0) mNextInstallToken = 1;
9213                token = mNextInstallToken++;
9214
9215                PostInstallData data = new PostInstallData(args, res);
9216                mRunningInstalls.put(token, data);
9217                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9218
9219                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9220                    // Pass responsibility to the Backup Manager.  It will perform a
9221                    // restore if appropriate, then pass responsibility back to the
9222                    // Package Manager to run the post-install observer callbacks
9223                    // and broadcasts.
9224                    IBackupManager bm = IBackupManager.Stub.asInterface(
9225                            ServiceManager.getService(Context.BACKUP_SERVICE));
9226                    if (bm != null) {
9227                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9228                                + " to BM for possible restore");
9229                        try {
9230                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9231                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9232                            } else {
9233                                doRestore = false;
9234                            }
9235                        } catch (RemoteException e) {
9236                            // can't happen; the backup manager is local
9237                        } catch (Exception e) {
9238                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9239                            doRestore = false;
9240                        }
9241                    } else {
9242                        Slog.e(TAG, "Backup Manager not found!");
9243                        doRestore = false;
9244                    }
9245                }
9246
9247                if (!doRestore) {
9248                    // No restore possible, or the Backup Manager was mysteriously not
9249                    // available -- just fire the post-install work request directly.
9250                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9251                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9252                    mHandler.sendMessage(msg);
9253                }
9254            }
9255        });
9256    }
9257
9258    private abstract class HandlerParams {
9259        private static final int MAX_RETRIES = 4;
9260
9261        /**
9262         * Number of times startCopy() has been attempted and had a non-fatal
9263         * error.
9264         */
9265        private int mRetries = 0;
9266
9267        /** User handle for the user requesting the information or installation. */
9268        private final UserHandle mUser;
9269
9270        HandlerParams(UserHandle user) {
9271            mUser = user;
9272        }
9273
9274        UserHandle getUser() {
9275            return mUser;
9276        }
9277
9278        final boolean startCopy() {
9279            boolean res;
9280            try {
9281                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9282
9283                if (++mRetries > MAX_RETRIES) {
9284                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9285                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9286                    handleServiceError();
9287                    return false;
9288                } else {
9289                    handleStartCopy();
9290                    res = true;
9291                }
9292            } catch (RemoteException e) {
9293                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9294                mHandler.sendEmptyMessage(MCS_RECONNECT);
9295                res = false;
9296            }
9297            handleReturnCode();
9298            return res;
9299        }
9300
9301        final void serviceError() {
9302            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9303            handleServiceError();
9304            handleReturnCode();
9305        }
9306
9307        abstract void handleStartCopy() throws RemoteException;
9308        abstract void handleServiceError();
9309        abstract void handleReturnCode();
9310    }
9311
9312    class MeasureParams extends HandlerParams {
9313        private final PackageStats mStats;
9314        private boolean mSuccess;
9315
9316        private final IPackageStatsObserver mObserver;
9317
9318        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9319            super(new UserHandle(stats.userHandle));
9320            mObserver = observer;
9321            mStats = stats;
9322        }
9323
9324        @Override
9325        public String toString() {
9326            return "MeasureParams{"
9327                + Integer.toHexString(System.identityHashCode(this))
9328                + " " + mStats.packageName + "}";
9329        }
9330
9331        @Override
9332        void handleStartCopy() throws RemoteException {
9333            synchronized (mInstallLock) {
9334                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9335            }
9336
9337            if (mSuccess) {
9338                final boolean mounted;
9339                if (Environment.isExternalStorageEmulated()) {
9340                    mounted = true;
9341                } else {
9342                    final String status = Environment.getExternalStorageState();
9343                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9344                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9345                }
9346
9347                if (mounted) {
9348                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9349
9350                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9351                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9352
9353                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9354                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9355
9356                    // Always subtract cache size, since it's a subdirectory
9357                    mStats.externalDataSize -= mStats.externalCacheSize;
9358
9359                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9360                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9361
9362                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9363                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9364                }
9365            }
9366        }
9367
9368        @Override
9369        void handleReturnCode() {
9370            if (mObserver != null) {
9371                try {
9372                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9373                } catch (RemoteException e) {
9374                    Slog.i(TAG, "Observer no longer exists.");
9375                }
9376            }
9377        }
9378
9379        @Override
9380        void handleServiceError() {
9381            Slog.e(TAG, "Could not measure application " + mStats.packageName
9382                            + " external storage");
9383        }
9384    }
9385
9386    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9387            throws RemoteException {
9388        long result = 0;
9389        for (File path : paths) {
9390            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9391        }
9392        return result;
9393    }
9394
9395    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9396        for (File path : paths) {
9397            try {
9398                mcs.clearDirectory(path.getAbsolutePath());
9399            } catch (RemoteException e) {
9400            }
9401        }
9402    }
9403
9404    static class OriginInfo {
9405        /**
9406         * Location where install is coming from, before it has been
9407         * copied/renamed into place. This could be a single monolithic APK
9408         * file, or a cluster directory. This location may be untrusted.
9409         */
9410        final File file;
9411        final String cid;
9412
9413        /**
9414         * Flag indicating that {@link #file} or {@link #cid} has already been
9415         * staged, meaning downstream users don't need to defensively copy the
9416         * contents.
9417         */
9418        final boolean staged;
9419
9420        /**
9421         * Flag indicating that {@link #file} or {@link #cid} is an already
9422         * installed app that is being moved.
9423         */
9424        final boolean existing;
9425
9426        final String resolvedPath;
9427        final File resolvedFile;
9428
9429        static OriginInfo fromNothing() {
9430            return new OriginInfo(null, null, false, false);
9431        }
9432
9433        static OriginInfo fromUntrustedFile(File file) {
9434            return new OriginInfo(file, null, false, false);
9435        }
9436
9437        static OriginInfo fromExistingFile(File file) {
9438            return new OriginInfo(file, null, false, true);
9439        }
9440
9441        static OriginInfo fromStagedFile(File file) {
9442            return new OriginInfo(file, null, true, false);
9443        }
9444
9445        static OriginInfo fromStagedContainer(String cid) {
9446            return new OriginInfo(null, cid, true, false);
9447        }
9448
9449        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9450            this.file = file;
9451            this.cid = cid;
9452            this.staged = staged;
9453            this.existing = existing;
9454
9455            if (cid != null) {
9456                resolvedPath = PackageHelper.getSdDir(cid);
9457                resolvedFile = new File(resolvedPath);
9458            } else if (file != null) {
9459                resolvedPath = file.getAbsolutePath();
9460                resolvedFile = file;
9461            } else {
9462                resolvedPath = null;
9463                resolvedFile = null;
9464            }
9465        }
9466    }
9467
9468    class InstallParams extends HandlerParams {
9469        final OriginInfo origin;
9470        final IPackageInstallObserver2 observer;
9471        int installFlags;
9472        final String installerPackageName;
9473        final String volumeUuid;
9474        final VerificationParams verificationParams;
9475        private InstallArgs mArgs;
9476        private int mRet;
9477        final String packageAbiOverride;
9478
9479        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9480                String installerPackageName, String volumeUuid,
9481                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9482            super(user);
9483            this.origin = origin;
9484            this.observer = observer;
9485            this.installFlags = installFlags;
9486            this.installerPackageName = installerPackageName;
9487            this.volumeUuid = volumeUuid;
9488            this.verificationParams = verificationParams;
9489            this.packageAbiOverride = packageAbiOverride;
9490        }
9491
9492        @Override
9493        public String toString() {
9494            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9495                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9496        }
9497
9498        public ManifestDigest getManifestDigest() {
9499            if (verificationParams == null) {
9500                return null;
9501            }
9502            return verificationParams.getManifestDigest();
9503        }
9504
9505        private int installLocationPolicy(PackageInfoLite pkgLite) {
9506            String packageName = pkgLite.packageName;
9507            int installLocation = pkgLite.installLocation;
9508            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9509            // reader
9510            synchronized (mPackages) {
9511                PackageParser.Package pkg = mPackages.get(packageName);
9512                if (pkg != null) {
9513                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9514                        // Check for downgrading.
9515                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9516                            try {
9517                                checkDowngrade(pkg, pkgLite);
9518                            } catch (PackageManagerException e) {
9519                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9520                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9521                            }
9522                        }
9523                        // Check for updated system application.
9524                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9525                            if (onSd) {
9526                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9527                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9528                            }
9529                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9530                        } else {
9531                            if (onSd) {
9532                                // Install flag overrides everything.
9533                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9534                            }
9535                            // If current upgrade specifies particular preference
9536                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9537                                // Application explicitly specified internal.
9538                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9539                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9540                                // App explictly prefers external. Let policy decide
9541                            } else {
9542                                // Prefer previous location
9543                                if (isExternal(pkg)) {
9544                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9545                                }
9546                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9547                            }
9548                        }
9549                    } else {
9550                        // Invalid install. Return error code
9551                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9552                    }
9553                }
9554            }
9555            // All the special cases have been taken care of.
9556            // Return result based on recommended install location.
9557            if (onSd) {
9558                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9559            }
9560            return pkgLite.recommendedInstallLocation;
9561        }
9562
9563        /*
9564         * Invoke remote method to get package information and install
9565         * location values. Override install location based on default
9566         * policy if needed and then create install arguments based
9567         * on the install location.
9568         */
9569        public void handleStartCopy() throws RemoteException {
9570            int ret = PackageManager.INSTALL_SUCCEEDED;
9571
9572            // If we're already staged, we've firmly committed to an install location
9573            if (origin.staged) {
9574                if (origin.file != null) {
9575                    installFlags |= PackageManager.INSTALL_INTERNAL;
9576                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9577                } else if (origin.cid != null) {
9578                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9579                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9580                } else {
9581                    throw new IllegalStateException("Invalid stage location");
9582                }
9583            }
9584
9585            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9586            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9587
9588            PackageInfoLite pkgLite = null;
9589
9590            if (onInt && onSd) {
9591                // Check if both bits are set.
9592                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9593                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9594            } else {
9595                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9596                        packageAbiOverride);
9597
9598                /*
9599                 * If we have too little free space, try to free cache
9600                 * before giving up.
9601                 */
9602                if (!origin.staged && pkgLite.recommendedInstallLocation
9603                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9604                    // TODO: focus freeing disk space on the target device
9605                    final StorageManager storage = StorageManager.from(mContext);
9606                    final long lowThreshold = storage.getStorageLowBytes(
9607                            Environment.getDataDirectory());
9608
9609                    final long sizeBytes = mContainerService.calculateInstalledSize(
9610                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9611
9612                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
9613                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9614                                installFlags, packageAbiOverride);
9615                    }
9616
9617                    /*
9618                     * The cache free must have deleted the file we
9619                     * downloaded to install.
9620                     *
9621                     * TODO: fix the "freeCache" call to not delete
9622                     *       the file we care about.
9623                     */
9624                    if (pkgLite.recommendedInstallLocation
9625                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9626                        pkgLite.recommendedInstallLocation
9627                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9628                    }
9629                }
9630            }
9631
9632            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9633                int loc = pkgLite.recommendedInstallLocation;
9634                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9635                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9636                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9637                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9638                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9639                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9640                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9641                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9642                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9643                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9644                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9645                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9646                } else {
9647                    // Override with defaults if needed.
9648                    loc = installLocationPolicy(pkgLite);
9649                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9650                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9651                    } else if (!onSd && !onInt) {
9652                        // Override install location with flags
9653                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9654                            // Set the flag to install on external media.
9655                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9656                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9657                        } else {
9658                            // Make sure the flag for installing on external
9659                            // media is unset
9660                            installFlags |= PackageManager.INSTALL_INTERNAL;
9661                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9662                        }
9663                    }
9664                }
9665            }
9666
9667            final InstallArgs args = createInstallArgs(this);
9668            mArgs = args;
9669
9670            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9671                 /*
9672                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9673                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9674                 */
9675                int userIdentifier = getUser().getIdentifier();
9676                if (userIdentifier == UserHandle.USER_ALL
9677                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9678                    userIdentifier = UserHandle.USER_OWNER;
9679                }
9680
9681                /*
9682                 * Determine if we have any installed package verifiers. If we
9683                 * do, then we'll defer to them to verify the packages.
9684                 */
9685                final int requiredUid = mRequiredVerifierPackage == null ? -1
9686                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9687                if (!origin.existing && requiredUid != -1
9688                        && isVerificationEnabled(userIdentifier, installFlags)) {
9689                    final Intent verification = new Intent(
9690                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9691                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9692                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9693                            PACKAGE_MIME_TYPE);
9694                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9695
9696                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9697                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9698                            0 /* TODO: Which userId? */);
9699
9700                    if (DEBUG_VERIFY) {
9701                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9702                                + verification.toString() + " with " + pkgLite.verifiers.length
9703                                + " optional verifiers");
9704                    }
9705
9706                    final int verificationId = mPendingVerificationToken++;
9707
9708                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9709
9710                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9711                            installerPackageName);
9712
9713                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9714                            installFlags);
9715
9716                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9717                            pkgLite.packageName);
9718
9719                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9720                            pkgLite.versionCode);
9721
9722                    if (verificationParams != null) {
9723                        if (verificationParams.getVerificationURI() != null) {
9724                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9725                                 verificationParams.getVerificationURI());
9726                        }
9727                        if (verificationParams.getOriginatingURI() != null) {
9728                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9729                                  verificationParams.getOriginatingURI());
9730                        }
9731                        if (verificationParams.getReferrer() != null) {
9732                            verification.putExtra(Intent.EXTRA_REFERRER,
9733                                  verificationParams.getReferrer());
9734                        }
9735                        if (verificationParams.getOriginatingUid() >= 0) {
9736                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9737                                  verificationParams.getOriginatingUid());
9738                        }
9739                        if (verificationParams.getInstallerUid() >= 0) {
9740                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9741                                  verificationParams.getInstallerUid());
9742                        }
9743                    }
9744
9745                    final PackageVerificationState verificationState = new PackageVerificationState(
9746                            requiredUid, args);
9747
9748                    mPendingVerification.append(verificationId, verificationState);
9749
9750                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9751                            receivers, verificationState);
9752
9753                    /*
9754                     * If any sufficient verifiers were listed in the package
9755                     * manifest, attempt to ask them.
9756                     */
9757                    if (sufficientVerifiers != null) {
9758                        final int N = sufficientVerifiers.size();
9759                        if (N == 0) {
9760                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9761                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9762                        } else {
9763                            for (int i = 0; i < N; i++) {
9764                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9765
9766                                final Intent sufficientIntent = new Intent(verification);
9767                                sufficientIntent.setComponent(verifierComponent);
9768
9769                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9770                            }
9771                        }
9772                    }
9773
9774                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9775                            mRequiredVerifierPackage, receivers);
9776                    if (ret == PackageManager.INSTALL_SUCCEEDED
9777                            && mRequiredVerifierPackage != null) {
9778                        /*
9779                         * Send the intent to the required verification agent,
9780                         * but only start the verification timeout after the
9781                         * target BroadcastReceivers have run.
9782                         */
9783                        verification.setComponent(requiredVerifierComponent);
9784                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9785                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9786                                new BroadcastReceiver() {
9787                                    @Override
9788                                    public void onReceive(Context context, Intent intent) {
9789                                        final Message msg = mHandler
9790                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9791                                        msg.arg1 = verificationId;
9792                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9793                                    }
9794                                }, null, 0, null, null);
9795
9796                        /*
9797                         * We don't want the copy to proceed until verification
9798                         * succeeds, so null out this field.
9799                         */
9800                        mArgs = null;
9801                    }
9802                } else {
9803                    /*
9804                     * No package verification is enabled, so immediately start
9805                     * the remote call to initiate copy using temporary file.
9806                     */
9807                    ret = args.copyApk(mContainerService, true);
9808                }
9809            }
9810
9811            mRet = ret;
9812        }
9813
9814        @Override
9815        void handleReturnCode() {
9816            // If mArgs is null, then MCS couldn't be reached. When it
9817            // reconnects, it will try again to install. At that point, this
9818            // will succeed.
9819            if (mArgs != null) {
9820                processPendingInstall(mArgs, mRet);
9821            }
9822        }
9823
9824        @Override
9825        void handleServiceError() {
9826            mArgs = createInstallArgs(this);
9827            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9828        }
9829
9830        public boolean isForwardLocked() {
9831            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9832        }
9833    }
9834
9835    /**
9836     * Used during creation of InstallArgs
9837     *
9838     * @param installFlags package installation flags
9839     * @return true if should be installed on external storage
9840     */
9841    private static boolean installOnExternalAsec(int installFlags) {
9842        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9843            return false;
9844        }
9845        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9846            return true;
9847        }
9848        return false;
9849    }
9850
9851    /**
9852     * Used during creation of InstallArgs
9853     *
9854     * @param installFlags package installation flags
9855     * @return true if should be installed as forward locked
9856     */
9857    private static boolean installForwardLocked(int installFlags) {
9858        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9859    }
9860
9861    private InstallArgs createInstallArgs(InstallParams params) {
9862        if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
9863            return new AsecInstallArgs(params);
9864        } else {
9865            return new FileInstallArgs(params);
9866        }
9867    }
9868
9869    /**
9870     * Create args that describe an existing installed package. Typically used
9871     * when cleaning up old installs, or used as a move source.
9872     */
9873    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9874            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9875        final boolean isInAsec;
9876        if (installOnExternalAsec(installFlags)) {
9877            /* Apps on SD card are always in ASEC containers. */
9878            isInAsec = true;
9879        } else if (installForwardLocked(installFlags)
9880                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9881            /*
9882             * Forward-locked apps are only in ASEC containers if they're the
9883             * new style
9884             */
9885            isInAsec = true;
9886        } else {
9887            isInAsec = false;
9888        }
9889
9890        if (isInAsec) {
9891            return new AsecInstallArgs(codePath, instructionSets,
9892                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
9893        } else {
9894            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9895                    instructionSets);
9896        }
9897    }
9898
9899    static abstract class InstallArgs {
9900        /** @see InstallParams#origin */
9901        final OriginInfo origin;
9902
9903        final IPackageInstallObserver2 observer;
9904        // Always refers to PackageManager flags only
9905        final int installFlags;
9906        final String installerPackageName;
9907        final String volumeUuid;
9908        final ManifestDigest manifestDigest;
9909        final UserHandle user;
9910        final String abiOverride;
9911
9912        // The list of instruction sets supported by this app. This is currently
9913        // only used during the rmdex() phase to clean up resources. We can get rid of this
9914        // if we move dex files under the common app path.
9915        /* nullable */ String[] instructionSets;
9916
9917        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9918                String installerPackageName, String volumeUuid, ManifestDigest manifestDigest,
9919                UserHandle user, String[] instructionSets, String abiOverride) {
9920            this.origin = origin;
9921            this.installFlags = installFlags;
9922            this.observer = observer;
9923            this.installerPackageName = installerPackageName;
9924            this.volumeUuid = volumeUuid;
9925            this.manifestDigest = manifestDigest;
9926            this.user = user;
9927            this.instructionSets = instructionSets;
9928            this.abiOverride = abiOverride;
9929        }
9930
9931        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9932        abstract int doPreInstall(int status);
9933
9934        /**
9935         * Rename package into final resting place. All paths on the given
9936         * scanned package should be updated to reflect the rename.
9937         */
9938        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9939        abstract int doPostInstall(int status, int uid);
9940
9941        /** @see PackageSettingBase#codePathString */
9942        abstract String getCodePath();
9943        /** @see PackageSettingBase#resourcePathString */
9944        abstract String getResourcePath();
9945        abstract String getLegacyNativeLibraryPath();
9946
9947        // Need installer lock especially for dex file removal.
9948        abstract void cleanUpResourcesLI();
9949        abstract boolean doPostDeleteLI(boolean delete);
9950        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9951
9952        /**
9953         * Called before the source arguments are copied. This is used mostly
9954         * for MoveParams when it needs to read the source file to put it in the
9955         * destination.
9956         */
9957        int doPreCopy() {
9958            return PackageManager.INSTALL_SUCCEEDED;
9959        }
9960
9961        /**
9962         * Called after the source arguments are copied. This is used mostly for
9963         * MoveParams when it needs to read the source file to put it in the
9964         * destination.
9965         *
9966         * @return
9967         */
9968        int doPostCopy(int uid) {
9969            return PackageManager.INSTALL_SUCCEEDED;
9970        }
9971
9972        protected boolean isFwdLocked() {
9973            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9974        }
9975
9976        protected boolean isExternalAsec() {
9977            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9978        }
9979
9980        UserHandle getUser() {
9981            return user;
9982        }
9983    }
9984
9985    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
9986        if (!allCodePaths.isEmpty()) {
9987            if (instructionSets == null) {
9988                throw new IllegalStateException("instructionSet == null");
9989            }
9990            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9991            for (String codePath : allCodePaths) {
9992                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9993                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9994                    if (retCode < 0) {
9995                        Slog.w(TAG, "Couldn't remove dex file for package: "
9996                                + " at location " + codePath + ", retcode=" + retCode);
9997                        // we don't consider this to be a failure of the core package deletion
9998                    }
9999                }
10000            }
10001        }
10002    }
10003
10004    /**
10005     * Logic to handle installation of non-ASEC applications, including copying
10006     * and renaming logic.
10007     */
10008    class FileInstallArgs extends InstallArgs {
10009        private File codeFile;
10010        private File resourceFile;
10011        private File legacyNativeLibraryPath;
10012
10013        // Example topology:
10014        // /data/app/com.example/base.apk
10015        // /data/app/com.example/split_foo.apk
10016        // /data/app/com.example/lib/arm/libfoo.so
10017        // /data/app/com.example/lib/arm64/libfoo.so
10018        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10019
10020        /** New install */
10021        FileInstallArgs(InstallParams params) {
10022            super(params.origin, params.observer, params.installFlags,
10023                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10024                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10025            if (isFwdLocked()) {
10026                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10027            }
10028        }
10029
10030        /** Existing install */
10031        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
10032                String[] instructionSets) {
10033            super(OriginInfo.fromNothing(), null, 0, null, null, null, null, instructionSets, null);
10034            this.codeFile = (codePath != null) ? new File(codePath) : null;
10035            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10036            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
10037                    new File(legacyNativeLibraryPath) : null;
10038        }
10039
10040        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
10041            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
10042                    isFwdLocked(), abiOverride);
10043
10044            final StorageManager storage = StorageManager.from(mContext);
10045            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
10046        }
10047
10048        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10049            if (origin.staged) {
10050                Slog.d(TAG, origin.file + " already staged; skipping copy");
10051                codeFile = origin.file;
10052                resourceFile = origin.file;
10053                return PackageManager.INSTALL_SUCCEEDED;
10054            }
10055
10056            try {
10057                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10058                codeFile = tempDir;
10059                resourceFile = tempDir;
10060            } catch (IOException e) {
10061                Slog.w(TAG, "Failed to create copy file: " + e);
10062                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10063            }
10064
10065            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10066                @Override
10067                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10068                    if (!FileUtils.isValidExtFilename(name)) {
10069                        throw new IllegalArgumentException("Invalid filename: " + name);
10070                    }
10071                    try {
10072                        final File file = new File(codeFile, name);
10073                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10074                                O_RDWR | O_CREAT, 0644);
10075                        Os.chmod(file.getAbsolutePath(), 0644);
10076                        return new ParcelFileDescriptor(fd);
10077                    } catch (ErrnoException e) {
10078                        throw new RemoteException("Failed to open: " + e.getMessage());
10079                    }
10080                }
10081            };
10082
10083            int ret = PackageManager.INSTALL_SUCCEEDED;
10084            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10085            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10086                Slog.e(TAG, "Failed to copy package");
10087                return ret;
10088            }
10089
10090            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10091            NativeLibraryHelper.Handle handle = null;
10092            try {
10093                handle = NativeLibraryHelper.Handle.create(codeFile);
10094                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10095                        abiOverride);
10096            } catch (IOException e) {
10097                Slog.e(TAG, "Copying native libraries failed", e);
10098                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10099            } finally {
10100                IoUtils.closeQuietly(handle);
10101            }
10102
10103            return ret;
10104        }
10105
10106        int doPreInstall(int status) {
10107            if (status != PackageManager.INSTALL_SUCCEEDED) {
10108                cleanUp();
10109            }
10110            return status;
10111        }
10112
10113        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10114            if (status != PackageManager.INSTALL_SUCCEEDED) {
10115                cleanUp();
10116                return false;
10117            } else {
10118                final File targetDir = codeFile.getParentFile();
10119                final File beforeCodeFile = codeFile;
10120                final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10121
10122                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10123                try {
10124                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10125                } catch (ErrnoException e) {
10126                    Slog.d(TAG, "Failed to rename", e);
10127                    return false;
10128                }
10129
10130                if (!SELinux.restoreconRecursive(afterCodeFile)) {
10131                    Slog.d(TAG, "Failed to restorecon");
10132                    return false;
10133                }
10134
10135                // Reflect the rename internally
10136                codeFile = afterCodeFile;
10137                resourceFile = afterCodeFile;
10138
10139                // Reflect the rename in scanned details
10140                pkg.codePath = afterCodeFile.getAbsolutePath();
10141                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10142                        pkg.baseCodePath);
10143                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10144                        pkg.splitCodePaths);
10145
10146                // Reflect the rename in app info
10147                pkg.applicationInfo.setCodePath(pkg.codePath);
10148                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10149                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10150                pkg.applicationInfo.setResourcePath(pkg.codePath);
10151                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10152                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10153
10154                return true;
10155            }
10156        }
10157
10158        int doPostInstall(int status, int uid) {
10159            if (status != PackageManager.INSTALL_SUCCEEDED) {
10160                cleanUp();
10161            }
10162            return status;
10163        }
10164
10165        @Override
10166        String getCodePath() {
10167            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10168        }
10169
10170        @Override
10171        String getResourcePath() {
10172            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10173        }
10174
10175        @Override
10176        String getLegacyNativeLibraryPath() {
10177            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
10178        }
10179
10180        private boolean cleanUp() {
10181            if (codeFile == null || !codeFile.exists()) {
10182                return false;
10183            }
10184
10185            if (codeFile.isDirectory()) {
10186                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10187            } else {
10188                codeFile.delete();
10189            }
10190
10191            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10192                resourceFile.delete();
10193            }
10194
10195            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
10196                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
10197                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
10198                }
10199                legacyNativeLibraryPath.delete();
10200            }
10201
10202            return true;
10203        }
10204
10205        void cleanUpResourcesLI() {
10206            // Try enumerating all code paths before deleting
10207            List<String> allCodePaths = Collections.EMPTY_LIST;
10208            if (codeFile != null && codeFile.exists()) {
10209                try {
10210                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10211                    allCodePaths = pkg.getAllCodePaths();
10212                } catch (PackageParserException e) {
10213                    // Ignored; we tried our best
10214                }
10215            }
10216
10217            cleanUp();
10218            removeDexFiles(allCodePaths, instructionSets);
10219        }
10220
10221        boolean doPostDeleteLI(boolean delete) {
10222            // XXX err, shouldn't we respect the delete flag?
10223            cleanUpResourcesLI();
10224            return true;
10225        }
10226    }
10227
10228    private boolean isAsecExternal(String cid) {
10229        final String asecPath = PackageHelper.getSdFilesystem(cid);
10230        return !asecPath.startsWith(mAsecInternalPath);
10231    }
10232
10233    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10234            PackageManagerException {
10235        if (copyRet < 0) {
10236            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10237                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10238                throw new PackageManagerException(copyRet, message);
10239            }
10240        }
10241    }
10242
10243    /**
10244     * Extract the MountService "container ID" from the full code path of an
10245     * .apk.
10246     */
10247    static String cidFromCodePath(String fullCodePath) {
10248        int eidx = fullCodePath.lastIndexOf("/");
10249        String subStr1 = fullCodePath.substring(0, eidx);
10250        int sidx = subStr1.lastIndexOf("/");
10251        return subStr1.substring(sidx+1, eidx);
10252    }
10253
10254    /**
10255     * Logic to handle installation of ASEC applications, including copying and
10256     * renaming logic.
10257     */
10258    class AsecInstallArgs extends InstallArgs {
10259        static final String RES_FILE_NAME = "pkg.apk";
10260        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10261
10262        String cid;
10263        String packagePath;
10264        String resourcePath;
10265        String legacyNativeLibraryDir;
10266
10267        /** New install */
10268        AsecInstallArgs(InstallParams params) {
10269            super(params.origin, params.observer, params.installFlags,
10270                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10271                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10272        }
10273
10274        /** Existing install */
10275        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10276                        boolean isExternal, boolean isForwardLocked) {
10277            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
10278                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10279                    instructionSets, null);
10280            // Hackily pretend we're still looking at a full code path
10281            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10282                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10283            }
10284
10285            // Extract cid from fullCodePath
10286            int eidx = fullCodePath.lastIndexOf("/");
10287            String subStr1 = fullCodePath.substring(0, eidx);
10288            int sidx = subStr1.lastIndexOf("/");
10289            cid = subStr1.substring(sidx+1, eidx);
10290            setMountPath(subStr1);
10291        }
10292
10293        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10294            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10295                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10296                    instructionSets, null);
10297            this.cid = cid;
10298            setMountPath(PackageHelper.getSdDir(cid));
10299        }
10300
10301        void createCopyFile() {
10302            cid = mInstallerService.allocateExternalStageCidLegacy();
10303        }
10304
10305        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
10306            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
10307                    abiOverride);
10308
10309            final File target;
10310            if (isExternalAsec()) {
10311                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
10312            } else {
10313                target = Environment.getDataDirectory();
10314            }
10315
10316            final StorageManager storage = StorageManager.from(mContext);
10317            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
10318        }
10319
10320        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10321            if (origin.staged) {
10322                Slog.d(TAG, origin.cid + " already staged; skipping copy");
10323                cid = origin.cid;
10324                setMountPath(PackageHelper.getSdDir(cid));
10325                return PackageManager.INSTALL_SUCCEEDED;
10326            }
10327
10328            if (temp) {
10329                createCopyFile();
10330            } else {
10331                /*
10332                 * Pre-emptively destroy the container since it's destroyed if
10333                 * copying fails due to it existing anyway.
10334                 */
10335                PackageHelper.destroySdDir(cid);
10336            }
10337
10338            final String newMountPath = imcs.copyPackageToContainer(
10339                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10340                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10341
10342            if (newMountPath != null) {
10343                setMountPath(newMountPath);
10344                return PackageManager.INSTALL_SUCCEEDED;
10345            } else {
10346                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10347            }
10348        }
10349
10350        @Override
10351        String getCodePath() {
10352            return packagePath;
10353        }
10354
10355        @Override
10356        String getResourcePath() {
10357            return resourcePath;
10358        }
10359
10360        @Override
10361        String getLegacyNativeLibraryPath() {
10362            return legacyNativeLibraryDir;
10363        }
10364
10365        int doPreInstall(int status) {
10366            if (status != PackageManager.INSTALL_SUCCEEDED) {
10367                // Destroy container
10368                PackageHelper.destroySdDir(cid);
10369            } else {
10370                boolean mounted = PackageHelper.isContainerMounted(cid);
10371                if (!mounted) {
10372                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10373                            Process.SYSTEM_UID);
10374                    if (newMountPath != null) {
10375                        setMountPath(newMountPath);
10376                    } else {
10377                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10378                    }
10379                }
10380            }
10381            return status;
10382        }
10383
10384        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10385            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10386            String newMountPath = null;
10387            if (PackageHelper.isContainerMounted(cid)) {
10388                // Unmount the container
10389                if (!PackageHelper.unMountSdDir(cid)) {
10390                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10391                    return false;
10392                }
10393            }
10394            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10395                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10396                        " which might be stale. Will try to clean up.");
10397                // Clean up the stale container and proceed to recreate.
10398                if (!PackageHelper.destroySdDir(newCacheId)) {
10399                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10400                    return false;
10401                }
10402                // Successfully cleaned up stale container. Try to rename again.
10403                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10404                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10405                            + " inspite of cleaning it up.");
10406                    return false;
10407                }
10408            }
10409            if (!PackageHelper.isContainerMounted(newCacheId)) {
10410                Slog.w(TAG, "Mounting container " + newCacheId);
10411                newMountPath = PackageHelper.mountSdDir(newCacheId,
10412                        getEncryptKey(), Process.SYSTEM_UID);
10413            } else {
10414                newMountPath = PackageHelper.getSdDir(newCacheId);
10415            }
10416            if (newMountPath == null) {
10417                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10418                return false;
10419            }
10420            Log.i(TAG, "Succesfully renamed " + cid +
10421                    " to " + newCacheId +
10422                    " at new path: " + newMountPath);
10423            cid = newCacheId;
10424
10425            final File beforeCodeFile = new File(packagePath);
10426            setMountPath(newMountPath);
10427            final File afterCodeFile = new File(packagePath);
10428
10429            // Reflect the rename in scanned details
10430            pkg.codePath = afterCodeFile.getAbsolutePath();
10431            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10432                    pkg.baseCodePath);
10433            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10434                    pkg.splitCodePaths);
10435
10436            // Reflect the rename in app info
10437            pkg.applicationInfo.setCodePath(pkg.codePath);
10438            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10439            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10440            pkg.applicationInfo.setResourcePath(pkg.codePath);
10441            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10442            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10443
10444            return true;
10445        }
10446
10447        private void setMountPath(String mountPath) {
10448            final File mountFile = new File(mountPath);
10449
10450            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10451            if (monolithicFile.exists()) {
10452                packagePath = monolithicFile.getAbsolutePath();
10453                if (isFwdLocked()) {
10454                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10455                } else {
10456                    resourcePath = packagePath;
10457                }
10458            } else {
10459                packagePath = mountFile.getAbsolutePath();
10460                resourcePath = packagePath;
10461            }
10462
10463            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
10464        }
10465
10466        int doPostInstall(int status, int uid) {
10467            if (status != PackageManager.INSTALL_SUCCEEDED) {
10468                cleanUp();
10469            } else {
10470                final int groupOwner;
10471                final String protectedFile;
10472                if (isFwdLocked()) {
10473                    groupOwner = UserHandle.getSharedAppGid(uid);
10474                    protectedFile = RES_FILE_NAME;
10475                } else {
10476                    groupOwner = -1;
10477                    protectedFile = null;
10478                }
10479
10480                if (uid < Process.FIRST_APPLICATION_UID
10481                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10482                    Slog.e(TAG, "Failed to finalize " + cid);
10483                    PackageHelper.destroySdDir(cid);
10484                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10485                }
10486
10487                boolean mounted = PackageHelper.isContainerMounted(cid);
10488                if (!mounted) {
10489                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10490                }
10491            }
10492            return status;
10493        }
10494
10495        private void cleanUp() {
10496            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10497
10498            // Destroy secure container
10499            PackageHelper.destroySdDir(cid);
10500        }
10501
10502        private List<String> getAllCodePaths() {
10503            final File codeFile = new File(getCodePath());
10504            if (codeFile != null && codeFile.exists()) {
10505                try {
10506                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10507                    return pkg.getAllCodePaths();
10508                } catch (PackageParserException e) {
10509                    // Ignored; we tried our best
10510                }
10511            }
10512            return Collections.EMPTY_LIST;
10513        }
10514
10515        void cleanUpResourcesLI() {
10516            // Enumerate all code paths before deleting
10517            cleanUpResourcesLI(getAllCodePaths());
10518        }
10519
10520        private void cleanUpResourcesLI(List<String> allCodePaths) {
10521            cleanUp();
10522            removeDexFiles(allCodePaths, instructionSets);
10523        }
10524
10525
10526
10527        String getPackageName() {
10528            return getAsecPackageName(cid);
10529        }
10530
10531        boolean doPostDeleteLI(boolean delete) {
10532            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10533            final List<String> allCodePaths = getAllCodePaths();
10534            boolean mounted = PackageHelper.isContainerMounted(cid);
10535            if (mounted) {
10536                // Unmount first
10537                if (PackageHelper.unMountSdDir(cid)) {
10538                    mounted = false;
10539                }
10540            }
10541            if (!mounted && delete) {
10542                cleanUpResourcesLI(allCodePaths);
10543            }
10544            return !mounted;
10545        }
10546
10547        @Override
10548        int doPreCopy() {
10549            if (isFwdLocked()) {
10550                if (!PackageHelper.fixSdPermissions(cid,
10551                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10552                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10553                }
10554            }
10555
10556            return PackageManager.INSTALL_SUCCEEDED;
10557        }
10558
10559        @Override
10560        int doPostCopy(int uid) {
10561            if (isFwdLocked()) {
10562                if (uid < Process.FIRST_APPLICATION_UID
10563                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10564                                RES_FILE_NAME)) {
10565                    Slog.e(TAG, "Failed to finalize " + cid);
10566                    PackageHelper.destroySdDir(cid);
10567                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10568                }
10569            }
10570
10571            return PackageManager.INSTALL_SUCCEEDED;
10572        }
10573    }
10574
10575    static String getAsecPackageName(String packageCid) {
10576        int idx = packageCid.lastIndexOf("-");
10577        if (idx == -1) {
10578            return packageCid;
10579        }
10580        return packageCid.substring(0, idx);
10581    }
10582
10583    // Utility method used to create code paths based on package name and available index.
10584    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
10585        String idxStr = "";
10586        int idx = 1;
10587        // Fall back to default value of idx=1 if prefix is not
10588        // part of oldCodePath
10589        if (oldCodePath != null) {
10590            String subStr = oldCodePath;
10591            // Drop the suffix right away
10592            if (suffix != null && subStr.endsWith(suffix)) {
10593                subStr = subStr.substring(0, subStr.length() - suffix.length());
10594            }
10595            // If oldCodePath already contains prefix find out the
10596            // ending index to either increment or decrement.
10597            int sidx = subStr.lastIndexOf(prefix);
10598            if (sidx != -1) {
10599                subStr = subStr.substring(sidx + prefix.length());
10600                if (subStr != null) {
10601                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10602                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10603                    }
10604                    try {
10605                        idx = Integer.parseInt(subStr);
10606                        if (idx <= 1) {
10607                            idx++;
10608                        } else {
10609                            idx--;
10610                        }
10611                    } catch(NumberFormatException e) {
10612                    }
10613                }
10614            }
10615        }
10616        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10617        return prefix + idxStr;
10618    }
10619
10620    private File getNextCodePath(File targetDir, String packageName) {
10621        int suffix = 1;
10622        File result;
10623        do {
10624            result = new File(targetDir, packageName + "-" + suffix);
10625            suffix++;
10626        } while (result.exists());
10627        return result;
10628    }
10629
10630    // Utility method that returns the relative package path with respect
10631    // to the installation directory. Like say for /data/data/com.test-1.apk
10632    // string com.test-1 is returned.
10633    static String deriveCodePathName(String codePath) {
10634        if (codePath == null) {
10635            return null;
10636        }
10637        final File codeFile = new File(codePath);
10638        final String name = codeFile.getName();
10639        if (codeFile.isDirectory()) {
10640            return name;
10641        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10642            final int lastDot = name.lastIndexOf('.');
10643            return name.substring(0, lastDot);
10644        } else {
10645            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10646            return null;
10647        }
10648    }
10649
10650    class PackageInstalledInfo {
10651        String name;
10652        int uid;
10653        // The set of users that originally had this package installed.
10654        int[] origUsers;
10655        // The set of users that now have this package installed.
10656        int[] newUsers;
10657        PackageParser.Package pkg;
10658        int returnCode;
10659        String returnMsg;
10660        PackageRemovedInfo removedInfo;
10661
10662        public void setError(int code, String msg) {
10663            returnCode = code;
10664            returnMsg = msg;
10665            Slog.w(TAG, msg);
10666        }
10667
10668        public void setError(String msg, PackageParserException e) {
10669            returnCode = e.error;
10670            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10671            Slog.w(TAG, msg, e);
10672        }
10673
10674        public void setError(String msg, PackageManagerException e) {
10675            returnCode = e.error;
10676            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10677            Slog.w(TAG, msg, e);
10678        }
10679
10680        // In some error cases we want to convey more info back to the observer
10681        String origPackage;
10682        String origPermission;
10683    }
10684
10685    /*
10686     * Install a non-existing package.
10687     */
10688    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
10689            UserHandle user, String installerPackageName, String volumeUuid,
10690            PackageInstalledInfo res) {
10691        // Remember this for later, in case we need to rollback this install
10692        String pkgName = pkg.packageName;
10693
10694        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10695        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
10696        synchronized(mPackages) {
10697            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10698                // A package with the same name is already installed, though
10699                // it has been renamed to an older name.  The package we
10700                // are trying to install should be installed as an update to
10701                // the existing one, but that has not been requested, so bail.
10702                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10703                        + " without first uninstalling package running as "
10704                        + mSettings.mRenamedPackages.get(pkgName));
10705                return;
10706            }
10707            if (mPackages.containsKey(pkgName)) {
10708                // Don't allow installation over an existing package with the same name.
10709                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10710                        + " without first uninstalling.");
10711                return;
10712            }
10713        }
10714
10715        try {
10716            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10717                    System.currentTimeMillis(), user);
10718
10719            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
10720            // delete the partially installed application. the data directory will have to be
10721            // restored if it was already existing
10722            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10723                // remove package from internal structures.  Note that we want deletePackageX to
10724                // delete the package data and cache directories that it created in
10725                // scanPackageLocked, unless those directories existed before we even tried to
10726                // install.
10727                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10728                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10729                                res.removedInfo, true);
10730            }
10731
10732        } catch (PackageManagerException e) {
10733            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10734        }
10735    }
10736
10737    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10738        // Upgrade keysets are being used.  Determine if new package has a superset of the
10739        // required keys.
10740        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10741        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10742        for (int i = 0; i < upgradeKeySets.length; i++) {
10743            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10744            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10745                return true;
10746            }
10747        }
10748        return false;
10749    }
10750
10751    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
10752            UserHandle user, String installerPackageName, String volumeUuid,
10753            PackageInstalledInfo res) {
10754        PackageParser.Package oldPackage;
10755        String pkgName = pkg.packageName;
10756        int[] allUsers;
10757        boolean[] perUserInstalled;
10758
10759        // First find the old package info and check signatures
10760        synchronized(mPackages) {
10761            oldPackage = mPackages.get(pkgName);
10762            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10763            PackageSetting ps = mSettings.mPackages.get(pkgName);
10764            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10765                // default to original signature matching
10766                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10767                    != PackageManager.SIGNATURE_MATCH) {
10768                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10769                            "New package has a different signature: " + pkgName);
10770                    return;
10771                }
10772            } else {
10773                if(!checkUpgradeKeySetLP(ps, pkg)) {
10774                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10775                            "New package not signed by keys specified by upgrade-keysets: "
10776                            + pkgName);
10777                    return;
10778                }
10779            }
10780
10781            // In case of rollback, remember per-user/profile install state
10782            allUsers = sUserManager.getUserIds();
10783            perUserInstalled = new boolean[allUsers.length];
10784            for (int i = 0; i < allUsers.length; i++) {
10785                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10786            }
10787        }
10788
10789        boolean sysPkg = (isSystemApp(oldPackage));
10790        if (sysPkg) {
10791            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10792                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
10793        } else {
10794            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10795                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
10796        }
10797    }
10798
10799    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10800            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10801            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
10802            String volumeUuid, PackageInstalledInfo res) {
10803        String pkgName = deletedPackage.packageName;
10804        boolean deletedPkg = true;
10805        boolean updatedSettings = false;
10806
10807        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10808                + deletedPackage);
10809        long origUpdateTime;
10810        if (pkg.mExtras != null) {
10811            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10812        } else {
10813            origUpdateTime = 0;
10814        }
10815
10816        // First delete the existing package while retaining the data directory
10817        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10818                res.removedInfo, true)) {
10819            // If the existing package wasn't successfully deleted
10820            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10821            deletedPkg = false;
10822        } else {
10823            // Successfully deleted the old package; proceed with replace.
10824
10825            // If deleted package lived in a container, give users a chance to
10826            // relinquish resources before killing.
10827            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
10828                if (DEBUG_INSTALL) {
10829                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10830                }
10831                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10832                final ArrayList<String> pkgList = new ArrayList<String>(1);
10833                pkgList.add(deletedPackage.applicationInfo.packageName);
10834                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10835            }
10836
10837            deleteCodeCacheDirsLI(pkgName);
10838            try {
10839                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10840                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10841                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
10842                        perUserInstalled, res, user);
10843                updatedSettings = true;
10844            } catch (PackageManagerException e) {
10845                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10846            }
10847        }
10848
10849        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10850            // remove package from internal structures.  Note that we want deletePackageX to
10851            // delete the package data and cache directories that it created in
10852            // scanPackageLocked, unless those directories existed before we even tried to
10853            // install.
10854            if(updatedSettings) {
10855                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10856                deletePackageLI(
10857                        pkgName, null, true, allUsers, perUserInstalled,
10858                        PackageManager.DELETE_KEEP_DATA,
10859                                res.removedInfo, true);
10860            }
10861            // Since we failed to install the new package we need to restore the old
10862            // package that we deleted.
10863            if (deletedPkg) {
10864                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10865                File restoreFile = new File(deletedPackage.codePath);
10866                // Parse old package
10867                boolean oldExternal = isExternal(deletedPackage);
10868                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10869                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10870                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
10871                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10872                try {
10873                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10874                } catch (PackageManagerException e) {
10875                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10876                            + e.getMessage());
10877                    return;
10878                }
10879                // Restore of old package succeeded. Update permissions.
10880                // writer
10881                synchronized (mPackages) {
10882                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10883                            UPDATE_PERMISSIONS_ALL);
10884                    // can downgrade to reader
10885                    mSettings.writeLPr();
10886                }
10887                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10888            }
10889        }
10890    }
10891
10892    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10893            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10894            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
10895            String volumeUuid, PackageInstalledInfo res) {
10896        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10897                + ", old=" + deletedPackage);
10898        boolean disabledSystem = false;
10899        boolean updatedSettings = false;
10900        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10901        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
10902                != 0) {
10903            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10904        }
10905        String packageName = deletedPackage.packageName;
10906        if (packageName == null) {
10907            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10908                    "Attempt to delete null packageName.");
10909            return;
10910        }
10911        PackageParser.Package oldPkg;
10912        PackageSetting oldPkgSetting;
10913        // reader
10914        synchronized (mPackages) {
10915            oldPkg = mPackages.get(packageName);
10916            oldPkgSetting = mSettings.mPackages.get(packageName);
10917            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10918                    (oldPkgSetting == null)) {
10919                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10920                        "Couldn't find package:" + packageName + " information");
10921                return;
10922            }
10923        }
10924
10925        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10926
10927        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10928        res.removedInfo.removedPackage = packageName;
10929        // Remove existing system package
10930        removePackageLI(oldPkgSetting, true);
10931        // writer
10932        synchronized (mPackages) {
10933            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10934            if (!disabledSystem && deletedPackage != null) {
10935                // We didn't need to disable the .apk as a current system package,
10936                // which means we are replacing another update that is already
10937                // installed.  We need to make sure to delete the older one's .apk.
10938                res.removedInfo.args = createInstallArgsForExisting(0,
10939                        deletedPackage.applicationInfo.getCodePath(),
10940                        deletedPackage.applicationInfo.getResourcePath(),
10941                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10942                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10943            } else {
10944                res.removedInfo.args = null;
10945            }
10946        }
10947
10948        // Successfully disabled the old package. Now proceed with re-installation
10949        deleteCodeCacheDirsLI(packageName);
10950
10951        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10952        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10953
10954        PackageParser.Package newPackage = null;
10955        try {
10956            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10957            if (newPackage.mExtras != null) {
10958                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10959                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10960                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10961
10962                // is the update attempting to change shared user? that isn't going to work...
10963                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10964                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10965                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10966                            + " to " + newPkgSetting.sharedUser);
10967                    updatedSettings = true;
10968                }
10969            }
10970
10971            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10972                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
10973                        perUserInstalled, res, user);
10974                updatedSettings = true;
10975            }
10976
10977        } catch (PackageManagerException e) {
10978            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10979        }
10980
10981        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10982            // Re installation failed. Restore old information
10983            // Remove new pkg information
10984            if (newPackage != null) {
10985                removeInstalledPackageLI(newPackage, true);
10986            }
10987            // Add back the old system package
10988            try {
10989                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10990            } catch (PackageManagerException e) {
10991                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10992            }
10993            // Restore the old system information in Settings
10994            synchronized (mPackages) {
10995                if (disabledSystem) {
10996                    mSettings.enableSystemPackageLPw(packageName);
10997                }
10998                if (updatedSettings) {
10999                    mSettings.setInstallerPackageName(packageName,
11000                            oldPkgSetting.installerPackageName);
11001                }
11002                mSettings.writeLPr();
11003            }
11004        }
11005    }
11006
11007    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11008            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11009            UserHandle user) {
11010        String pkgName = newPackage.packageName;
11011        synchronized (mPackages) {
11012            //write settings. the installStatus will be incomplete at this stage.
11013            //note that the new package setting would have already been
11014            //added to mPackages. It hasn't been persisted yet.
11015            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11016            mSettings.writeLPr();
11017        }
11018
11019        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11020
11021        synchronized (mPackages) {
11022            updatePermissionsLPw(newPackage.packageName, newPackage,
11023                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11024                            ? UPDATE_PERMISSIONS_ALL : 0));
11025            // For system-bundled packages, we assume that installing an upgraded version
11026            // of the package implies that the user actually wants to run that new code,
11027            // so we enable the package.
11028            PackageSetting ps = mSettings.mPackages.get(pkgName);
11029            if (ps != null) {
11030                if (isSystemApp(newPackage)) {
11031                    // NB: implicit assumption that system package upgrades apply to all users
11032                    if (DEBUG_INSTALL) {
11033                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11034                    }
11035                    if (res.origUsers != null) {
11036                        for (int userHandle : res.origUsers) {
11037                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11038                                    userHandle, installerPackageName);
11039                        }
11040                    }
11041                    // Also convey the prior install/uninstall state
11042                    if (allUsers != null && perUserInstalled != null) {
11043                        for (int i = 0; i < allUsers.length; i++) {
11044                            if (DEBUG_INSTALL) {
11045                                Slog.d(TAG, "    user " + allUsers[i]
11046                                        + " => " + perUserInstalled[i]);
11047                            }
11048                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11049                        }
11050                        // these install state changes will be persisted in the
11051                        // upcoming call to mSettings.writeLPr().
11052                    }
11053                }
11054                // It's implied that when a user requests installation, they want the app to be
11055                // installed and enabled.
11056                int userId = user.getIdentifier();
11057                if (userId != UserHandle.USER_ALL) {
11058                    ps.setInstalled(true, userId);
11059                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11060                }
11061            }
11062            res.name = pkgName;
11063            res.uid = newPackage.applicationInfo.uid;
11064            res.pkg = newPackage;
11065            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11066            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11067            mSettings.setVolumeUuid(pkgName, volumeUuid);
11068            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11069            //to update install status
11070            mSettings.writeLPr();
11071        }
11072    }
11073
11074    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11075        final int installFlags = args.installFlags;
11076        final String installerPackageName = args.installerPackageName;
11077        final String volumeUuid = args.volumeUuid;
11078        final File tmpPackageFile = new File(args.getCodePath());
11079        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11080        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11081                || (args.volumeUuid != null));
11082        boolean replace = false;
11083        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
11084        // Result object to be returned
11085        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11086
11087        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11088        // Retrieve PackageSettings and parse package
11089        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11090                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11091                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11092        PackageParser pp = new PackageParser();
11093        pp.setSeparateProcesses(mSeparateProcesses);
11094        pp.setDisplayMetrics(mMetrics);
11095
11096        final PackageParser.Package pkg;
11097        try {
11098            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11099        } catch (PackageParserException e) {
11100            res.setError("Failed parse during installPackageLI", e);
11101            return;
11102        }
11103
11104        // Mark that we have an install time CPU ABI override.
11105        pkg.cpuAbiOverride = args.abiOverride;
11106
11107        String pkgName = res.name = pkg.packageName;
11108        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11109            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11110                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11111                return;
11112            }
11113        }
11114
11115        try {
11116            pp.collectCertificates(pkg, parseFlags);
11117            pp.collectManifestDigest(pkg);
11118        } catch (PackageParserException e) {
11119            res.setError("Failed collect during installPackageLI", e);
11120            return;
11121        }
11122
11123        /* If the installer passed in a manifest digest, compare it now. */
11124        if (args.manifestDigest != null) {
11125            if (DEBUG_INSTALL) {
11126                final String parsedManifest = pkg.manifestDigest == null ? "null"
11127                        : pkg.manifestDigest.toString();
11128                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11129                        + parsedManifest);
11130            }
11131
11132            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11133                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11134                return;
11135            }
11136        } else if (DEBUG_INSTALL) {
11137            final String parsedManifest = pkg.manifestDigest == null
11138                    ? "null" : pkg.manifestDigest.toString();
11139            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11140        }
11141
11142        // Get rid of all references to package scan path via parser.
11143        pp = null;
11144        String oldCodePath = null;
11145        boolean systemApp = false;
11146        synchronized (mPackages) {
11147            // Check if installing already existing package
11148            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11149                String oldName = mSettings.mRenamedPackages.get(pkgName);
11150                if (pkg.mOriginalPackages != null
11151                        && pkg.mOriginalPackages.contains(oldName)
11152                        && mPackages.containsKey(oldName)) {
11153                    // This package is derived from an original package,
11154                    // and this device has been updating from that original
11155                    // name.  We must continue using the original name, so
11156                    // rename the new package here.
11157                    pkg.setPackageName(oldName);
11158                    pkgName = pkg.packageName;
11159                    replace = true;
11160                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11161                            + oldName + " pkgName=" + pkgName);
11162                } else if (mPackages.containsKey(pkgName)) {
11163                    // This package, under its official name, already exists
11164                    // on the device; we should replace it.
11165                    replace = true;
11166                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11167                }
11168            }
11169
11170            PackageSetting ps = mSettings.mPackages.get(pkgName);
11171            if (ps != null) {
11172                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11173
11174                // Quick sanity check that we're signed correctly if updating;
11175                // we'll check this again later when scanning, but we want to
11176                // bail early here before tripping over redefined permissions.
11177                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11178                    try {
11179                        verifySignaturesLP(ps, pkg);
11180                    } catch (PackageManagerException e) {
11181                        res.setError(e.error, e.getMessage());
11182                        return;
11183                    }
11184                } else {
11185                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11186                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11187                                + pkg.packageName + " upgrade keys do not match the "
11188                                + "previously installed version");
11189                        return;
11190                    }
11191                }
11192
11193                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11194                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11195                    systemApp = (ps.pkg.applicationInfo.flags &
11196                            ApplicationInfo.FLAG_SYSTEM) != 0;
11197                }
11198                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11199            }
11200
11201            // Check whether the newly-scanned package wants to define an already-defined perm
11202            int N = pkg.permissions.size();
11203            for (int i = N-1; i >= 0; i--) {
11204                PackageParser.Permission perm = pkg.permissions.get(i);
11205                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11206                if (bp != null) {
11207                    // If the defining package is signed with our cert, it's okay.  This
11208                    // also includes the "updating the same package" case, of course.
11209                    // "updating same package" could also involve key-rotation.
11210                    final boolean sigsOk;
11211                    if (!bp.sourcePackage.equals(pkg.packageName)
11212                            || !(bp.packageSetting instanceof PackageSetting)
11213                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
11214                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
11215                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11216                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11217                    } else {
11218                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11219                    }
11220                    if (!sigsOk) {
11221                        // If the owning package is the system itself, we log but allow
11222                        // install to proceed; we fail the install on all other permission
11223                        // redefinitions.
11224                        if (!bp.sourcePackage.equals("android")) {
11225                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11226                                    + pkg.packageName + " attempting to redeclare permission "
11227                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11228                            res.origPermission = perm.info.name;
11229                            res.origPackage = bp.sourcePackage;
11230                            return;
11231                        } else {
11232                            Slog.w(TAG, "Package " + pkg.packageName
11233                                    + " attempting to redeclare system permission "
11234                                    + perm.info.name + "; ignoring new declaration");
11235                            pkg.permissions.remove(i);
11236                        }
11237                    }
11238                }
11239            }
11240
11241        }
11242
11243        if (systemApp && onExternal) {
11244            // Disable updates to system apps on sdcard
11245            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11246                    "Cannot install updates to system apps on sdcard");
11247            return;
11248        }
11249
11250        // Run dexopt before old package gets removed, to minimize time when app is not available
11251        int result = mPackageDexOptimizer
11252                .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */,
11253                        false /* defer */, false /* inclDependencies */);
11254        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11255            res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11256            return;
11257        }
11258
11259        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11260            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11261            return;
11262        }
11263
11264        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11265
11266        // Call with SCAN_NO_DEX, since dexopt has already been made
11267        if (replace) {
11268            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING | SCAN_NO_DEX, args.user,
11269                    installerPackageName, volumeUuid, res);
11270        } else {
11271            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES
11272                    | SCAN_NO_DEX, args.user, installerPackageName, volumeUuid, res);
11273        }
11274        synchronized (mPackages) {
11275            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11276            if (ps != null) {
11277                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11278            }
11279        }
11280    }
11281
11282    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11283        if (mIntentFilterVerifierComponent == null) {
11284            Slog.d(TAG, "No IntentFilter verification will not be done as "
11285                    + "there is no IntentFilterVerifier available!");
11286            return;
11287        }
11288
11289        final int verifierUid = getPackageUid(
11290                mIntentFilterVerifierComponent.getPackageName(),
11291                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11292
11293        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11294        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11295        msg.obj = pkg;
11296        msg.arg1 = userId;
11297        msg.arg2 = verifierUid;
11298
11299        mHandler.sendMessage(msg);
11300    }
11301
11302    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11303            PackageParser.Package pkg) {
11304        int size = pkg.activities.size();
11305        if (size == 0) {
11306            Slog.d(TAG, "No activity, so no need to verify any IntentFilter!");
11307            return;
11308        }
11309
11310        final boolean hasDomainURLs = hasDomainURLs(pkg);
11311        if (!hasDomainURLs) {
11312            Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!");
11313            return;
11314        }
11315
11316        Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size
11317                + " Activities needs verification ...");
11318
11319        final int verificationId = mIntentFilterVerificationToken++;
11320        int count = 0;
11321        final String packageName = pkg.packageName;
11322        ArrayList<String> allHosts = new ArrayList<>();
11323
11324        synchronized (mPackages) {
11325            for (PackageParser.Activity a : pkg.activities) {
11326                for (ActivityIntentInfo filter : a.intents) {
11327                    boolean needsFilterVerification = filter.needsVerification();
11328                    if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11329                        Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString());
11330                        mIntentFilterVerifier.addOneIntentFilterVerification(
11331                                verifierUid, userId, verificationId, filter, packageName);
11332                        count++;
11333                    } else if (!needsFilterVerification) {
11334                        Slog.d(TAG, "No verification needed for IntentFilter:"
11335                                + filter.toString());
11336                        if (hasValidDomains(filter)) {
11337                            allHosts.addAll(filter.getHostsList());
11338                        }
11339                    } else {
11340                        Slog.d(TAG, "Verification already done for IntentFilter:"
11341                                + filter.toString());
11342                    }
11343                }
11344            }
11345        }
11346
11347        if (count > 0) {
11348            mIntentFilterVerifier.startVerifications(userId);
11349            Slog.d(TAG, "Started " + count + " IntentFilter verification"
11350                    + (count > 1 ? "s" : "") +  " for userId:" + userId + "!");
11351        } else {
11352            Slog.d(TAG, "No need to start any IntentFilter verification!");
11353            if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw(
11354                    packageName, allHosts) != null) {
11355                scheduleWriteSettingsLocked();
11356            }
11357        }
11358    }
11359
11360    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11361        final ComponentName cn  = filter.activity.getComponentName();
11362        final String packageName = cn.getPackageName();
11363
11364        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11365                packageName);
11366        if (ivi == null) {
11367            return true;
11368        }
11369        int status = ivi.getStatus();
11370        switch (status) {
11371            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11372            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11373                return true;
11374
11375            default:
11376                // Nothing to do
11377                return false;
11378        }
11379    }
11380
11381    private static boolean isMultiArch(PackageSetting ps) {
11382        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11383    }
11384
11385    private static boolean isMultiArch(ApplicationInfo info) {
11386        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11387    }
11388
11389    private static boolean isExternal(PackageParser.Package pkg) {
11390        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11391    }
11392
11393    private static boolean isExternal(PackageSetting ps) {
11394        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11395    }
11396
11397    private static boolean isExternal(ApplicationInfo info) {
11398        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11399    }
11400
11401    private static boolean isSystemApp(PackageParser.Package pkg) {
11402        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11403    }
11404
11405    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11406        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11407    }
11408
11409    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11410        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11411    }
11412
11413    private static boolean isSystemApp(PackageSetting ps) {
11414        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11415    }
11416
11417    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11418        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11419    }
11420
11421    private int packageFlagsToInstallFlags(PackageSetting ps) {
11422        int installFlags = 0;
11423        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11424            // This existing package was an external ASEC install when we have
11425            // the external flag without a UUID
11426            installFlags |= PackageManager.INSTALL_EXTERNAL;
11427        }
11428        if (ps.isForwardLocked()) {
11429            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11430        }
11431        return installFlags;
11432    }
11433
11434    private void deleteTempPackageFiles() {
11435        final FilenameFilter filter = new FilenameFilter() {
11436            public boolean accept(File dir, String name) {
11437                return name.startsWith("vmdl") && name.endsWith(".tmp");
11438            }
11439        };
11440        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11441            file.delete();
11442        }
11443    }
11444
11445    @Override
11446    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11447            int flags) {
11448        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11449                flags);
11450    }
11451
11452    @Override
11453    public void deletePackage(final String packageName,
11454            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11455        mContext.enforceCallingOrSelfPermission(
11456                android.Manifest.permission.DELETE_PACKAGES, null);
11457        final int uid = Binder.getCallingUid();
11458        if (UserHandle.getUserId(uid) != userId) {
11459            mContext.enforceCallingPermission(
11460                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11461                    "deletePackage for user " + userId);
11462        }
11463        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11464            try {
11465                observer.onPackageDeleted(packageName,
11466                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11467            } catch (RemoteException re) {
11468            }
11469            return;
11470        }
11471
11472        boolean uninstallBlocked = false;
11473        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11474            int[] users = sUserManager.getUserIds();
11475            for (int i = 0; i < users.length; ++i) {
11476                if (getBlockUninstallForUser(packageName, users[i])) {
11477                    uninstallBlocked = true;
11478                    break;
11479                }
11480            }
11481        } else {
11482            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11483        }
11484        if (uninstallBlocked) {
11485            try {
11486                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11487                        null);
11488            } catch (RemoteException re) {
11489            }
11490            return;
11491        }
11492
11493        if (DEBUG_REMOVE) {
11494            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
11495        }
11496        // Queue up an async operation since the package deletion may take a little while.
11497        mHandler.post(new Runnable() {
11498            public void run() {
11499                mHandler.removeCallbacks(this);
11500                final int returnCode = deletePackageX(packageName, userId, flags);
11501                if (observer != null) {
11502                    try {
11503                        observer.onPackageDeleted(packageName, returnCode, null);
11504                    } catch (RemoteException e) {
11505                        Log.i(TAG, "Observer no longer exists.");
11506                    } //end catch
11507                } //end if
11508            } //end run
11509        });
11510    }
11511
11512    private boolean isPackageDeviceAdmin(String packageName, int userId) {
11513        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
11514                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
11515        try {
11516            if (dpm != null) {
11517                if (dpm.isDeviceOwner(packageName)) {
11518                    return true;
11519                }
11520                int[] users;
11521                if (userId == UserHandle.USER_ALL) {
11522                    users = sUserManager.getUserIds();
11523                } else {
11524                    users = new int[]{userId};
11525                }
11526                for (int i = 0; i < users.length; ++i) {
11527                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
11528                        return true;
11529                    }
11530                }
11531            }
11532        } catch (RemoteException e) {
11533        }
11534        return false;
11535    }
11536
11537    /**
11538     *  This method is an internal method that could be get invoked either
11539     *  to delete an installed package or to clean up a failed installation.
11540     *  After deleting an installed package, a broadcast is sent to notify any
11541     *  listeners that the package has been installed. For cleaning up a failed
11542     *  installation, the broadcast is not necessary since the package's
11543     *  installation wouldn't have sent the initial broadcast either
11544     *  The key steps in deleting a package are
11545     *  deleting the package information in internal structures like mPackages,
11546     *  deleting the packages base directories through installd
11547     *  updating mSettings to reflect current status
11548     *  persisting settings for later use
11549     *  sending a broadcast if necessary
11550     */
11551    private int deletePackageX(String packageName, int userId, int flags) {
11552        final PackageRemovedInfo info = new PackageRemovedInfo();
11553        final boolean res;
11554
11555        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
11556                ? UserHandle.ALL : new UserHandle(userId);
11557
11558        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
11559            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
11560            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
11561        }
11562
11563        boolean removedForAllUsers = false;
11564        boolean systemUpdate = false;
11565
11566        // for the uninstall-updates case and restricted profiles, remember the per-
11567        // userhandle installed state
11568        int[] allUsers;
11569        boolean[] perUserInstalled;
11570        synchronized (mPackages) {
11571            PackageSetting ps = mSettings.mPackages.get(packageName);
11572            allUsers = sUserManager.getUserIds();
11573            perUserInstalled = new boolean[allUsers.length];
11574            for (int i = 0; i < allUsers.length; i++) {
11575                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11576            }
11577        }
11578
11579        synchronized (mInstallLock) {
11580            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
11581            res = deletePackageLI(packageName, removeForUser,
11582                    true, allUsers, perUserInstalled,
11583                    flags | REMOVE_CHATTY, info, true);
11584            systemUpdate = info.isRemovedPackageSystemUpdate;
11585            if (res && !systemUpdate && mPackages.get(packageName) == null) {
11586                removedForAllUsers = true;
11587            }
11588            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
11589                    + " removedForAllUsers=" + removedForAllUsers);
11590        }
11591
11592        if (res) {
11593            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
11594
11595            // If the removed package was a system update, the old system package
11596            // was re-enabled; we need to broadcast this information
11597            if (systemUpdate) {
11598                Bundle extras = new Bundle(1);
11599                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
11600                        ? info.removedAppId : info.uid);
11601                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11602
11603                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
11604                        extras, null, null, null);
11605                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
11606                        extras, null, null, null);
11607                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
11608                        null, packageName, null, null);
11609            }
11610        }
11611        // Force a gc here.
11612        Runtime.getRuntime().gc();
11613        // Delete the resources here after sending the broadcast to let
11614        // other processes clean up before deleting resources.
11615        if (info.args != null) {
11616            synchronized (mInstallLock) {
11617                info.args.doPostDeleteLI(true);
11618            }
11619        }
11620
11621        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
11622    }
11623
11624    static class PackageRemovedInfo {
11625        String removedPackage;
11626        int uid = -1;
11627        int removedAppId = -1;
11628        int[] removedUsers = null;
11629        boolean isRemovedPackageSystemUpdate = false;
11630        // Clean up resources deleted packages.
11631        InstallArgs args = null;
11632
11633        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
11634            Bundle extras = new Bundle(1);
11635            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
11636            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
11637            if (replacing) {
11638                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11639            }
11640            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
11641            if (removedPackage != null) {
11642                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
11643                        extras, null, null, removedUsers);
11644                if (fullRemove && !replacing) {
11645                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
11646                            extras, null, null, removedUsers);
11647                }
11648            }
11649            if (removedAppId >= 0) {
11650                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
11651                        removedUsers);
11652            }
11653        }
11654    }
11655
11656    /*
11657     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
11658     * flag is not set, the data directory is removed as well.
11659     * make sure this flag is set for partially installed apps. If not its meaningless to
11660     * delete a partially installed application.
11661     */
11662    private void removePackageDataLI(PackageSetting ps,
11663            int[] allUserHandles, boolean[] perUserInstalled,
11664            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
11665        String packageName = ps.name;
11666        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
11667        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
11668        // Retrieve object to delete permissions for shared user later on
11669        final PackageSetting deletedPs;
11670        // reader
11671        synchronized (mPackages) {
11672            deletedPs = mSettings.mPackages.get(packageName);
11673            if (outInfo != null) {
11674                outInfo.removedPackage = packageName;
11675                outInfo.removedUsers = deletedPs != null
11676                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
11677                        : null;
11678            }
11679        }
11680        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11681            removeDataDirsLI(packageName);
11682            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
11683        }
11684        // writer
11685        synchronized (mPackages) {
11686            if (deletedPs != null) {
11687                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11688                    if (outInfo != null) {
11689                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
11690                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
11691                    }
11692                    updatePermissionsLPw(deletedPs.name, null, 0);
11693                    if (deletedPs.sharedUser != null) {
11694                        // Remove permissions associated with package. Since runtime
11695                        // permissions are per user we have to kill the removed package
11696                        // or packages running under the shared user of the removed
11697                        // package if revoking the permissions requested only by the removed
11698                        // package is successful and this causes a change in gids.
11699                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11700                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
11701                                    userId);
11702                            if (userIdToKill == UserHandle.USER_ALL
11703                                    || userIdToKill >= UserHandle.USER_OWNER) {
11704                                // If gids changed for this user, kill all affected packages.
11705                                mHandler.post(new Runnable() {
11706                                    @Override
11707                                    public void run() {
11708                                        // This has to happen with no lock held.
11709                                        killSettingPackagesForUser(deletedPs, userIdToKill,
11710                                                KILL_APP_REASON_GIDS_CHANGED);
11711                                    }
11712                                });
11713                            break;
11714                            }
11715                        }
11716                    }
11717                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
11718                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
11719                }
11720                // make sure to preserve per-user disabled state if this removal was just
11721                // a downgrade of a system app to the factory package
11722                if (allUserHandles != null && perUserInstalled != null) {
11723                    if (DEBUG_REMOVE) {
11724                        Slog.d(TAG, "Propagating install state across downgrade");
11725                    }
11726                    for (int i = 0; i < allUserHandles.length; i++) {
11727                        if (DEBUG_REMOVE) {
11728                            Slog.d(TAG, "    user " + allUserHandles[i]
11729                                    + " => " + perUserInstalled[i]);
11730                        }
11731                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11732                    }
11733                }
11734            }
11735            // can downgrade to reader
11736            if (writeSettings) {
11737                // Save settings now
11738                mSettings.writeLPr();
11739            }
11740        }
11741        if (outInfo != null) {
11742            // A user ID was deleted here. Go through all users and remove it
11743            // from KeyStore.
11744            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
11745        }
11746    }
11747
11748    static boolean locationIsPrivileged(File path) {
11749        try {
11750            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
11751                    .getCanonicalPath();
11752            return path.getCanonicalPath().startsWith(privilegedAppDir);
11753        } catch (IOException e) {
11754            Slog.e(TAG, "Unable to access code path " + path);
11755        }
11756        return false;
11757    }
11758
11759    /*
11760     * Tries to delete system package.
11761     */
11762    private boolean deleteSystemPackageLI(PackageSetting newPs,
11763            int[] allUserHandles, boolean[] perUserInstalled,
11764            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
11765        final boolean applyUserRestrictions
11766                = (allUserHandles != null) && (perUserInstalled != null);
11767        PackageSetting disabledPs = null;
11768        // Confirm if the system package has been updated
11769        // An updated system app can be deleted. This will also have to restore
11770        // the system pkg from system partition
11771        // reader
11772        synchronized (mPackages) {
11773            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
11774        }
11775        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
11776                + " disabledPs=" + disabledPs);
11777        if (disabledPs == null) {
11778            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
11779            return false;
11780        } else if (DEBUG_REMOVE) {
11781            Slog.d(TAG, "Deleting system pkg from data partition");
11782        }
11783        if (DEBUG_REMOVE) {
11784            if (applyUserRestrictions) {
11785                Slog.d(TAG, "Remembering install states:");
11786                for (int i = 0; i < allUserHandles.length; i++) {
11787                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
11788                }
11789            }
11790        }
11791        // Delete the updated package
11792        outInfo.isRemovedPackageSystemUpdate = true;
11793        if (disabledPs.versionCode < newPs.versionCode) {
11794            // Delete data for downgrades
11795            flags &= ~PackageManager.DELETE_KEEP_DATA;
11796        } else {
11797            // Preserve data by setting flag
11798            flags |= PackageManager.DELETE_KEEP_DATA;
11799        }
11800        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
11801                allUserHandles, perUserInstalled, outInfo, writeSettings);
11802        if (!ret) {
11803            return false;
11804        }
11805        // writer
11806        synchronized (mPackages) {
11807            // Reinstate the old system package
11808            mSettings.enableSystemPackageLPw(newPs.name);
11809            // Remove any native libraries from the upgraded package.
11810            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
11811        }
11812        // Install the system package
11813        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
11814        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
11815        if (locationIsPrivileged(disabledPs.codePath)) {
11816            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11817        }
11818
11819        final PackageParser.Package newPkg;
11820        try {
11821            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
11822        } catch (PackageManagerException e) {
11823            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
11824            return false;
11825        }
11826
11827        // writer
11828        synchronized (mPackages) {
11829            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
11830            updatePermissionsLPw(newPkg.packageName, newPkg,
11831                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
11832            if (applyUserRestrictions) {
11833                if (DEBUG_REMOVE) {
11834                    Slog.d(TAG, "Propagating install state across reinstall");
11835                }
11836                for (int i = 0; i < allUserHandles.length; i++) {
11837                    if (DEBUG_REMOVE) {
11838                        Slog.d(TAG, "    user " + allUserHandles[i]
11839                                + " => " + perUserInstalled[i]);
11840                    }
11841                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11842                }
11843                // Regardless of writeSettings we need to ensure that this restriction
11844                // state propagation is persisted
11845                mSettings.writeAllUsersPackageRestrictionsLPr();
11846            }
11847            // can downgrade to reader here
11848            if (writeSettings) {
11849                mSettings.writeLPr();
11850            }
11851        }
11852        return true;
11853    }
11854
11855    private boolean deleteInstalledPackageLI(PackageSetting ps,
11856            boolean deleteCodeAndResources, int flags,
11857            int[] allUserHandles, boolean[] perUserInstalled,
11858            PackageRemovedInfo outInfo, boolean writeSettings) {
11859        if (outInfo != null) {
11860            outInfo.uid = ps.appId;
11861        }
11862
11863        // Delete package data from internal structures and also remove data if flag is set
11864        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
11865
11866        // Delete application code and resources
11867        if (deleteCodeAndResources && (outInfo != null)) {
11868            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
11869                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
11870                    getAppDexInstructionSets(ps));
11871            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
11872        }
11873        return true;
11874    }
11875
11876    @Override
11877    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
11878            int userId) {
11879        mContext.enforceCallingOrSelfPermission(
11880                android.Manifest.permission.DELETE_PACKAGES, null);
11881        synchronized (mPackages) {
11882            PackageSetting ps = mSettings.mPackages.get(packageName);
11883            if (ps == null) {
11884                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
11885                return false;
11886            }
11887            if (!ps.getInstalled(userId)) {
11888                // Can't block uninstall for an app that is not installed or enabled.
11889                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11890                return false;
11891            }
11892            ps.setBlockUninstall(blockUninstall, userId);
11893            mSettings.writePackageRestrictionsLPr(userId);
11894        }
11895        return true;
11896    }
11897
11898    @Override
11899    public boolean getBlockUninstallForUser(String packageName, int userId) {
11900        synchronized (mPackages) {
11901            PackageSetting ps = mSettings.mPackages.get(packageName);
11902            if (ps == null) {
11903                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11904                return false;
11905            }
11906            return ps.getBlockUninstall(userId);
11907        }
11908    }
11909
11910    /*
11911     * This method handles package deletion in general
11912     */
11913    private boolean deletePackageLI(String packageName, UserHandle user,
11914            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11915            int flags, PackageRemovedInfo outInfo,
11916            boolean writeSettings) {
11917        if (packageName == null) {
11918            Slog.w(TAG, "Attempt to delete null packageName.");
11919            return false;
11920        }
11921        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11922        PackageSetting ps;
11923        boolean dataOnly = false;
11924        int removeUser = -1;
11925        int appId = -1;
11926        synchronized (mPackages) {
11927            ps = mSettings.mPackages.get(packageName);
11928            if (ps == null) {
11929                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11930                return false;
11931            }
11932            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11933                    && user.getIdentifier() != UserHandle.USER_ALL) {
11934                // The caller is asking that the package only be deleted for a single
11935                // user.  To do this, we just mark its uninstalled state and delete
11936                // its data.  If this is a system app, we only allow this to happen if
11937                // they have set the special DELETE_SYSTEM_APP which requests different
11938                // semantics than normal for uninstalling system apps.
11939                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11940                ps.setUserState(user.getIdentifier(),
11941                        COMPONENT_ENABLED_STATE_DEFAULT,
11942                        false, //installed
11943                        true,  //stopped
11944                        true,  //notLaunched
11945                        false, //hidden
11946                        null, null, null,
11947                        false, // blockUninstall
11948                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
11949                if (!isSystemApp(ps)) {
11950                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11951                        // Other user still have this package installed, so all
11952                        // we need to do is clear this user's data and save that
11953                        // it is uninstalled.
11954                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11955                        removeUser = user.getIdentifier();
11956                        appId = ps.appId;
11957                        mSettings.writePackageRestrictionsLPr(removeUser);
11958                    } else {
11959                        // We need to set it back to 'installed' so the uninstall
11960                        // broadcasts will be sent correctly.
11961                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11962                        ps.setInstalled(true, user.getIdentifier());
11963                    }
11964                } else {
11965                    // This is a system app, so we assume that the
11966                    // other users still have this package installed, so all
11967                    // we need to do is clear this user's data and save that
11968                    // it is uninstalled.
11969                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11970                    removeUser = user.getIdentifier();
11971                    appId = ps.appId;
11972                    mSettings.writePackageRestrictionsLPr(removeUser);
11973                }
11974            }
11975        }
11976
11977        if (removeUser >= 0) {
11978            // From above, we determined that we are deleting this only
11979            // for a single user.  Continue the work here.
11980            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11981            if (outInfo != null) {
11982                outInfo.removedPackage = packageName;
11983                outInfo.removedAppId = appId;
11984                outInfo.removedUsers = new int[] {removeUser};
11985            }
11986            mInstaller.clearUserData(packageName, removeUser);
11987            removeKeystoreDataIfNeeded(removeUser, appId);
11988            schedulePackageCleaning(packageName, removeUser, false);
11989            return true;
11990        }
11991
11992        if (dataOnly) {
11993            // Delete application data first
11994            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11995            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11996            return true;
11997        }
11998
11999        boolean ret = false;
12000        if (isSystemApp(ps)) {
12001            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12002            // When an updated system application is deleted we delete the existing resources as well and
12003            // fall back to existing code in system partition
12004            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12005                    flags, outInfo, writeSettings);
12006        } else {
12007            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12008            // Kill application pre-emptively especially for apps on sd.
12009            killApplication(packageName, ps.appId, "uninstall pkg");
12010            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12011                    allUserHandles, perUserInstalled,
12012                    outInfo, writeSettings);
12013        }
12014
12015        return ret;
12016    }
12017
12018    private final class ClearStorageConnection implements ServiceConnection {
12019        IMediaContainerService mContainerService;
12020
12021        @Override
12022        public void onServiceConnected(ComponentName name, IBinder service) {
12023            synchronized (this) {
12024                mContainerService = IMediaContainerService.Stub.asInterface(service);
12025                notifyAll();
12026            }
12027        }
12028
12029        @Override
12030        public void onServiceDisconnected(ComponentName name) {
12031        }
12032    }
12033
12034    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12035        final boolean mounted;
12036        if (Environment.isExternalStorageEmulated()) {
12037            mounted = true;
12038        } else {
12039            final String status = Environment.getExternalStorageState();
12040
12041            mounted = status.equals(Environment.MEDIA_MOUNTED)
12042                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12043        }
12044
12045        if (!mounted) {
12046            return;
12047        }
12048
12049        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12050        int[] users;
12051        if (userId == UserHandle.USER_ALL) {
12052            users = sUserManager.getUserIds();
12053        } else {
12054            users = new int[] { userId };
12055        }
12056        final ClearStorageConnection conn = new ClearStorageConnection();
12057        if (mContext.bindServiceAsUser(
12058                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12059            try {
12060                for (int curUser : users) {
12061                    long timeout = SystemClock.uptimeMillis() + 5000;
12062                    synchronized (conn) {
12063                        long now = SystemClock.uptimeMillis();
12064                        while (conn.mContainerService == null && now < timeout) {
12065                            try {
12066                                conn.wait(timeout - now);
12067                            } catch (InterruptedException e) {
12068                            }
12069                        }
12070                    }
12071                    if (conn.mContainerService == null) {
12072                        return;
12073                    }
12074
12075                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12076                    clearDirectory(conn.mContainerService,
12077                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12078                    if (allData) {
12079                        clearDirectory(conn.mContainerService,
12080                                userEnv.buildExternalStorageAppDataDirs(packageName));
12081                        clearDirectory(conn.mContainerService,
12082                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12083                    }
12084                }
12085            } finally {
12086                mContext.unbindService(conn);
12087            }
12088        }
12089    }
12090
12091    @Override
12092    public void clearApplicationUserData(final String packageName,
12093            final IPackageDataObserver observer, final int userId) {
12094        mContext.enforceCallingOrSelfPermission(
12095                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12096        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12097        // Queue up an async operation since the package deletion may take a little while.
12098        mHandler.post(new Runnable() {
12099            public void run() {
12100                mHandler.removeCallbacks(this);
12101                final boolean succeeded;
12102                synchronized (mInstallLock) {
12103                    succeeded = clearApplicationUserDataLI(packageName, userId);
12104                }
12105                clearExternalStorageDataSync(packageName, userId, true);
12106                if (succeeded) {
12107                    // invoke DeviceStorageMonitor's update method to clear any notifications
12108                    DeviceStorageMonitorInternal
12109                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12110                    if (dsm != null) {
12111                        dsm.checkMemory();
12112                    }
12113                }
12114                if(observer != null) {
12115                    try {
12116                        observer.onRemoveCompleted(packageName, succeeded);
12117                    } catch (RemoteException e) {
12118                        Log.i(TAG, "Observer no longer exists.");
12119                    }
12120                } //end if observer
12121            } //end run
12122        });
12123    }
12124
12125    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12126        if (packageName == null) {
12127            Slog.w(TAG, "Attempt to delete null packageName.");
12128            return false;
12129        }
12130
12131        // Try finding details about the requested package
12132        PackageParser.Package pkg;
12133        synchronized (mPackages) {
12134            pkg = mPackages.get(packageName);
12135            if (pkg == null) {
12136                final PackageSetting ps = mSettings.mPackages.get(packageName);
12137                if (ps != null) {
12138                    pkg = ps.pkg;
12139                }
12140            }
12141        }
12142
12143        if (pkg == null) {
12144            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12145        }
12146
12147        // Always delete data directories for package, even if we found no other
12148        // record of app. This helps users recover from UID mismatches without
12149        // resorting to a full data wipe.
12150        int retCode = mInstaller.clearUserData(packageName, userId);
12151        if (retCode < 0) {
12152            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12153            return false;
12154        }
12155
12156        if (pkg == null) {
12157            return false;
12158        }
12159
12160        if (pkg != null && pkg.applicationInfo != null) {
12161            final int appId = pkg.applicationInfo.uid;
12162            removeKeystoreDataIfNeeded(userId, appId);
12163        }
12164
12165        // Create a native library symlink only if we have native libraries
12166        // and if the native libraries are 32 bit libraries. We do not provide
12167        // this symlink for 64 bit libraries.
12168        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
12169                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12170            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12171            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
12172                Slog.w(TAG, "Failed linking native library dir");
12173                return false;
12174            }
12175        }
12176
12177        return true;
12178    }
12179
12180    /**
12181     * Remove entries from the keystore daemon. Will only remove it if the
12182     * {@code appId} is valid.
12183     */
12184    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12185        if (appId < 0) {
12186            return;
12187        }
12188
12189        final KeyStore keyStore = KeyStore.getInstance();
12190        if (keyStore != null) {
12191            if (userId == UserHandle.USER_ALL) {
12192                for (final int individual : sUserManager.getUserIds()) {
12193                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12194                }
12195            } else {
12196                keyStore.clearUid(UserHandle.getUid(userId, appId));
12197            }
12198        } else {
12199            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12200        }
12201    }
12202
12203    @Override
12204    public void deleteApplicationCacheFiles(final String packageName,
12205            final IPackageDataObserver observer) {
12206        mContext.enforceCallingOrSelfPermission(
12207                android.Manifest.permission.DELETE_CACHE_FILES, null);
12208        // Queue up an async operation since the package deletion may take a little while.
12209        final int userId = UserHandle.getCallingUserId();
12210        mHandler.post(new Runnable() {
12211            public void run() {
12212                mHandler.removeCallbacks(this);
12213                final boolean succeded;
12214                synchronized (mInstallLock) {
12215                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12216                }
12217                clearExternalStorageDataSync(packageName, userId, false);
12218                if(observer != null) {
12219                    try {
12220                        observer.onRemoveCompleted(packageName, succeded);
12221                    } catch (RemoteException e) {
12222                        Log.i(TAG, "Observer no longer exists.");
12223                    }
12224                } //end if observer
12225            } //end run
12226        });
12227    }
12228
12229    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12230        if (packageName == null) {
12231            Slog.w(TAG, "Attempt to delete null packageName.");
12232            return false;
12233        }
12234        PackageParser.Package p;
12235        synchronized (mPackages) {
12236            p = mPackages.get(packageName);
12237        }
12238        if (p == null) {
12239            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12240            return false;
12241        }
12242        final ApplicationInfo applicationInfo = p.applicationInfo;
12243        if (applicationInfo == null) {
12244            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12245            return false;
12246        }
12247        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
12248        if (retCode < 0) {
12249            Slog.w(TAG, "Couldn't remove cache files for package: "
12250                       + packageName + " u" + userId);
12251            return false;
12252        }
12253        return true;
12254    }
12255
12256    @Override
12257    public void getPackageSizeInfo(final String packageName, int userHandle,
12258            final IPackageStatsObserver observer) {
12259        mContext.enforceCallingOrSelfPermission(
12260                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12261        if (packageName == null) {
12262            throw new IllegalArgumentException("Attempt to get size of null packageName");
12263        }
12264
12265        PackageStats stats = new PackageStats(packageName, userHandle);
12266
12267        /*
12268         * Queue up an async operation since the package measurement may take a
12269         * little while.
12270         */
12271        Message msg = mHandler.obtainMessage(INIT_COPY);
12272        msg.obj = new MeasureParams(stats, observer);
12273        mHandler.sendMessage(msg);
12274    }
12275
12276    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12277            PackageStats pStats) {
12278        if (packageName == null) {
12279            Slog.w(TAG, "Attempt to get size of null packageName.");
12280            return false;
12281        }
12282        PackageParser.Package p;
12283        boolean dataOnly = false;
12284        String libDirRoot = null;
12285        String asecPath = null;
12286        PackageSetting ps = null;
12287        synchronized (mPackages) {
12288            p = mPackages.get(packageName);
12289            ps = mSettings.mPackages.get(packageName);
12290            if(p == null) {
12291                dataOnly = true;
12292                if((ps == null) || (ps.pkg == null)) {
12293                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12294                    return false;
12295                }
12296                p = ps.pkg;
12297            }
12298            if (ps != null) {
12299                libDirRoot = ps.legacyNativeLibraryPathString;
12300            }
12301            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12302                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12303                if (secureContainerId != null) {
12304                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12305                }
12306            }
12307        }
12308        String publicSrcDir = null;
12309        if(!dataOnly) {
12310            final ApplicationInfo applicationInfo = p.applicationInfo;
12311            if (applicationInfo == null) {
12312                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12313                return false;
12314            }
12315            if (p.isForwardLocked()) {
12316                publicSrcDir = applicationInfo.getBaseResourcePath();
12317            }
12318        }
12319        // TODO: extend to measure size of split APKs
12320        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12321        // not just the first level.
12322        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12323        // just the primary.
12324        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12325        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
12326                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12327        if (res < 0) {
12328            return false;
12329        }
12330
12331        // Fix-up for forward-locked applications in ASEC containers.
12332        if (!isExternal(p)) {
12333            pStats.codeSize += pStats.externalCodeSize;
12334            pStats.externalCodeSize = 0L;
12335        }
12336
12337        return true;
12338    }
12339
12340
12341    @Override
12342    public void addPackageToPreferred(String packageName) {
12343        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12344    }
12345
12346    @Override
12347    public void removePackageFromPreferred(String packageName) {
12348        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12349    }
12350
12351    @Override
12352    public List<PackageInfo> getPreferredPackages(int flags) {
12353        return new ArrayList<PackageInfo>();
12354    }
12355
12356    private int getUidTargetSdkVersionLockedLPr(int uid) {
12357        Object obj = mSettings.getUserIdLPr(uid);
12358        if (obj instanceof SharedUserSetting) {
12359            final SharedUserSetting sus = (SharedUserSetting) obj;
12360            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12361            final Iterator<PackageSetting> it = sus.packages.iterator();
12362            while (it.hasNext()) {
12363                final PackageSetting ps = it.next();
12364                if (ps.pkg != null) {
12365                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12366                    if (v < vers) vers = v;
12367                }
12368            }
12369            return vers;
12370        } else if (obj instanceof PackageSetting) {
12371            final PackageSetting ps = (PackageSetting) obj;
12372            if (ps.pkg != null) {
12373                return ps.pkg.applicationInfo.targetSdkVersion;
12374            }
12375        }
12376        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12377    }
12378
12379    @Override
12380    public void addPreferredActivity(IntentFilter filter, int match,
12381            ComponentName[] set, ComponentName activity, int userId) {
12382        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12383                "Adding preferred");
12384    }
12385
12386    private void addPreferredActivityInternal(IntentFilter filter, int match,
12387            ComponentName[] set, ComponentName activity, boolean always, int userId,
12388            String opname) {
12389        // writer
12390        int callingUid = Binder.getCallingUid();
12391        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12392        if (filter.countActions() == 0) {
12393            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12394            return;
12395        }
12396        synchronized (mPackages) {
12397            if (mContext.checkCallingOrSelfPermission(
12398                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12399                    != PackageManager.PERMISSION_GRANTED) {
12400                if (getUidTargetSdkVersionLockedLPr(callingUid)
12401                        < Build.VERSION_CODES.FROYO) {
12402                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12403                            + callingUid);
12404                    return;
12405                }
12406                mContext.enforceCallingOrSelfPermission(
12407                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12408            }
12409
12410            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12411            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12412                    + userId + ":");
12413            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12414            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12415            scheduleWritePackageRestrictionsLocked(userId);
12416        }
12417    }
12418
12419    @Override
12420    public void replacePreferredActivity(IntentFilter filter, int match,
12421            ComponentName[] set, ComponentName activity, int userId) {
12422        if (filter.countActions() != 1) {
12423            throw new IllegalArgumentException(
12424                    "replacePreferredActivity expects filter to have only 1 action.");
12425        }
12426        if (filter.countDataAuthorities() != 0
12427                || filter.countDataPaths() != 0
12428                || filter.countDataSchemes() > 1
12429                || filter.countDataTypes() != 0) {
12430            throw new IllegalArgumentException(
12431                    "replacePreferredActivity expects filter to have no data authorities, " +
12432                    "paths, or types; and at most one scheme.");
12433        }
12434
12435        final int callingUid = Binder.getCallingUid();
12436        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12437        synchronized (mPackages) {
12438            if (mContext.checkCallingOrSelfPermission(
12439                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12440                    != PackageManager.PERMISSION_GRANTED) {
12441                if (getUidTargetSdkVersionLockedLPr(callingUid)
12442                        < Build.VERSION_CODES.FROYO) {
12443                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12444                            + Binder.getCallingUid());
12445                    return;
12446                }
12447                mContext.enforceCallingOrSelfPermission(
12448                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12449            }
12450
12451            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12452            if (pir != null) {
12453                // Get all of the existing entries that exactly match this filter.
12454                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
12455                if (existing != null && existing.size() == 1) {
12456                    PreferredActivity cur = existing.get(0);
12457                    if (DEBUG_PREFERRED) {
12458                        Slog.i(TAG, "Checking replace of preferred:");
12459                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12460                        if (!cur.mPref.mAlways) {
12461                            Slog.i(TAG, "  -- CUR; not mAlways!");
12462                        } else {
12463                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
12464                            Slog.i(TAG, "  -- CUR: mSet="
12465                                    + Arrays.toString(cur.mPref.mSetComponents));
12466                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
12467                            Slog.i(TAG, "  -- NEW: mMatch="
12468                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
12469                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
12470                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
12471                        }
12472                    }
12473                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
12474                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
12475                            && cur.mPref.sameSet(set)) {
12476                        // Setting the preferred activity to what it happens to be already
12477                        if (DEBUG_PREFERRED) {
12478                            Slog.i(TAG, "Replacing with same preferred activity "
12479                                    + cur.mPref.mShortComponent + " for user "
12480                                    + userId + ":");
12481                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12482                        }
12483                        return;
12484                    }
12485                }
12486
12487                if (existing != null) {
12488                    if (DEBUG_PREFERRED) {
12489                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
12490                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12491                    }
12492                    for (int i = 0; i < existing.size(); i++) {
12493                        PreferredActivity pa = existing.get(i);
12494                        if (DEBUG_PREFERRED) {
12495                            Slog.i(TAG, "Removing existing preferred activity "
12496                                    + pa.mPref.mComponent + ":");
12497                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
12498                        }
12499                        pir.removeFilter(pa);
12500                    }
12501                }
12502            }
12503            addPreferredActivityInternal(filter, match, set, activity, true, userId,
12504                    "Replacing preferred");
12505        }
12506    }
12507
12508    @Override
12509    public void clearPackagePreferredActivities(String packageName) {
12510        final int uid = Binder.getCallingUid();
12511        // writer
12512        synchronized (mPackages) {
12513            PackageParser.Package pkg = mPackages.get(packageName);
12514            if (pkg == null || pkg.applicationInfo.uid != uid) {
12515                if (mContext.checkCallingOrSelfPermission(
12516                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12517                        != PackageManager.PERMISSION_GRANTED) {
12518                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
12519                            < Build.VERSION_CODES.FROYO) {
12520                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
12521                                + Binder.getCallingUid());
12522                        return;
12523                    }
12524                    mContext.enforceCallingOrSelfPermission(
12525                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12526                }
12527            }
12528
12529            int user = UserHandle.getCallingUserId();
12530            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
12531                scheduleWritePackageRestrictionsLocked(user);
12532            }
12533        }
12534    }
12535
12536    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12537    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
12538        ArrayList<PreferredActivity> removed = null;
12539        boolean changed = false;
12540        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12541            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
12542            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12543            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
12544                continue;
12545            }
12546            Iterator<PreferredActivity> it = pir.filterIterator();
12547            while (it.hasNext()) {
12548                PreferredActivity pa = it.next();
12549                // Mark entry for removal only if it matches the package name
12550                // and the entry is of type "always".
12551                if (packageName == null ||
12552                        (pa.mPref.mComponent.getPackageName().equals(packageName)
12553                                && pa.mPref.mAlways)) {
12554                    if (removed == null) {
12555                        removed = new ArrayList<PreferredActivity>();
12556                    }
12557                    removed.add(pa);
12558                }
12559            }
12560            if (removed != null) {
12561                for (int j=0; j<removed.size(); j++) {
12562                    PreferredActivity pa = removed.get(j);
12563                    pir.removeFilter(pa);
12564                }
12565                changed = true;
12566            }
12567        }
12568        return changed;
12569    }
12570
12571    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12572    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
12573        if (userId == UserHandle.USER_ALL) {
12574            mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds());
12575            for (int oneUserId : sUserManager.getUserIds()) {
12576                scheduleWritePackageRestrictionsLocked(oneUserId);
12577            }
12578        } else {
12579            mSettings.removeIntentFilterVerificationLPw(packageName, userId);
12580            scheduleWritePackageRestrictionsLocked(userId);
12581        }
12582    }
12583
12584    @Override
12585    public void resetPreferredActivities(int userId) {
12586        /* TODO: Actually use userId. Why is it being passed in? */
12587        mContext.enforceCallingOrSelfPermission(
12588                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12589        // writer
12590        synchronized (mPackages) {
12591            int user = UserHandle.getCallingUserId();
12592            clearPackagePreferredActivitiesLPw(null, user);
12593            mSettings.readDefaultPreferredAppsLPw(this, user);
12594            scheduleWritePackageRestrictionsLocked(user);
12595        }
12596    }
12597
12598    @Override
12599    public int getPreferredActivities(List<IntentFilter> outFilters,
12600            List<ComponentName> outActivities, String packageName) {
12601
12602        int num = 0;
12603        final int userId = UserHandle.getCallingUserId();
12604        // reader
12605        synchronized (mPackages) {
12606            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12607            if (pir != null) {
12608                final Iterator<PreferredActivity> it = pir.filterIterator();
12609                while (it.hasNext()) {
12610                    final PreferredActivity pa = it.next();
12611                    if (packageName == null
12612                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
12613                                    && pa.mPref.mAlways)) {
12614                        if (outFilters != null) {
12615                            outFilters.add(new IntentFilter(pa));
12616                        }
12617                        if (outActivities != null) {
12618                            outActivities.add(pa.mPref.mComponent);
12619                        }
12620                    }
12621                }
12622            }
12623        }
12624
12625        return num;
12626    }
12627
12628    @Override
12629    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
12630            int userId) {
12631        int callingUid = Binder.getCallingUid();
12632        if (callingUid != Process.SYSTEM_UID) {
12633            throw new SecurityException(
12634                    "addPersistentPreferredActivity can only be run by the system");
12635        }
12636        if (filter.countActions() == 0) {
12637            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12638            return;
12639        }
12640        synchronized (mPackages) {
12641            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
12642                    " :");
12643            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12644            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
12645                    new PersistentPreferredActivity(filter, activity));
12646            scheduleWritePackageRestrictionsLocked(userId);
12647        }
12648    }
12649
12650    @Override
12651    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
12652        int callingUid = Binder.getCallingUid();
12653        if (callingUid != Process.SYSTEM_UID) {
12654            throw new SecurityException(
12655                    "clearPackagePersistentPreferredActivities can only be run by the system");
12656        }
12657        ArrayList<PersistentPreferredActivity> removed = null;
12658        boolean changed = false;
12659        synchronized (mPackages) {
12660            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
12661                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
12662                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
12663                        .valueAt(i);
12664                if (userId != thisUserId) {
12665                    continue;
12666                }
12667                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
12668                while (it.hasNext()) {
12669                    PersistentPreferredActivity ppa = it.next();
12670                    // Mark entry for removal only if it matches the package name.
12671                    if (ppa.mComponent.getPackageName().equals(packageName)) {
12672                        if (removed == null) {
12673                            removed = new ArrayList<PersistentPreferredActivity>();
12674                        }
12675                        removed.add(ppa);
12676                    }
12677                }
12678                if (removed != null) {
12679                    for (int j=0; j<removed.size(); j++) {
12680                        PersistentPreferredActivity ppa = removed.get(j);
12681                        ppir.removeFilter(ppa);
12682                    }
12683                    changed = true;
12684                }
12685            }
12686
12687            if (changed) {
12688                scheduleWritePackageRestrictionsLocked(userId);
12689            }
12690        }
12691    }
12692
12693    /**
12694     * Non-Binder method, support for the backup/restore mechanism: write the
12695     * full set of preferred activities in its canonical XML format.  Returns true
12696     * on success; false otherwise.
12697     */
12698    @Override
12699    public byte[] getPreferredActivityBackup(int userId) {
12700        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
12701            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
12702        }
12703
12704        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
12705        try {
12706            final XmlSerializer serializer = new FastXmlSerializer();
12707            serializer.setOutput(dataStream, "utf-8");
12708            serializer.startDocument(null, true);
12709            serializer.startTag(null, TAG_PREFERRED_BACKUP);
12710
12711            synchronized (mPackages) {
12712                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
12713            }
12714
12715            serializer.endTag(null, TAG_PREFERRED_BACKUP);
12716            serializer.endDocument();
12717            serializer.flush();
12718        } catch (Exception e) {
12719            if (DEBUG_BACKUP) {
12720                Slog.e(TAG, "Unable to write preferred activities for backup", e);
12721            }
12722            return null;
12723        }
12724
12725        return dataStream.toByteArray();
12726    }
12727
12728    @Override
12729    public void restorePreferredActivities(byte[] backup, int userId) {
12730        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
12731            throw new SecurityException("Only the system may call restorePreferredActivities()");
12732        }
12733
12734        try {
12735            final XmlPullParser parser = Xml.newPullParser();
12736            parser.setInput(new ByteArrayInputStream(backup), null);
12737
12738            int type;
12739            while ((type = parser.next()) != XmlPullParser.START_TAG
12740                    && type != XmlPullParser.END_DOCUMENT) {
12741            }
12742            if (type != XmlPullParser.START_TAG) {
12743                // oops didn't find a start tag?!
12744                if (DEBUG_BACKUP) {
12745                    Slog.e(TAG, "Didn't find start tag during restore");
12746                }
12747                return;
12748            }
12749
12750            // this is supposed to be TAG_PREFERRED_BACKUP
12751            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
12752                if (DEBUG_BACKUP) {
12753                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
12754                }
12755                return;
12756            }
12757
12758            // skip interfering stuff, then we're aligned with the backing implementation
12759            while ((type = parser.next()) == XmlPullParser.TEXT) { }
12760            synchronized (mPackages) {
12761                mSettings.readPreferredActivitiesLPw(parser, userId);
12762            }
12763        } catch (Exception e) {
12764            if (DEBUG_BACKUP) {
12765                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
12766            }
12767        }
12768    }
12769
12770    @Override
12771    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
12772            int sourceUserId, int targetUserId, int flags) {
12773        mContext.enforceCallingOrSelfPermission(
12774                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12775        int callingUid = Binder.getCallingUid();
12776        enforceOwnerRights(ownerPackage, callingUid);
12777        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12778        if (intentFilter.countActions() == 0) {
12779            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
12780            return;
12781        }
12782        synchronized (mPackages) {
12783            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
12784                    ownerPackage, targetUserId, flags);
12785            CrossProfileIntentResolver resolver =
12786                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12787            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
12788            // We have all those whose filter is equal. Now checking if the rest is equal as well.
12789            if (existing != null) {
12790                int size = existing.size();
12791                for (int i = 0; i < size; i++) {
12792                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
12793                        return;
12794                    }
12795                }
12796            }
12797            resolver.addFilter(newFilter);
12798            scheduleWritePackageRestrictionsLocked(sourceUserId);
12799        }
12800    }
12801
12802    @Override
12803    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
12804        mContext.enforceCallingOrSelfPermission(
12805                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12806        int callingUid = Binder.getCallingUid();
12807        enforceOwnerRights(ownerPackage, callingUid);
12808        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12809        synchronized (mPackages) {
12810            CrossProfileIntentResolver resolver =
12811                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12812            ArraySet<CrossProfileIntentFilter> set =
12813                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
12814            for (CrossProfileIntentFilter filter : set) {
12815                if (filter.getOwnerPackage().equals(ownerPackage)) {
12816                    resolver.removeFilter(filter);
12817                }
12818            }
12819            scheduleWritePackageRestrictionsLocked(sourceUserId);
12820        }
12821    }
12822
12823    // Enforcing that callingUid is owning pkg on userId
12824    private void enforceOwnerRights(String pkg, int callingUid) {
12825        // The system owns everything.
12826        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
12827            return;
12828        }
12829        int callingUserId = UserHandle.getUserId(callingUid);
12830        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
12831        if (pi == null) {
12832            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
12833                    + callingUserId);
12834        }
12835        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
12836            throw new SecurityException("Calling uid " + callingUid
12837                    + " does not own package " + pkg);
12838        }
12839    }
12840
12841    @Override
12842    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
12843        Intent intent = new Intent(Intent.ACTION_MAIN);
12844        intent.addCategory(Intent.CATEGORY_HOME);
12845
12846        final int callingUserId = UserHandle.getCallingUserId();
12847        List<ResolveInfo> list = queryIntentActivities(intent, null,
12848                PackageManager.GET_META_DATA, callingUserId);
12849        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
12850                true, false, false, callingUserId);
12851
12852        allHomeCandidates.clear();
12853        if (list != null) {
12854            for (ResolveInfo ri : list) {
12855                allHomeCandidates.add(ri);
12856            }
12857        }
12858        return (preferred == null || preferred.activityInfo == null)
12859                ? null
12860                : new ComponentName(preferred.activityInfo.packageName,
12861                        preferred.activityInfo.name);
12862    }
12863
12864    @Override
12865    public void setApplicationEnabledSetting(String appPackageName,
12866            int newState, int flags, int userId, String callingPackage) {
12867        if (!sUserManager.exists(userId)) return;
12868        if (callingPackage == null) {
12869            callingPackage = Integer.toString(Binder.getCallingUid());
12870        }
12871        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
12872    }
12873
12874    @Override
12875    public void setComponentEnabledSetting(ComponentName componentName,
12876            int newState, int flags, int userId) {
12877        if (!sUserManager.exists(userId)) return;
12878        setEnabledSetting(componentName.getPackageName(),
12879                componentName.getClassName(), newState, flags, userId, null);
12880    }
12881
12882    private void setEnabledSetting(final String packageName, String className, int newState,
12883            final int flags, int userId, String callingPackage) {
12884        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
12885              || newState == COMPONENT_ENABLED_STATE_ENABLED
12886              || newState == COMPONENT_ENABLED_STATE_DISABLED
12887              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
12888              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
12889            throw new IllegalArgumentException("Invalid new component state: "
12890                    + newState);
12891        }
12892        PackageSetting pkgSetting;
12893        final int uid = Binder.getCallingUid();
12894        final int permission = mContext.checkCallingOrSelfPermission(
12895                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12896        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
12897        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12898        boolean sendNow = false;
12899        boolean isApp = (className == null);
12900        String componentName = isApp ? packageName : className;
12901        int packageUid = -1;
12902        ArrayList<String> components;
12903
12904        // writer
12905        synchronized (mPackages) {
12906            pkgSetting = mSettings.mPackages.get(packageName);
12907            if (pkgSetting == null) {
12908                if (className == null) {
12909                    throw new IllegalArgumentException(
12910                            "Unknown package: " + packageName);
12911                }
12912                throw new IllegalArgumentException(
12913                        "Unknown component: " + packageName
12914                        + "/" + className);
12915            }
12916            // Allow root and verify that userId is not being specified by a different user
12917            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
12918                throw new SecurityException(
12919                        "Permission Denial: attempt to change component state from pid="
12920                        + Binder.getCallingPid()
12921                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
12922            }
12923            if (className == null) {
12924                // We're dealing with an application/package level state change
12925                if (pkgSetting.getEnabled(userId) == newState) {
12926                    // Nothing to do
12927                    return;
12928                }
12929                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
12930                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
12931                    // Don't care about who enables an app.
12932                    callingPackage = null;
12933                }
12934                pkgSetting.setEnabled(newState, userId, callingPackage);
12935                // pkgSetting.pkg.mSetEnabled = newState;
12936            } else {
12937                // We're dealing with a component level state change
12938                // First, verify that this is a valid class name.
12939                PackageParser.Package pkg = pkgSetting.pkg;
12940                if (pkg == null || !pkg.hasComponentClassName(className)) {
12941                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
12942                        throw new IllegalArgumentException("Component class " + className
12943                                + " does not exist in " + packageName);
12944                    } else {
12945                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
12946                                + className + " does not exist in " + packageName);
12947                    }
12948                }
12949                switch (newState) {
12950                case COMPONENT_ENABLED_STATE_ENABLED:
12951                    if (!pkgSetting.enableComponentLPw(className, userId)) {
12952                        return;
12953                    }
12954                    break;
12955                case COMPONENT_ENABLED_STATE_DISABLED:
12956                    if (!pkgSetting.disableComponentLPw(className, userId)) {
12957                        return;
12958                    }
12959                    break;
12960                case COMPONENT_ENABLED_STATE_DEFAULT:
12961                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
12962                        return;
12963                    }
12964                    break;
12965                default:
12966                    Slog.e(TAG, "Invalid new component state: " + newState);
12967                    return;
12968                }
12969            }
12970            scheduleWritePackageRestrictionsLocked(userId);
12971            components = mPendingBroadcasts.get(userId, packageName);
12972            final boolean newPackage = components == null;
12973            if (newPackage) {
12974                components = new ArrayList<String>();
12975            }
12976            if (!components.contains(componentName)) {
12977                components.add(componentName);
12978            }
12979            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12980                sendNow = true;
12981                // Purge entry from pending broadcast list if another one exists already
12982                // since we are sending one right away.
12983                mPendingBroadcasts.remove(userId, packageName);
12984            } else {
12985                if (newPackage) {
12986                    mPendingBroadcasts.put(userId, packageName, components);
12987                }
12988                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12989                    // Schedule a message
12990                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12991                }
12992            }
12993        }
12994
12995        long callingId = Binder.clearCallingIdentity();
12996        try {
12997            if (sendNow) {
12998                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12999                sendPackageChangedBroadcast(packageName,
13000                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13001            }
13002        } finally {
13003            Binder.restoreCallingIdentity(callingId);
13004        }
13005    }
13006
13007    private void sendPackageChangedBroadcast(String packageName,
13008            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13009        if (DEBUG_INSTALL)
13010            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13011                    + componentNames);
13012        Bundle extras = new Bundle(4);
13013        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13014        String nameList[] = new String[componentNames.size()];
13015        componentNames.toArray(nameList);
13016        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13017        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13018        extras.putInt(Intent.EXTRA_UID, packageUid);
13019        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13020                new int[] {UserHandle.getUserId(packageUid)});
13021    }
13022
13023    @Override
13024    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13025        if (!sUserManager.exists(userId)) return;
13026        final int uid = Binder.getCallingUid();
13027        final int permission = mContext.checkCallingOrSelfPermission(
13028                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13029        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13030        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13031        // writer
13032        synchronized (mPackages) {
13033            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
13034                    uid, userId)) {
13035                scheduleWritePackageRestrictionsLocked(userId);
13036            }
13037        }
13038    }
13039
13040    @Override
13041    public String getInstallerPackageName(String packageName) {
13042        // reader
13043        synchronized (mPackages) {
13044            return mSettings.getInstallerPackageNameLPr(packageName);
13045        }
13046    }
13047
13048    @Override
13049    public int getApplicationEnabledSetting(String packageName, int userId) {
13050        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13051        int uid = Binder.getCallingUid();
13052        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13053        // reader
13054        synchronized (mPackages) {
13055            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13056        }
13057    }
13058
13059    @Override
13060    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13061        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13062        int uid = Binder.getCallingUid();
13063        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13064        // reader
13065        synchronized (mPackages) {
13066            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13067        }
13068    }
13069
13070    @Override
13071    public void enterSafeMode() {
13072        enforceSystemOrRoot("Only the system can request entering safe mode");
13073
13074        if (!mSystemReady) {
13075            mSafeMode = true;
13076        }
13077    }
13078
13079    @Override
13080    public void systemReady() {
13081        mSystemReady = true;
13082
13083        // Read the compatibilty setting when the system is ready.
13084        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13085                mContext.getContentResolver(),
13086                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13087        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13088        if (DEBUG_SETTINGS) {
13089            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13090        }
13091
13092        synchronized (mPackages) {
13093            // Verify that all of the preferred activity components actually
13094            // exist.  It is possible for applications to be updated and at
13095            // that point remove a previously declared activity component that
13096            // had been set as a preferred activity.  We try to clean this up
13097            // the next time we encounter that preferred activity, but it is
13098            // possible for the user flow to never be able to return to that
13099            // situation so here we do a sanity check to make sure we haven't
13100            // left any junk around.
13101            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13102            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13103                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13104                removed.clear();
13105                for (PreferredActivity pa : pir.filterSet()) {
13106                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13107                        removed.add(pa);
13108                    }
13109                }
13110                if (removed.size() > 0) {
13111                    for (int r=0; r<removed.size(); r++) {
13112                        PreferredActivity pa = removed.get(r);
13113                        Slog.w(TAG, "Removing dangling preferred activity: "
13114                                + pa.mPref.mComponent);
13115                        pir.removeFilter(pa);
13116                    }
13117                    mSettings.writePackageRestrictionsLPr(
13118                            mSettings.mPreferredActivities.keyAt(i));
13119                }
13120            }
13121        }
13122        sUserManager.systemReady();
13123
13124        // Kick off any messages waiting for system ready
13125        if (mPostSystemReadyMessages != null) {
13126            for (Message msg : mPostSystemReadyMessages) {
13127                msg.sendToTarget();
13128            }
13129            mPostSystemReadyMessages = null;
13130        }
13131
13132        // Watch for external volumes that come and go over time
13133        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13134        storage.registerListener(mStorageListener);
13135
13136        mInstallerService.systemReady();
13137    }
13138
13139    @Override
13140    public boolean isSafeMode() {
13141        return mSafeMode;
13142    }
13143
13144    @Override
13145    public boolean hasSystemUidErrors() {
13146        return mHasSystemUidErrors;
13147    }
13148
13149    static String arrayToString(int[] array) {
13150        StringBuffer buf = new StringBuffer(128);
13151        buf.append('[');
13152        if (array != null) {
13153            for (int i=0; i<array.length; i++) {
13154                if (i > 0) buf.append(", ");
13155                buf.append(array[i]);
13156            }
13157        }
13158        buf.append(']');
13159        return buf.toString();
13160    }
13161
13162    static class DumpState {
13163        public static final int DUMP_LIBS = 1 << 0;
13164        public static final int DUMP_FEATURES = 1 << 1;
13165        public static final int DUMP_RESOLVERS = 1 << 2;
13166        public static final int DUMP_PERMISSIONS = 1 << 3;
13167        public static final int DUMP_PACKAGES = 1 << 4;
13168        public static final int DUMP_SHARED_USERS = 1 << 5;
13169        public static final int DUMP_MESSAGES = 1 << 6;
13170        public static final int DUMP_PROVIDERS = 1 << 7;
13171        public static final int DUMP_VERIFIERS = 1 << 8;
13172        public static final int DUMP_PREFERRED = 1 << 9;
13173        public static final int DUMP_PREFERRED_XML = 1 << 10;
13174        public static final int DUMP_KEYSETS = 1 << 11;
13175        public static final int DUMP_VERSION = 1 << 12;
13176        public static final int DUMP_INSTALLS = 1 << 13;
13177        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13178        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13179
13180        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13181
13182        private int mTypes;
13183
13184        private int mOptions;
13185
13186        private boolean mTitlePrinted;
13187
13188        private SharedUserSetting mSharedUser;
13189
13190        public boolean isDumping(int type) {
13191            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13192                return true;
13193            }
13194
13195            return (mTypes & type) != 0;
13196        }
13197
13198        public void setDump(int type) {
13199            mTypes |= type;
13200        }
13201
13202        public boolean isOptionEnabled(int option) {
13203            return (mOptions & option) != 0;
13204        }
13205
13206        public void setOptionEnabled(int option) {
13207            mOptions |= option;
13208        }
13209
13210        public boolean onTitlePrinted() {
13211            final boolean printed = mTitlePrinted;
13212            mTitlePrinted = true;
13213            return printed;
13214        }
13215
13216        public boolean getTitlePrinted() {
13217            return mTitlePrinted;
13218        }
13219
13220        public void setTitlePrinted(boolean enabled) {
13221            mTitlePrinted = enabled;
13222        }
13223
13224        public SharedUserSetting getSharedUser() {
13225            return mSharedUser;
13226        }
13227
13228        public void setSharedUser(SharedUserSetting user) {
13229            mSharedUser = user;
13230        }
13231    }
13232
13233    @Override
13234    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13235        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13236                != PackageManager.PERMISSION_GRANTED) {
13237            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13238                    + Binder.getCallingPid()
13239                    + ", uid=" + Binder.getCallingUid()
13240                    + " without permission "
13241                    + android.Manifest.permission.DUMP);
13242            return;
13243        }
13244
13245        DumpState dumpState = new DumpState();
13246        boolean fullPreferred = false;
13247        boolean checkin = false;
13248
13249        String packageName = null;
13250
13251        int opti = 0;
13252        while (opti < args.length) {
13253            String opt = args[opti];
13254            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13255                break;
13256            }
13257            opti++;
13258
13259            if ("-a".equals(opt)) {
13260                // Right now we only know how to print all.
13261            } else if ("-h".equals(opt)) {
13262                pw.println("Package manager dump options:");
13263                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13264                pw.println("    --checkin: dump for a checkin");
13265                pw.println("    -f: print details of intent filters");
13266                pw.println("    -h: print this help");
13267                pw.println("  cmd may be one of:");
13268                pw.println("    l[ibraries]: list known shared libraries");
13269                pw.println("    f[ibraries]: list device features");
13270                pw.println("    k[eysets]: print known keysets");
13271                pw.println("    r[esolvers]: dump intent resolvers");
13272                pw.println("    perm[issions]: dump permissions");
13273                pw.println("    pref[erred]: print preferred package settings");
13274                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13275                pw.println("    prov[iders]: dump content providers");
13276                pw.println("    p[ackages]: dump installed packages");
13277                pw.println("    s[hared-users]: dump shared user IDs");
13278                pw.println("    m[essages]: print collected runtime messages");
13279                pw.println("    v[erifiers]: print package verifier info");
13280                pw.println("    version: print database version info");
13281                pw.println("    write: write current settings now");
13282                pw.println("    <package.name>: info about given package");
13283                pw.println("    installs: details about install sessions");
13284                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13285                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13286                return;
13287            } else if ("--checkin".equals(opt)) {
13288                checkin = true;
13289            } else if ("-f".equals(opt)) {
13290                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13291            } else {
13292                pw.println("Unknown argument: " + opt + "; use -h for help");
13293            }
13294        }
13295
13296        // Is the caller requesting to dump a particular piece of data?
13297        if (opti < args.length) {
13298            String cmd = args[opti];
13299            opti++;
13300            // Is this a package name?
13301            if ("android".equals(cmd) || cmd.contains(".")) {
13302                packageName = cmd;
13303                // When dumping a single package, we always dump all of its
13304                // filter information since the amount of data will be reasonable.
13305                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13306            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13307                dumpState.setDump(DumpState.DUMP_LIBS);
13308            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13309                dumpState.setDump(DumpState.DUMP_FEATURES);
13310            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13311                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13312            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13313                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13314            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13315                dumpState.setDump(DumpState.DUMP_PREFERRED);
13316            } else if ("preferred-xml".equals(cmd)) {
13317                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13318                if (opti < args.length && "--full".equals(args[opti])) {
13319                    fullPreferred = true;
13320                    opti++;
13321                }
13322            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13323                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13324            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13325                dumpState.setDump(DumpState.DUMP_PACKAGES);
13326            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13327                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13328            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13329                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13330            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13331                dumpState.setDump(DumpState.DUMP_MESSAGES);
13332            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13333                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13334            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13335                    || "intent-filter-verifiers".equals(cmd)) {
13336                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13337            } else if ("version".equals(cmd)) {
13338                dumpState.setDump(DumpState.DUMP_VERSION);
13339            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13340                dumpState.setDump(DumpState.DUMP_KEYSETS);
13341            } else if ("installs".equals(cmd)) {
13342                dumpState.setDump(DumpState.DUMP_INSTALLS);
13343            } else if ("write".equals(cmd)) {
13344                synchronized (mPackages) {
13345                    mSettings.writeLPr();
13346                    pw.println("Settings written.");
13347                    return;
13348                }
13349            }
13350        }
13351
13352        if (checkin) {
13353            pw.println("vers,1");
13354        }
13355
13356        // reader
13357        synchronized (mPackages) {
13358            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13359                if (!checkin) {
13360                    if (dumpState.onTitlePrinted())
13361                        pw.println();
13362                    pw.println("Database versions:");
13363                    pw.print("  SDK Version:");
13364                    pw.print(" internal=");
13365                    pw.print(mSettings.mInternalSdkPlatform);
13366                    pw.print(" external=");
13367                    pw.println(mSettings.mExternalSdkPlatform);
13368                    pw.print("  DB Version:");
13369                    pw.print(" internal=");
13370                    pw.print(mSettings.mInternalDatabaseVersion);
13371                    pw.print(" external=");
13372                    pw.println(mSettings.mExternalDatabaseVersion);
13373                }
13374            }
13375
13376            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13377                if (!checkin) {
13378                    if (dumpState.onTitlePrinted())
13379                        pw.println();
13380                    pw.println("Verifiers:");
13381                    pw.print("  Required: ");
13382                    pw.print(mRequiredVerifierPackage);
13383                    pw.print(" (uid=");
13384                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13385                    pw.println(")");
13386                } else if (mRequiredVerifierPackage != null) {
13387                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13388                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13389                }
13390            }
13391
13392            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13393                    packageName == null) {
13394                if (mIntentFilterVerifierComponent != null) {
13395                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13396                    if (!checkin) {
13397                        if (dumpState.onTitlePrinted())
13398                            pw.println();
13399                        pw.println("Intent Filter Verifier:");
13400                        pw.print("  Using: ");
13401                        pw.print(verifierPackageName);
13402                        pw.print(" (uid=");
13403                        pw.print(getPackageUid(verifierPackageName, 0));
13404                        pw.println(")");
13405                    } else if (verifierPackageName != null) {
13406                        pw.print("ifv,"); pw.print(verifierPackageName);
13407                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13408                    }
13409                } else {
13410                    pw.println();
13411                    pw.println("No Intent Filter Verifier available!");
13412                }
13413            }
13414
13415            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13416                boolean printedHeader = false;
13417                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13418                while (it.hasNext()) {
13419                    String name = it.next();
13420                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13421                    if (!checkin) {
13422                        if (!printedHeader) {
13423                            if (dumpState.onTitlePrinted())
13424                                pw.println();
13425                            pw.println("Libraries:");
13426                            printedHeader = true;
13427                        }
13428                        pw.print("  ");
13429                    } else {
13430                        pw.print("lib,");
13431                    }
13432                    pw.print(name);
13433                    if (!checkin) {
13434                        pw.print(" -> ");
13435                    }
13436                    if (ent.path != null) {
13437                        if (!checkin) {
13438                            pw.print("(jar) ");
13439                            pw.print(ent.path);
13440                        } else {
13441                            pw.print(",jar,");
13442                            pw.print(ent.path);
13443                        }
13444                    } else {
13445                        if (!checkin) {
13446                            pw.print("(apk) ");
13447                            pw.print(ent.apk);
13448                        } else {
13449                            pw.print(",apk,");
13450                            pw.print(ent.apk);
13451                        }
13452                    }
13453                    pw.println();
13454                }
13455            }
13456
13457            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
13458                if (dumpState.onTitlePrinted())
13459                    pw.println();
13460                if (!checkin) {
13461                    pw.println("Features:");
13462                }
13463                Iterator<String> it = mAvailableFeatures.keySet().iterator();
13464                while (it.hasNext()) {
13465                    String name = it.next();
13466                    if (!checkin) {
13467                        pw.print("  ");
13468                    } else {
13469                        pw.print("feat,");
13470                    }
13471                    pw.println(name);
13472                }
13473            }
13474
13475            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
13476                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
13477                        : "Activity Resolver Table:", "  ", packageName,
13478                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13479                    dumpState.setTitlePrinted(true);
13480                }
13481                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
13482                        : "Receiver Resolver Table:", "  ", packageName,
13483                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13484                    dumpState.setTitlePrinted(true);
13485                }
13486                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
13487                        : "Service Resolver Table:", "  ", packageName,
13488                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13489                    dumpState.setTitlePrinted(true);
13490                }
13491                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
13492                        : "Provider Resolver Table:", "  ", packageName,
13493                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13494                    dumpState.setTitlePrinted(true);
13495                }
13496            }
13497
13498            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
13499                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13500                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13501                    int user = mSettings.mPreferredActivities.keyAt(i);
13502                    if (pir.dump(pw,
13503                            dumpState.getTitlePrinted()
13504                                ? "\nPreferred Activities User " + user + ":"
13505                                : "Preferred Activities User " + user + ":", "  ",
13506                            packageName, true, false)) {
13507                        dumpState.setTitlePrinted(true);
13508                    }
13509                }
13510            }
13511
13512            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
13513                pw.flush();
13514                FileOutputStream fout = new FileOutputStream(fd);
13515                BufferedOutputStream str = new BufferedOutputStream(fout);
13516                XmlSerializer serializer = new FastXmlSerializer();
13517                try {
13518                    serializer.setOutput(str, "utf-8");
13519                    serializer.startDocument(null, true);
13520                    serializer.setFeature(
13521                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
13522                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
13523                    serializer.endDocument();
13524                    serializer.flush();
13525                } catch (IllegalArgumentException e) {
13526                    pw.println("Failed writing: " + e);
13527                } catch (IllegalStateException e) {
13528                    pw.println("Failed writing: " + e);
13529                } catch (IOException e) {
13530                    pw.println("Failed writing: " + e);
13531                }
13532            }
13533
13534            if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) {
13535                pw.println();
13536                int count = mSettings.mPackages.size();
13537                if (count == 0) {
13538                    pw.println("No domain preferred apps!");
13539                    pw.println();
13540                } else {
13541                    final String prefix = "  ";
13542                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
13543                    if (allPackageSettings.size() == 0) {
13544                        pw.println("No domain preferred apps!");
13545                        pw.println();
13546                    } else {
13547                        pw.println("Domain preferred apps status:");
13548                        pw.println();
13549                        count = 0;
13550                        for (PackageSetting ps : allPackageSettings) {
13551                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13552                            if (ivi == null || ivi.getPackageName() == null) continue;
13553                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
13554                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
13555                            pw.println(prefix + "Status: " + ivi.getStatusString());
13556                            pw.println();
13557                            count++;
13558                        }
13559                        if (count == 0) {
13560                            pw.println(prefix + "No domain preferred app status!");
13561                            pw.println();
13562                        }
13563                        for (int userId : sUserManager.getUserIds()) {
13564                            pw.println("Domain preferred apps for User " + userId + ":");
13565                            pw.println();
13566                            count = 0;
13567                            for (PackageSetting ps : allPackageSettings) {
13568                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13569                                if (ivi == null || ivi.getPackageName() == null) {
13570                                    continue;
13571                                }
13572                                final int status = ps.getDomainVerificationStatusForUser(userId);
13573                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
13574                                    continue;
13575                                }
13576                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
13577                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
13578                                String statusStr = IntentFilterVerificationInfo.
13579                                        getStatusStringFromValue(status);
13580                                pw.println(prefix + "Status: " + statusStr);
13581                                pw.println();
13582                                count++;
13583                            }
13584                            if (count == 0) {
13585                                pw.println(prefix + "No domain preferred apps!");
13586                                pw.println();
13587                            }
13588                        }
13589                    }
13590                }
13591            }
13592
13593            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
13594                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
13595                if (packageName == null) {
13596                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
13597                        if (iperm == 0) {
13598                            if (dumpState.onTitlePrinted())
13599                                pw.println();
13600                            pw.println("AppOp Permissions:");
13601                        }
13602                        pw.print("  AppOp Permission ");
13603                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
13604                        pw.println(":");
13605                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
13606                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
13607                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
13608                        }
13609                    }
13610                }
13611            }
13612
13613            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
13614                boolean printedSomething = false;
13615                for (PackageParser.Provider p : mProviders.mProviders.values()) {
13616                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13617                        continue;
13618                    }
13619                    if (!printedSomething) {
13620                        if (dumpState.onTitlePrinted())
13621                            pw.println();
13622                        pw.println("Registered ContentProviders:");
13623                        printedSomething = true;
13624                    }
13625                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
13626                    pw.print("    "); pw.println(p.toString());
13627                }
13628                printedSomething = false;
13629                for (Map.Entry<String, PackageParser.Provider> entry :
13630                        mProvidersByAuthority.entrySet()) {
13631                    PackageParser.Provider p = entry.getValue();
13632                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13633                        continue;
13634                    }
13635                    if (!printedSomething) {
13636                        if (dumpState.onTitlePrinted())
13637                            pw.println();
13638                        pw.println("ContentProvider Authorities:");
13639                        printedSomething = true;
13640                    }
13641                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
13642                    pw.print("    "); pw.println(p.toString());
13643                    if (p.info != null && p.info.applicationInfo != null) {
13644                        final String appInfo = p.info.applicationInfo.toString();
13645                        pw.print("      applicationInfo="); pw.println(appInfo);
13646                    }
13647                }
13648            }
13649
13650            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
13651                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
13652            }
13653
13654            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
13655                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
13656            }
13657
13658            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
13659                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
13660            }
13661
13662            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
13663                // XXX should handle packageName != null by dumping only install data that
13664                // the given package is involved with.
13665                if (dumpState.onTitlePrinted()) pw.println();
13666                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
13667            }
13668
13669            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
13670                if (dumpState.onTitlePrinted()) pw.println();
13671                mSettings.dumpReadMessagesLPr(pw, dumpState);
13672
13673                pw.println();
13674                pw.println("Package warning messages:");
13675                BufferedReader in = null;
13676                String line = null;
13677                try {
13678                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
13679                    while ((line = in.readLine()) != null) {
13680                        if (line.contains("ignored: updated version")) continue;
13681                        pw.println(line);
13682                    }
13683                } catch (IOException ignored) {
13684                } finally {
13685                    IoUtils.closeQuietly(in);
13686                }
13687            }
13688
13689            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
13690                BufferedReader in = null;
13691                String line = null;
13692                try {
13693                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
13694                    while ((line = in.readLine()) != null) {
13695                        if (line.contains("ignored: updated version")) continue;
13696                        pw.print("msg,");
13697                        pw.println(line);
13698                    }
13699                } catch (IOException ignored) {
13700                } finally {
13701                    IoUtils.closeQuietly(in);
13702                }
13703            }
13704        }
13705    }
13706
13707    // ------- apps on sdcard specific code -------
13708    static final boolean DEBUG_SD_INSTALL = false;
13709
13710    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
13711
13712    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
13713
13714    private boolean mMediaMounted = false;
13715
13716    static String getEncryptKey() {
13717        try {
13718            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
13719                    SD_ENCRYPTION_KEYSTORE_NAME);
13720            if (sdEncKey == null) {
13721                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
13722                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
13723                if (sdEncKey == null) {
13724                    Slog.e(TAG, "Failed to create encryption keys");
13725                    return null;
13726                }
13727            }
13728            return sdEncKey;
13729        } catch (NoSuchAlgorithmException nsae) {
13730            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
13731            return null;
13732        } catch (IOException ioe) {
13733            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
13734            return null;
13735        }
13736    }
13737
13738    /*
13739     * Update media status on PackageManager.
13740     */
13741    @Override
13742    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
13743        int callingUid = Binder.getCallingUid();
13744        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
13745            throw new SecurityException("Media status can only be updated by the system");
13746        }
13747        // reader; this apparently protects mMediaMounted, but should probably
13748        // be a different lock in that case.
13749        synchronized (mPackages) {
13750            Log.i(TAG, "Updating external media status from "
13751                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
13752                    + (mediaStatus ? "mounted" : "unmounted"));
13753            if (DEBUG_SD_INSTALL)
13754                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
13755                        + ", mMediaMounted=" + mMediaMounted);
13756            if (mediaStatus == mMediaMounted) {
13757                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
13758                        : 0, -1);
13759                mHandler.sendMessage(msg);
13760                return;
13761            }
13762            mMediaMounted = mediaStatus;
13763        }
13764        // Queue up an async operation since the package installation may take a
13765        // little while.
13766        mHandler.post(new Runnable() {
13767            public void run() {
13768                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
13769            }
13770        });
13771    }
13772
13773    /**
13774     * Called by MountService when the initial ASECs to scan are available.
13775     * Should block until all the ASEC containers are finished being scanned.
13776     */
13777    public void scanAvailableAsecs() {
13778        updateExternalMediaStatusInner(true, false, false);
13779        if (mShouldRestoreconData) {
13780            SELinuxMMAC.setRestoreconDone();
13781            mShouldRestoreconData = false;
13782        }
13783    }
13784
13785    /*
13786     * Collect information of applications on external media, map them against
13787     * existing containers and update information based on current mount status.
13788     * Please note that we always have to report status if reportStatus has been
13789     * set to true especially when unloading packages.
13790     */
13791    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
13792            boolean externalStorage) {
13793        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
13794        int[] uidArr = EmptyArray.INT;
13795
13796        final String[] list = PackageHelper.getSecureContainerList();
13797        if (ArrayUtils.isEmpty(list)) {
13798            Log.i(TAG, "No secure containers found");
13799        } else {
13800            // Process list of secure containers and categorize them
13801            // as active or stale based on their package internal state.
13802
13803            // reader
13804            synchronized (mPackages) {
13805                for (String cid : list) {
13806                    // Leave stages untouched for now; installer service owns them
13807                    if (PackageInstallerService.isStageName(cid)) continue;
13808
13809                    if (DEBUG_SD_INSTALL)
13810                        Log.i(TAG, "Processing container " + cid);
13811                    String pkgName = getAsecPackageName(cid);
13812                    if (pkgName == null) {
13813                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
13814                        continue;
13815                    }
13816                    if (DEBUG_SD_INSTALL)
13817                        Log.i(TAG, "Looking for pkg : " + pkgName);
13818
13819                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
13820                    if (ps == null) {
13821                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
13822                        continue;
13823                    }
13824
13825                    /*
13826                     * Skip packages that are not external if we're unmounting
13827                     * external storage.
13828                     */
13829                    if (externalStorage && !isMounted && !isExternal(ps)) {
13830                        continue;
13831                    }
13832
13833                    final AsecInstallArgs args = new AsecInstallArgs(cid,
13834                            getAppDexInstructionSets(ps), ps.isForwardLocked());
13835                    // The package status is changed only if the code path
13836                    // matches between settings and the container id.
13837                    if (ps.codePathString != null
13838                            && ps.codePathString.startsWith(args.getCodePath())) {
13839                        if (DEBUG_SD_INSTALL) {
13840                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
13841                                    + " at code path: " + ps.codePathString);
13842                        }
13843
13844                        // We do have a valid package installed on sdcard
13845                        processCids.put(args, ps.codePathString);
13846                        final int uid = ps.appId;
13847                        if (uid != -1) {
13848                            uidArr = ArrayUtils.appendInt(uidArr, uid);
13849                        }
13850                    } else {
13851                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
13852                                + ps.codePathString);
13853                    }
13854                }
13855            }
13856
13857            Arrays.sort(uidArr);
13858        }
13859
13860        // Process packages with valid entries.
13861        if (isMounted) {
13862            if (DEBUG_SD_INSTALL)
13863                Log.i(TAG, "Loading packages");
13864            loadMediaPackages(processCids, uidArr);
13865            startCleaningPackages();
13866            mInstallerService.onSecureContainersAvailable();
13867        } else {
13868            if (DEBUG_SD_INSTALL)
13869                Log.i(TAG, "Unloading packages");
13870            unloadMediaPackages(processCids, uidArr, reportStatus);
13871        }
13872    }
13873
13874    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13875            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
13876        final int size = infos.size();
13877        final String[] packageNames = new String[size];
13878        final int[] packageUids = new int[size];
13879        for (int i = 0; i < size; i++) {
13880            final ApplicationInfo info = infos.get(i);
13881            packageNames[i] = info.packageName;
13882            packageUids[i] = info.uid;
13883        }
13884        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
13885                finishedReceiver);
13886    }
13887
13888    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13889            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
13890        sendResourcesChangedBroadcast(mediaStatus, replacing,
13891                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
13892    }
13893
13894    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13895            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
13896        int size = pkgList.length;
13897        if (size > 0) {
13898            // Send broadcasts here
13899            Bundle extras = new Bundle();
13900            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13901            if (uidArr != null) {
13902                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
13903            }
13904            if (replacing) {
13905                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
13906            }
13907            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
13908                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
13909            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
13910        }
13911    }
13912
13913   /*
13914     * Look at potentially valid container ids from processCids If package
13915     * information doesn't match the one on record or package scanning fails,
13916     * the cid is added to list of removeCids. We currently don't delete stale
13917     * containers.
13918     */
13919    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
13920        ArrayList<String> pkgList = new ArrayList<String>();
13921        Set<AsecInstallArgs> keys = processCids.keySet();
13922
13923        for (AsecInstallArgs args : keys) {
13924            String codePath = processCids.get(args);
13925            if (DEBUG_SD_INSTALL)
13926                Log.i(TAG, "Loading container : " + args.cid);
13927            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13928            try {
13929                // Make sure there are no container errors first.
13930                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
13931                    Slog.e(TAG, "Failed to mount cid : " + args.cid
13932                            + " when installing from sdcard");
13933                    continue;
13934                }
13935                // Check code path here.
13936                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
13937                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
13938                            + " does not match one in settings " + codePath);
13939                    continue;
13940                }
13941                // Parse package
13942                int parseFlags = mDefParseFlags;
13943                if (args.isExternalAsec()) {
13944                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
13945                }
13946                if (args.isFwdLocked()) {
13947                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
13948                }
13949
13950                synchronized (mInstallLock) {
13951                    PackageParser.Package pkg = null;
13952                    try {
13953                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
13954                    } catch (PackageManagerException e) {
13955                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
13956                    }
13957                    // Scan the package
13958                    if (pkg != null) {
13959                        /*
13960                         * TODO why is the lock being held? doPostInstall is
13961                         * called in other places without the lock. This needs
13962                         * to be straightened out.
13963                         */
13964                        // writer
13965                        synchronized (mPackages) {
13966                            retCode = PackageManager.INSTALL_SUCCEEDED;
13967                            pkgList.add(pkg.packageName);
13968                            // Post process args
13969                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
13970                                    pkg.applicationInfo.uid);
13971                        }
13972                    } else {
13973                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
13974                    }
13975                }
13976
13977            } finally {
13978                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
13979                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
13980                }
13981            }
13982        }
13983        // writer
13984        synchronized (mPackages) {
13985            // If the platform SDK has changed since the last time we booted,
13986            // we need to re-grant app permission to catch any new ones that
13987            // appear. This is really a hack, and means that apps can in some
13988            // cases get permissions that the user didn't initially explicitly
13989            // allow... it would be nice to have some better way to handle
13990            // this situation.
13991            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
13992            if (regrantPermissions)
13993                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
13994                        + mSdkVersion + "; regranting permissions for external storage");
13995            mSettings.mExternalSdkPlatform = mSdkVersion;
13996
13997            // Make sure group IDs have been assigned, and any permission
13998            // changes in other apps are accounted for
13999            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14000                    | (regrantPermissions
14001                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14002                            : 0));
14003
14004            mSettings.updateExternalDatabaseVersion();
14005
14006            // can downgrade to reader
14007            // Persist settings
14008            mSettings.writeLPr();
14009        }
14010        // Send a broadcast to let everyone know we are done processing
14011        if (pkgList.size() > 0) {
14012            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14013        }
14014    }
14015
14016   /*
14017     * Utility method to unload a list of specified containers
14018     */
14019    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14020        // Just unmount all valid containers.
14021        for (AsecInstallArgs arg : cidArgs) {
14022            synchronized (mInstallLock) {
14023                arg.doPostDeleteLI(false);
14024           }
14025       }
14026   }
14027
14028    /*
14029     * Unload packages mounted on external media. This involves deleting package
14030     * data from internal structures, sending broadcasts about diabled packages,
14031     * gc'ing to free up references, unmounting all secure containers
14032     * corresponding to packages on external media, and posting a
14033     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14034     * that we always have to post this message if status has been requested no
14035     * matter what.
14036     */
14037    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14038            final boolean reportStatus) {
14039        if (DEBUG_SD_INSTALL)
14040            Log.i(TAG, "unloading media packages");
14041        ArrayList<String> pkgList = new ArrayList<String>();
14042        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14043        final Set<AsecInstallArgs> keys = processCids.keySet();
14044        for (AsecInstallArgs args : keys) {
14045            String pkgName = args.getPackageName();
14046            if (DEBUG_SD_INSTALL)
14047                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14048            // Delete package internally
14049            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14050            synchronized (mInstallLock) {
14051                boolean res = deletePackageLI(pkgName, null, false, null, null,
14052                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14053                if (res) {
14054                    pkgList.add(pkgName);
14055                } else {
14056                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14057                    failedList.add(args);
14058                }
14059            }
14060        }
14061
14062        // reader
14063        synchronized (mPackages) {
14064            // We didn't update the settings after removing each package;
14065            // write them now for all packages.
14066            mSettings.writeLPr();
14067        }
14068
14069        // We have to absolutely send UPDATED_MEDIA_STATUS only
14070        // after confirming that all the receivers processed the ordered
14071        // broadcast when packages get disabled, force a gc to clean things up.
14072        // and unload all the containers.
14073        if (pkgList.size() > 0) {
14074            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14075                    new IIntentReceiver.Stub() {
14076                public void performReceive(Intent intent, int resultCode, String data,
14077                        Bundle extras, boolean ordered, boolean sticky,
14078                        int sendingUser) throws RemoteException {
14079                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14080                            reportStatus ? 1 : 0, 1, keys);
14081                    mHandler.sendMessage(msg);
14082                }
14083            });
14084        } else {
14085            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14086                    keys);
14087            mHandler.sendMessage(msg);
14088        }
14089    }
14090
14091    private void loadPrivatePackages(VolumeInfo vol) {
14092        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14093        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14094        synchronized (mPackages) {
14095            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14096            for (PackageSetting ps : packages) {
14097                synchronized (mInstallLock) {
14098                    final PackageParser.Package pkg;
14099                    try {
14100                        pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14101                        loaded.add(pkg.applicationInfo);
14102                    } catch (PackageManagerException e) {
14103                        Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14104                    }
14105                }
14106            }
14107
14108            // TODO: regrant any permissions that changed based since original install
14109
14110            mSettings.writeLPr();
14111        }
14112
14113        Slog.d(TAG, "Loaded packages " + loaded);
14114        sendResourcesChangedBroadcast(true, false, loaded, null);
14115    }
14116
14117    private void unloadPrivatePackages(VolumeInfo vol) {
14118        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14119        synchronized (mPackages) {
14120            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14121            for (PackageSetting ps : packages) {
14122                if (ps.pkg == null) continue;
14123                synchronized (mInstallLock) {
14124                    final ApplicationInfo info = ps.pkg.applicationInfo;
14125                    final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14126                    if (deletePackageLI(ps.name, null, false, null, null,
14127                            PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14128                        unloaded.add(info);
14129                    } else {
14130                        Slog.w(TAG, "Failed to unload " + ps.codePath);
14131                    }
14132                }
14133            }
14134
14135            mSettings.writeLPr();
14136        }
14137
14138        Slog.d(TAG, "Unloaded packages " + unloaded);
14139        sendResourcesChangedBroadcast(false, false, unloaded, null);
14140    }
14141
14142    @Override
14143    public void movePackage(final String packageName, final IPackageMoveObserver observer,
14144            final int flags) {
14145        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14146
14147        final int installFlags;
14148        if ((flags & MOVE_INTERNAL) != 0) {
14149            installFlags = INSTALL_INTERNAL;
14150        } else if ((flags & MOVE_EXTERNAL_MEDIA) != 0) {
14151            installFlags = INSTALL_EXTERNAL;
14152        } else {
14153            throw new IllegalArgumentException("Unsupported move flags " + flags);
14154        }
14155
14156        try {
14157            movePackageInternal(packageName, null, installFlags, false, observer);
14158        } catch (PackageManagerException e) {
14159            Slog.d(TAG, "Failed to move " + packageName, e);
14160            try {
14161                observer.packageMoved(packageName, e.error);
14162            } catch (RemoteException ignored) {
14163            }
14164        }
14165    }
14166
14167    @Override
14168    public void movePackageAndData(final String packageName, final String volumeUuid,
14169            final IPackageMoveObserver observer) {
14170        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14171        try {
14172            movePackageInternal(packageName, volumeUuid, INSTALL_INTERNAL, true, observer);
14173        } catch (PackageManagerException e) {
14174            Slog.d(TAG, "Failed to move " + packageName, e);
14175            try {
14176                observer.packageMoved(packageName, e.error);
14177            } catch (RemoteException ignored) {
14178            }
14179        }
14180    }
14181
14182    private void movePackageInternal(final String packageName, String volumeUuid, int installFlags,
14183            boolean andData, final IPackageMoveObserver observer) throws PackageManagerException {
14184        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14185
14186        File codeFile = null;
14187        String installerPackageName = null;
14188        String packageAbiOverride = null;
14189
14190        // TOOD: move app private data before installing
14191
14192        // reader
14193        synchronized (mPackages) {
14194            final PackageParser.Package pkg = mPackages.get(packageName);
14195            final PackageSetting ps = mSettings.mPackages.get(packageName);
14196            if (pkg == null || ps == null) {
14197                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14198            }
14199
14200            if (pkg.applicationInfo.isSystemApp()) {
14201                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14202                        "Cannot move system application");
14203            } else if (pkg.mOperationPending) {
14204                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14205                        "Attempt to move package which has pending operations");
14206            }
14207
14208            // TODO: yell if already in desired location
14209
14210            pkg.mOperationPending = true;
14211
14212            codeFile = new File(pkg.codePath);
14213            installerPackageName = ps.installerPackageName;
14214            packageAbiOverride = ps.cpuAbiOverrideString;
14215        }
14216
14217        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14218            @Override
14219            public void onUserActionRequired(Intent intent) throws RemoteException {
14220                throw new IllegalStateException();
14221            }
14222
14223            @Override
14224            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14225                    Bundle extras) throws RemoteException {
14226                Slog.d(TAG, "Install result for move: "
14227                        + PackageManager.installStatusToString(returnCode, msg));
14228
14229                // We usually have a new package now after the install, but if
14230                // we failed we need to clear the pending flag on the original
14231                // package object.
14232                synchronized (mPackages) {
14233                    final PackageParser.Package pkg = mPackages.get(packageName);
14234                    if (pkg != null) {
14235                        pkg.mOperationPending = false;
14236                    }
14237                }
14238
14239                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14240                switch (status) {
14241                    case PackageInstaller.STATUS_SUCCESS:
14242                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
14243                        break;
14244                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14245                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14246                        break;
14247                    default:
14248                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14249                        break;
14250                }
14251            }
14252        };
14253
14254        // Treat a move like reinstalling an existing app, which ensures that we
14255        // process everythign uniformly, like unpacking native libraries.
14256        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14257
14258        final Message msg = mHandler.obtainMessage(INIT_COPY);
14259        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14260        msg.obj = new InstallParams(origin, installObserver, installFlags,
14261                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14262        mHandler.sendMessage(msg);
14263    }
14264
14265    @Override
14266    public boolean setInstallLocation(int loc) {
14267        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14268                null);
14269        if (getInstallLocation() == loc) {
14270            return true;
14271        }
14272        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14273                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14274            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14275                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14276            return true;
14277        }
14278        return false;
14279   }
14280
14281    @Override
14282    public int getInstallLocation() {
14283        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14284                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14285                PackageHelper.APP_INSTALL_AUTO);
14286    }
14287
14288    /** Called by UserManagerService */
14289    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14290        mDirtyUsers.remove(userHandle);
14291        mSettings.removeUserLPw(userHandle);
14292        mPendingBroadcasts.remove(userHandle);
14293        if (mInstaller != null) {
14294            // Technically, we shouldn't be doing this with the package lock
14295            // held.  However, this is very rare, and there is already so much
14296            // other disk I/O going on, that we'll let it slide for now.
14297            mInstaller.removeUserDataDirs(userHandle);
14298        }
14299        mUserNeedsBadging.delete(userHandle);
14300        removeUnusedPackagesLILPw(userManager, userHandle);
14301    }
14302
14303    /**
14304     * We're removing userHandle and would like to remove any downloaded packages
14305     * that are no longer in use by any other user.
14306     * @param userHandle the user being removed
14307     */
14308    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
14309        final boolean DEBUG_CLEAN_APKS = false;
14310        int [] users = userManager.getUserIdsLPr();
14311        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
14312        while (psit.hasNext()) {
14313            PackageSetting ps = psit.next();
14314            if (ps.pkg == null) {
14315                continue;
14316            }
14317            final String packageName = ps.pkg.packageName;
14318            // Skip over if system app
14319            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14320                continue;
14321            }
14322            if (DEBUG_CLEAN_APKS) {
14323                Slog.i(TAG, "Checking package " + packageName);
14324            }
14325            boolean keep = false;
14326            for (int i = 0; i < users.length; i++) {
14327                if (users[i] != userHandle && ps.getInstalled(users[i])) {
14328                    keep = true;
14329                    if (DEBUG_CLEAN_APKS) {
14330                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
14331                                + users[i]);
14332                    }
14333                    break;
14334                }
14335            }
14336            if (!keep) {
14337                if (DEBUG_CLEAN_APKS) {
14338                    Slog.i(TAG, "  Removing package " + packageName);
14339                }
14340                mHandler.post(new Runnable() {
14341                    public void run() {
14342                        deletePackageX(packageName, userHandle, 0);
14343                    } //end run
14344                });
14345            }
14346        }
14347    }
14348
14349    /** Called by UserManagerService */
14350    void createNewUserLILPw(int userHandle, File path) {
14351        if (mInstaller != null) {
14352            mInstaller.createUserConfig(userHandle);
14353            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
14354        }
14355    }
14356
14357    void newUserCreatedLILPw(int userHandle) {
14358        // Adding a user requires updating runtime permissions for system apps.
14359        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
14360    }
14361
14362    @Override
14363    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
14364        mContext.enforceCallingOrSelfPermission(
14365                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14366                "Only package verification agents can read the verifier device identity");
14367
14368        synchronized (mPackages) {
14369            return mSettings.getVerifierDeviceIdentityLPw();
14370        }
14371    }
14372
14373    @Override
14374    public void setPermissionEnforced(String permission, boolean enforced) {
14375        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
14376        if (READ_EXTERNAL_STORAGE.equals(permission)) {
14377            synchronized (mPackages) {
14378                if (mSettings.mReadExternalStorageEnforced == null
14379                        || mSettings.mReadExternalStorageEnforced != enforced) {
14380                    mSettings.mReadExternalStorageEnforced = enforced;
14381                    mSettings.writeLPr();
14382                }
14383            }
14384            // kill any non-foreground processes so we restart them and
14385            // grant/revoke the GID.
14386            final IActivityManager am = ActivityManagerNative.getDefault();
14387            if (am != null) {
14388                final long token = Binder.clearCallingIdentity();
14389                try {
14390                    am.killProcessesBelowForeground("setPermissionEnforcement");
14391                } catch (RemoteException e) {
14392                } finally {
14393                    Binder.restoreCallingIdentity(token);
14394                }
14395            }
14396        } else {
14397            throw new IllegalArgumentException("No selective enforcement for " + permission);
14398        }
14399    }
14400
14401    @Override
14402    @Deprecated
14403    public boolean isPermissionEnforced(String permission) {
14404        return true;
14405    }
14406
14407    @Override
14408    public boolean isStorageLow() {
14409        final long token = Binder.clearCallingIdentity();
14410        try {
14411            final DeviceStorageMonitorInternal
14412                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14413            if (dsm != null) {
14414                return dsm.isMemoryLow();
14415            } else {
14416                return false;
14417            }
14418        } finally {
14419            Binder.restoreCallingIdentity(token);
14420        }
14421    }
14422
14423    @Override
14424    public IPackageInstaller getPackageInstaller() {
14425        return mInstallerService;
14426    }
14427
14428    private boolean userNeedsBadging(int userId) {
14429        int index = mUserNeedsBadging.indexOfKey(userId);
14430        if (index < 0) {
14431            final UserInfo userInfo;
14432            final long token = Binder.clearCallingIdentity();
14433            try {
14434                userInfo = sUserManager.getUserInfo(userId);
14435            } finally {
14436                Binder.restoreCallingIdentity(token);
14437            }
14438            final boolean b;
14439            if (userInfo != null && userInfo.isManagedProfile()) {
14440                b = true;
14441            } else {
14442                b = false;
14443            }
14444            mUserNeedsBadging.put(userId, b);
14445            return b;
14446        }
14447        return mUserNeedsBadging.valueAt(index);
14448    }
14449
14450    @Override
14451    public KeySet getKeySetByAlias(String packageName, String alias) {
14452        if (packageName == null || alias == null) {
14453            return null;
14454        }
14455        synchronized(mPackages) {
14456            final PackageParser.Package pkg = mPackages.get(packageName);
14457            if (pkg == null) {
14458                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14459                throw new IllegalArgumentException("Unknown package: " + packageName);
14460            }
14461            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14462            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
14463        }
14464    }
14465
14466    @Override
14467    public KeySet getSigningKeySet(String packageName) {
14468        if (packageName == null) {
14469            return null;
14470        }
14471        synchronized(mPackages) {
14472            final PackageParser.Package pkg = mPackages.get(packageName);
14473            if (pkg == null) {
14474                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14475                throw new IllegalArgumentException("Unknown package: " + packageName);
14476            }
14477            if (pkg.applicationInfo.uid != Binder.getCallingUid()
14478                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
14479                throw new SecurityException("May not access signing KeySet of other apps.");
14480            }
14481            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14482            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
14483        }
14484    }
14485
14486    @Override
14487    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
14488        if (packageName == null || ks == null) {
14489            return false;
14490        }
14491        synchronized(mPackages) {
14492            final PackageParser.Package pkg = mPackages.get(packageName);
14493            if (pkg == null) {
14494                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14495                throw new IllegalArgumentException("Unknown package: " + packageName);
14496            }
14497            IBinder ksh = ks.getToken();
14498            if (ksh instanceof KeySetHandle) {
14499                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14500                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
14501            }
14502            return false;
14503        }
14504    }
14505
14506    @Override
14507    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
14508        if (packageName == null || ks == null) {
14509            return false;
14510        }
14511        synchronized(mPackages) {
14512            final PackageParser.Package pkg = mPackages.get(packageName);
14513            if (pkg == null) {
14514                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14515                throw new IllegalArgumentException("Unknown package: " + packageName);
14516            }
14517            IBinder ksh = ks.getToken();
14518            if (ksh instanceof KeySetHandle) {
14519                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14520                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
14521            }
14522            return false;
14523        }
14524    }
14525
14526    public void getUsageStatsIfNoPackageUsageInfo() {
14527        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
14528            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
14529            if (usm == null) {
14530                throw new IllegalStateException("UsageStatsManager must be initialized");
14531            }
14532            long now = System.currentTimeMillis();
14533            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
14534            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
14535                String packageName = entry.getKey();
14536                PackageParser.Package pkg = mPackages.get(packageName);
14537                if (pkg == null) {
14538                    continue;
14539                }
14540                UsageStats usage = entry.getValue();
14541                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
14542                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
14543            }
14544        }
14545    }
14546
14547    /**
14548     * Check and throw if the given before/after packages would be considered a
14549     * downgrade.
14550     */
14551    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
14552            throws PackageManagerException {
14553        if (after.versionCode < before.mVersionCode) {
14554            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14555                    "Update version code " + after.versionCode + " is older than current "
14556                    + before.mVersionCode);
14557        } else if (after.versionCode == before.mVersionCode) {
14558            if (after.baseRevisionCode < before.baseRevisionCode) {
14559                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14560                        "Update base revision code " + after.baseRevisionCode
14561                        + " is older than current " + before.baseRevisionCode);
14562            }
14563
14564            if (!ArrayUtils.isEmpty(after.splitNames)) {
14565                for (int i = 0; i < after.splitNames.length; i++) {
14566                    final String splitName = after.splitNames[i];
14567                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
14568                    if (j != -1) {
14569                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
14570                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14571                                    "Update split " + splitName + " revision code "
14572                                    + after.splitRevisionCodes[i] + " is older than current "
14573                                    + before.splitRevisionCodes[j]);
14574                        }
14575                    }
14576                }
14577            }
14578        }
14579    }
14580}
14581