PackageManagerService.java revision a408061cc7b5efaf090ce9efd5fd0ba1d95e9c11
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.MATCH_ALL;
53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
57import static android.content.pm.PackageParser.isApkFile;
58import static android.os.Process.FIRST_APPLICATION_UID;
59import static android.os.Process.PACKAGE_INFO_GID;
60import static android.os.Process.SYSTEM_UID;
61import static android.system.OsConstants.O_CREAT;
62import static android.system.OsConstants.O_RDWR;
63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
65import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
66import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
67import static com.android.internal.util.ArrayUtils.appendInt;
68import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
71import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
72import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
73
74import android.Manifest;
75import android.app.ActivityManager;
76import android.app.ActivityManagerNative;
77import android.app.AppGlobals;
78import android.app.IActivityManager;
79import android.app.admin.IDevicePolicyManager;
80import android.app.backup.IBackupManager;
81import android.app.usage.UsageStats;
82import android.app.usage.UsageStatsManager;
83import android.content.BroadcastReceiver;
84import android.content.ComponentName;
85import android.content.Context;
86import android.content.IIntentReceiver;
87import android.content.Intent;
88import android.content.IntentFilter;
89import android.content.IntentSender;
90import android.content.IntentSender.SendIntentException;
91import android.content.ServiceConnection;
92import android.content.pm.ActivityInfo;
93import android.content.pm.ApplicationInfo;
94import android.content.pm.FeatureInfo;
95import android.content.pm.IOnPermissionsChangeListener;
96import android.content.pm.IPackageDataObserver;
97import android.content.pm.IPackageDeleteObserver;
98import android.content.pm.IPackageDeleteObserver2;
99import android.content.pm.IPackageInstallObserver2;
100import android.content.pm.IPackageInstaller;
101import android.content.pm.IPackageManager;
102import android.content.pm.IPackageMoveObserver;
103import android.content.pm.IPackageStatsObserver;
104import android.content.pm.InstrumentationInfo;
105import android.content.pm.IntentFilterVerificationInfo;
106import android.content.pm.KeySet;
107import android.content.pm.ManifestDigest;
108import android.content.pm.PackageCleanItem;
109import android.content.pm.PackageInfo;
110import android.content.pm.PackageInfoLite;
111import android.content.pm.PackageInstaller;
112import android.content.pm.PackageManager;
113import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
114import android.content.pm.PackageParser;
115import android.content.pm.PackageParser.ActivityIntentInfo;
116import android.content.pm.PackageParser.PackageLite;
117import android.content.pm.PackageParser.PackageParserException;
118import android.content.pm.PackageStats;
119import android.content.pm.PackageUserState;
120import android.content.pm.ParceledListSlice;
121import android.content.pm.PermissionGroupInfo;
122import android.content.pm.PermissionInfo;
123import android.content.pm.ProviderInfo;
124import android.content.pm.ResolveInfo;
125import android.content.pm.ServiceInfo;
126import android.content.pm.Signature;
127import android.content.pm.UserInfo;
128import android.content.pm.VerificationParams;
129import android.content.pm.VerifierDeviceIdentity;
130import android.content.pm.VerifierInfo;
131import android.content.res.Resources;
132import android.hardware.display.DisplayManager;
133import android.net.Uri;
134import android.os.Binder;
135import android.os.Build;
136import android.os.Bundle;
137import android.os.Debug;
138import android.os.Environment;
139import android.os.Environment.UserEnvironment;
140import android.os.FileUtils;
141import android.os.Handler;
142import android.os.IBinder;
143import android.os.Looper;
144import android.os.Message;
145import android.os.Parcel;
146import android.os.ParcelFileDescriptor;
147import android.os.Process;
148import android.os.RemoteCallbackList;
149import android.os.RemoteException;
150import android.os.SELinux;
151import android.os.ServiceManager;
152import android.os.SystemClock;
153import android.os.SystemProperties;
154import android.os.UserHandle;
155import android.os.UserManager;
156import android.os.storage.IMountService;
157import android.os.storage.StorageEventListener;
158import android.os.storage.StorageManager;
159import android.os.storage.VolumeInfo;
160import android.os.storage.VolumeRecord;
161import android.security.KeyStore;
162import android.security.SystemKeyStore;
163import android.system.ErrnoException;
164import android.system.Os;
165import android.system.StructStat;
166import android.text.TextUtils;
167import android.text.format.DateUtils;
168import android.util.ArrayMap;
169import android.util.ArraySet;
170import android.util.AtomicFile;
171import android.util.DisplayMetrics;
172import android.util.EventLog;
173import android.util.ExceptionUtils;
174import android.util.Log;
175import android.util.LogPrinter;
176import android.util.MathUtils;
177import android.util.PrintStreamPrinter;
178import android.util.Slog;
179import android.util.SparseArray;
180import android.util.SparseBooleanArray;
181import android.util.SparseIntArray;
182import android.util.Xml;
183import android.view.Display;
184
185import dalvik.system.DexFile;
186import dalvik.system.VMRuntime;
187
188import libcore.io.IoUtils;
189import libcore.util.EmptyArray;
190
191import com.android.internal.R;
192import com.android.internal.app.IMediaContainerService;
193import com.android.internal.app.ResolverActivity;
194import com.android.internal.content.NativeLibraryHelper;
195import com.android.internal.content.PackageHelper;
196import com.android.internal.os.IParcelFileDescriptorFactory;
197import com.android.internal.os.SomeArgs;
198import com.android.internal.util.ArrayUtils;
199import com.android.internal.util.FastPrintWriter;
200import com.android.internal.util.FastXmlSerializer;
201import com.android.internal.util.IndentingPrintWriter;
202import com.android.internal.util.Preconditions;
203import com.android.server.EventLogTags;
204import com.android.server.FgThread;
205import com.android.server.IntentResolver;
206import com.android.server.LocalServices;
207import com.android.server.ServiceThread;
208import com.android.server.SystemConfig;
209import com.android.server.Watchdog;
210import com.android.server.pm.Settings.DatabaseVersion;
211import com.android.server.pm.PermissionsState.PermissionState;
212import com.android.server.storage.DeviceStorageMonitorInternal;
213
214import org.xmlpull.v1.XmlPullParser;
215import org.xmlpull.v1.XmlSerializer;
216
217import java.io.BufferedInputStream;
218import java.io.BufferedOutputStream;
219import java.io.BufferedReader;
220import java.io.ByteArrayInputStream;
221import java.io.ByteArrayOutputStream;
222import java.io.File;
223import java.io.FileDescriptor;
224import java.io.FileNotFoundException;
225import java.io.FileOutputStream;
226import java.io.FileReader;
227import java.io.FilenameFilter;
228import java.io.IOException;
229import java.io.InputStream;
230import java.io.PrintWriter;
231import java.nio.charset.StandardCharsets;
232import java.security.NoSuchAlgorithmException;
233import java.security.PublicKey;
234import java.security.cert.CertificateEncodingException;
235import java.security.cert.CertificateException;
236import java.text.SimpleDateFormat;
237import java.util.ArrayList;
238import java.util.Arrays;
239import java.util.Collection;
240import java.util.Collections;
241import java.util.Comparator;
242import java.util.Date;
243import java.util.Iterator;
244import java.util.List;
245import java.util.Map;
246import java.util.Objects;
247import java.util.Set;
248import java.util.concurrent.CountDownLatch;
249import java.util.concurrent.TimeUnit;
250import java.util.concurrent.atomic.AtomicBoolean;
251import java.util.concurrent.atomic.AtomicInteger;
252import java.util.concurrent.atomic.AtomicLong;
253
254/**
255 * Keep track of all those .apks everywhere.
256 *
257 * This is very central to the platform's security; please run the unit
258 * tests whenever making modifications here:
259 *
260mmm frameworks/base/tests/AndroidTests
261adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
262adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
263 *
264 * {@hide}
265 */
266public class PackageManagerService extends IPackageManager.Stub {
267    static final String TAG = "PackageManager";
268    static final boolean DEBUG_SETTINGS = false;
269    static final boolean DEBUG_PREFERRED = false;
270    static final boolean DEBUG_UPGRADE = false;
271    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
272    private static final boolean DEBUG_BACKUP = true;
273    private static final boolean DEBUG_INSTALL = false;
274    private static final boolean DEBUG_REMOVE = false;
275    private static final boolean DEBUG_BROADCASTS = false;
276    private static final boolean DEBUG_SHOW_INFO = false;
277    private static final boolean DEBUG_PACKAGE_INFO = false;
278    private static final boolean DEBUG_INTENT_MATCHING = false;
279    private static final boolean DEBUG_PACKAGE_SCANNING = false;
280    private static final boolean DEBUG_VERIFY = false;
281    private static final boolean DEBUG_DEXOPT = false;
282    private static final boolean DEBUG_ABI_SELECTION = false;
283
284    private static final int RADIO_UID = Process.PHONE_UID;
285    private static final int LOG_UID = Process.LOG_UID;
286    private static final int NFC_UID = Process.NFC_UID;
287    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
288    private static final int SHELL_UID = Process.SHELL_UID;
289
290    // Cap the size of permission trees that 3rd party apps can define
291    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
292
293    // Suffix used during package installation when copying/moving
294    // package apks to install directory.
295    private static final String INSTALL_PACKAGE_SUFFIX = "-";
296
297    static final int SCAN_NO_DEX = 1<<1;
298    static final int SCAN_FORCE_DEX = 1<<2;
299    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
300    static final int SCAN_NEW_INSTALL = 1<<4;
301    static final int SCAN_NO_PATHS = 1<<5;
302    static final int SCAN_UPDATE_TIME = 1<<6;
303    static final int SCAN_DEFER_DEX = 1<<7;
304    static final int SCAN_BOOTING = 1<<8;
305    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
306    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
307    static final int SCAN_REQUIRE_KNOWN = 1<<12;
308    static final int SCAN_MOVE = 1<<13;
309
310    static final int REMOVE_CHATTY = 1<<16;
311
312    private static final int[] EMPTY_INT_ARRAY = new int[0];
313
314    /**
315     * Timeout (in milliseconds) after which the watchdog should declare that
316     * our handler thread is wedged.  The usual default for such things is one
317     * minute but we sometimes do very lengthy I/O operations on this thread,
318     * such as installing multi-gigabyte applications, so ours needs to be longer.
319     */
320    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
321
322    /**
323     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
324     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
325     * settings entry if available, otherwise we use the hardcoded default.  If it's been
326     * more than this long since the last fstrim, we force one during the boot sequence.
327     *
328     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
329     * one gets run at the next available charging+idle time.  This final mandatory
330     * no-fstrim check kicks in only of the other scheduling criteria is never met.
331     */
332    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
333
334    /**
335     * Whether verification is enabled by default.
336     */
337    private static final boolean DEFAULT_VERIFY_ENABLE = true;
338
339    /**
340     * The default maximum time to wait for the verification agent to return in
341     * milliseconds.
342     */
343    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
344
345    /**
346     * The default response for package verification timeout.
347     *
348     * This can be either PackageManager.VERIFICATION_ALLOW or
349     * PackageManager.VERIFICATION_REJECT.
350     */
351    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
352
353    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
354
355    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
356            DEFAULT_CONTAINER_PACKAGE,
357            "com.android.defcontainer.DefaultContainerService");
358
359    private static final String KILL_APP_REASON_GIDS_CHANGED =
360            "permission grant or revoke changed gids";
361
362    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
363            "permissions revoked";
364
365    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
366
367    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
368
369    /** Permission grant: not grant the permission. */
370    private static final int GRANT_DENIED = 1;
371
372    /** Permission grant: grant the permission as an install permission. */
373    private static final int GRANT_INSTALL = 2;
374
375    /** Permission grant: grant the permission as an install permission for a legacy app. */
376    private static final int GRANT_INSTALL_LEGACY = 3;
377
378    /** Permission grant: grant the permission as a runtime one. */
379    private static final int GRANT_RUNTIME = 4;
380
381    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
382    private static final int GRANT_UPGRADE = 5;
383
384    final ServiceThread mHandlerThread;
385
386    final PackageHandler mHandler;
387
388    /**
389     * Messages for {@link #mHandler} that need to wait for system ready before
390     * being dispatched.
391     */
392    private ArrayList<Message> mPostSystemReadyMessages;
393
394    final int mSdkVersion = Build.VERSION.SDK_INT;
395
396    final Context mContext;
397    final boolean mFactoryTest;
398    final boolean mOnlyCore;
399    final boolean mLazyDexOpt;
400    final long mDexOptLRUThresholdInMills;
401    final DisplayMetrics mMetrics;
402    final int mDefParseFlags;
403    final String[] mSeparateProcesses;
404    final boolean mIsUpgrade;
405
406    // This is where all application persistent data goes.
407    final File mAppDataDir;
408
409    // This is where all application persistent data goes for secondary users.
410    final File mUserAppDataDir;
411
412    /** The location for ASEC container files on internal storage. */
413    final String mAsecInternalPath;
414
415    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
416    // LOCK HELD.  Can be called with mInstallLock held.
417    final Installer mInstaller;
418
419    /** Directory where installed third-party apps stored */
420    final File mAppInstallDir;
421
422    /**
423     * Directory to which applications installed internally have their
424     * 32 bit native libraries copied.
425     */
426    private File mAppLib32InstallDir;
427
428    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
429    // apps.
430    final File mDrmAppPrivateInstallDir;
431
432    // ----------------------------------------------------------------
433
434    // Lock for state used when installing and doing other long running
435    // operations.  Methods that must be called with this lock held have
436    // the suffix "LI".
437    final Object mInstallLock = new Object();
438
439    // ----------------------------------------------------------------
440
441    // Keys are String (package name), values are Package.  This also serves
442    // as the lock for the global state.  Methods that must be called with
443    // this lock held have the prefix "LP".
444    final ArrayMap<String, PackageParser.Package> mPackages =
445            new ArrayMap<String, PackageParser.Package>();
446
447    // Tracks available target package names -> overlay package paths.
448    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
449        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
450
451    final Settings mSettings;
452    boolean mRestoredSettings;
453
454    // System configuration read by SystemConfig.
455    final int[] mGlobalGids;
456    final SparseArray<ArraySet<String>> mSystemPermissions;
457    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
458
459    // If mac_permissions.xml was found for seinfo labeling.
460    boolean mFoundPolicyFile;
461
462    // If a recursive restorecon of /data/data/<pkg> is needed.
463    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
464
465    public static final class SharedLibraryEntry {
466        public final String path;
467        public final String apk;
468
469        SharedLibraryEntry(String _path, String _apk) {
470            path = _path;
471            apk = _apk;
472        }
473    }
474
475    // Currently known shared libraries.
476    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
477            new ArrayMap<String, SharedLibraryEntry>();
478
479    // All available activities, for your resolving pleasure.
480    final ActivityIntentResolver mActivities =
481            new ActivityIntentResolver();
482
483    // All available receivers, for your resolving pleasure.
484    final ActivityIntentResolver mReceivers =
485            new ActivityIntentResolver();
486
487    // All available services, for your resolving pleasure.
488    final ServiceIntentResolver mServices = new ServiceIntentResolver();
489
490    // All available providers, for your resolving pleasure.
491    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
492
493    // Mapping from provider base names (first directory in content URI codePath)
494    // to the provider information.
495    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
496            new ArrayMap<String, PackageParser.Provider>();
497
498    // Mapping from instrumentation class names to info about them.
499    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
500            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
501
502    // Mapping from permission names to info about them.
503    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
504            new ArrayMap<String, PackageParser.PermissionGroup>();
505
506    // Packages whose data we have transfered into another package, thus
507    // should no longer exist.
508    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
509
510    // Broadcast actions that are only available to the system.
511    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
512
513    /** List of packages waiting for verification. */
514    final SparseArray<PackageVerificationState> mPendingVerification
515            = new SparseArray<PackageVerificationState>();
516
517    /** Set of packages associated with each app op permission. */
518    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
519
520    final PackageInstallerService mInstallerService;
521
522    private final PackageDexOptimizer mPackageDexOptimizer;
523
524    private AtomicInteger mNextMoveId = new AtomicInteger();
525    private final MoveCallbacks mMoveCallbacks;
526
527    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
528
529    // Cache of users who need badging.
530    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
531
532    /** Token for keys in mPendingVerification. */
533    private int mPendingVerificationToken = 0;
534
535    volatile boolean mSystemReady;
536    volatile boolean mSafeMode;
537    volatile boolean mHasSystemUidErrors;
538
539    ApplicationInfo mAndroidApplication;
540    final ActivityInfo mResolveActivity = new ActivityInfo();
541    final ResolveInfo mResolveInfo = new ResolveInfo();
542    ComponentName mResolveComponentName;
543    PackageParser.Package mPlatformPackage;
544    ComponentName mCustomResolverComponentName;
545
546    boolean mResolverReplaced = false;
547
548    private final ComponentName mIntentFilterVerifierComponent;
549    private int mIntentFilterVerificationToken = 0;
550
551    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
552            = new SparseArray<IntentFilterVerificationState>();
553
554    private interface IntentFilterVerifier<T extends IntentFilter> {
555        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
556                                               T filter, String packageName);
557        void startVerifications(int userId);
558        void receiveVerificationResponse(int verificationId);
559    }
560
561    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
562        private Context mContext;
563        private ComponentName mIntentFilterVerifierComponent;
564        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
565
566        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
567            mContext = context;
568            mIntentFilterVerifierComponent = verifierComponent;
569        }
570
571        private String getDefaultScheme() {
572            return IntentFilter.SCHEME_HTTPS;
573        }
574
575        @Override
576        public void startVerifications(int userId) {
577            // Launch verifications requests
578            int count = mCurrentIntentFilterVerifications.size();
579            for (int n=0; n<count; n++) {
580                int verificationId = mCurrentIntentFilterVerifications.get(n);
581                final IntentFilterVerificationState ivs =
582                        mIntentFilterVerificationStates.get(verificationId);
583
584                String packageName = ivs.getPackageName();
585
586                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
587                final int filterCount = filters.size();
588                ArraySet<String> domainsSet = new ArraySet<>();
589                for (int m=0; m<filterCount; m++) {
590                    PackageParser.ActivityIntentInfo filter = filters.get(m);
591                    domainsSet.addAll(filter.getHostsList());
592                }
593                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
594                synchronized (mPackages) {
595                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
596                            packageName, domainsList) != null) {
597                        scheduleWriteSettingsLocked();
598                    }
599                }
600                sendVerificationRequest(userId, verificationId, ivs);
601            }
602            mCurrentIntentFilterVerifications.clear();
603        }
604
605        private void sendVerificationRequest(int userId, int verificationId,
606                IntentFilterVerificationState ivs) {
607
608            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
609            verificationIntent.putExtra(
610                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
611                    verificationId);
612            verificationIntent.putExtra(
613                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
614                    getDefaultScheme());
615            verificationIntent.putExtra(
616                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
617                    ivs.getHostsString());
618            verificationIntent.putExtra(
619                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
620                    ivs.getPackageName());
621            verificationIntent.setComponent(mIntentFilterVerifierComponent);
622            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
623
624            UserHandle user = new UserHandle(userId);
625            mContext.sendBroadcastAsUser(verificationIntent, user);
626            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
627                    "Sending IntenFilter verification broadcast");
628        }
629
630        public void receiveVerificationResponse(int verificationId) {
631            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
632
633            final boolean verified = ivs.isVerified();
634
635            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
636            final int count = filters.size();
637            for (int n=0; n<count; n++) {
638                PackageParser.ActivityIntentInfo filter = filters.get(n);
639                filter.setVerified(verified);
640
641                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
642                        + " verified with result:" + verified + " and hosts:"
643                        + ivs.getHostsString());
644            }
645
646            mIntentFilterVerificationStates.remove(verificationId);
647
648            final String packageName = ivs.getPackageName();
649            IntentFilterVerificationInfo ivi = null;
650
651            synchronized (mPackages) {
652                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
653            }
654            if (ivi == null) {
655                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
656                        + verificationId + " packageName:" + packageName);
657                return;
658            }
659            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
660                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
661
662            synchronized (mPackages) {
663                if (verified) {
664                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
665                } else {
666                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
667                }
668                scheduleWriteSettingsLocked();
669
670                final int userId = ivs.getUserId();
671                if (userId != UserHandle.USER_ALL) {
672                    final int userStatus =
673                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
674
675                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
676                    boolean needUpdate = false;
677
678                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
679                    // already been set by the User thru the Disambiguation dialog
680                    switch (userStatus) {
681                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
682                            if (verified) {
683                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
684                            } else {
685                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
686                            }
687                            needUpdate = true;
688                            break;
689
690                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
691                            if (verified) {
692                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
693                                needUpdate = true;
694                            }
695                            break;
696
697                        default:
698                            // Nothing to do
699                    }
700
701                    if (needUpdate) {
702                        mSettings.updateIntentFilterVerificationStatusLPw(
703                                packageName, updatedStatus, userId);
704                        scheduleWritePackageRestrictionsLocked(userId);
705                    }
706                }
707            }
708        }
709
710        @Override
711        public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
712                    ActivityIntentInfo filter, String packageName) {
713            if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
714                    filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
715                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
716                        "IntentFilter does not contain HTTP nor HTTPS data scheme");
717                return false;
718            }
719            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
720            if (ivs == null) {
721                ivs = createDomainVerificationState(verifierId, userId, verificationId,
722                        packageName);
723            }
724            if (!hasValidDomains(filter)) {
725                return false;
726            }
727            ivs.addFilter(filter);
728            return true;
729        }
730
731        private IntentFilterVerificationState createDomainVerificationState(int verifierId,
732                int userId, int verificationId, String packageName) {
733            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
734                    verifierId, userId, packageName);
735            ivs.setPendingState();
736            synchronized (mPackages) {
737                mIntentFilterVerificationStates.append(verificationId, ivs);
738                mCurrentIntentFilterVerifications.add(verificationId);
739            }
740            return ivs;
741        }
742    }
743
744    private static boolean hasValidDomains(ActivityIntentInfo filter) {
745        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
746                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
747        if (!hasHTTPorHTTPS) {
748            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
749                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
750            return false;
751        }
752        return true;
753    }
754
755    private IntentFilterVerifier mIntentFilterVerifier;
756
757    // Set of pending broadcasts for aggregating enable/disable of components.
758    static class PendingPackageBroadcasts {
759        // for each user id, a map of <package name -> components within that package>
760        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
761
762        public PendingPackageBroadcasts() {
763            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
764        }
765
766        public ArrayList<String> get(int userId, String packageName) {
767            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
768            return packages.get(packageName);
769        }
770
771        public void put(int userId, String packageName, ArrayList<String> components) {
772            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
773            packages.put(packageName, components);
774        }
775
776        public void remove(int userId, String packageName) {
777            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
778            if (packages != null) {
779                packages.remove(packageName);
780            }
781        }
782
783        public void remove(int userId) {
784            mUidMap.remove(userId);
785        }
786
787        public int userIdCount() {
788            return mUidMap.size();
789        }
790
791        public int userIdAt(int n) {
792            return mUidMap.keyAt(n);
793        }
794
795        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
796            return mUidMap.get(userId);
797        }
798
799        public int size() {
800            // total number of pending broadcast entries across all userIds
801            int num = 0;
802            for (int i = 0; i< mUidMap.size(); i++) {
803                num += mUidMap.valueAt(i).size();
804            }
805            return num;
806        }
807
808        public void clear() {
809            mUidMap.clear();
810        }
811
812        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
813            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
814            if (map == null) {
815                map = new ArrayMap<String, ArrayList<String>>();
816                mUidMap.put(userId, map);
817            }
818            return map;
819        }
820    }
821    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
822
823    // Service Connection to remote media container service to copy
824    // package uri's from external media onto secure containers
825    // or internal storage.
826    private IMediaContainerService mContainerService = null;
827
828    static final int SEND_PENDING_BROADCAST = 1;
829    static final int MCS_BOUND = 3;
830    static final int END_COPY = 4;
831    static final int INIT_COPY = 5;
832    static final int MCS_UNBIND = 6;
833    static final int START_CLEANING_PACKAGE = 7;
834    static final int FIND_INSTALL_LOC = 8;
835    static final int POST_INSTALL = 9;
836    static final int MCS_RECONNECT = 10;
837    static final int MCS_GIVE_UP = 11;
838    static final int UPDATED_MEDIA_STATUS = 12;
839    static final int WRITE_SETTINGS = 13;
840    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
841    static final int PACKAGE_VERIFIED = 15;
842    static final int CHECK_PENDING_VERIFICATION = 16;
843    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
844    static final int INTENT_FILTER_VERIFIED = 18;
845
846    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
847
848    // Delay time in millisecs
849    static final int BROADCAST_DELAY = 10 * 1000;
850
851    static UserManagerService sUserManager;
852
853    // Stores a list of users whose package restrictions file needs to be updated
854    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
855
856    final private DefaultContainerConnection mDefContainerConn =
857            new DefaultContainerConnection();
858    class DefaultContainerConnection implements ServiceConnection {
859        public void onServiceConnected(ComponentName name, IBinder service) {
860            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
861            IMediaContainerService imcs =
862                IMediaContainerService.Stub.asInterface(service);
863            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
864        }
865
866        public void onServiceDisconnected(ComponentName name) {
867            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
868        }
869    };
870
871    // Recordkeeping of restore-after-install operations that are currently in flight
872    // between the Package Manager and the Backup Manager
873    class PostInstallData {
874        public InstallArgs args;
875        public PackageInstalledInfo res;
876
877        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
878            args = _a;
879            res = _r;
880        }
881    };
882    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
883    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
884
885    // backup/restore of preferred activity state
886    private static final String TAG_PREFERRED_BACKUP = "pa";
887
888    private final String mRequiredVerifierPackage;
889
890    private final PackageUsage mPackageUsage = new PackageUsage();
891
892    private class PackageUsage {
893        private static final int WRITE_INTERVAL
894            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
895
896        private final Object mFileLock = new Object();
897        private final AtomicLong mLastWritten = new AtomicLong(0);
898        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
899
900        private boolean mIsHistoricalPackageUsageAvailable = true;
901
902        boolean isHistoricalPackageUsageAvailable() {
903            return mIsHistoricalPackageUsageAvailable;
904        }
905
906        void write(boolean force) {
907            if (force) {
908                writeInternal();
909                return;
910            }
911            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
912                && !DEBUG_DEXOPT) {
913                return;
914            }
915            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
916                new Thread("PackageUsage_DiskWriter") {
917                    @Override
918                    public void run() {
919                        try {
920                            writeInternal();
921                        } finally {
922                            mBackgroundWriteRunning.set(false);
923                        }
924                    }
925                }.start();
926            }
927        }
928
929        private void writeInternal() {
930            synchronized (mPackages) {
931                synchronized (mFileLock) {
932                    AtomicFile file = getFile();
933                    FileOutputStream f = null;
934                    try {
935                        f = file.startWrite();
936                        BufferedOutputStream out = new BufferedOutputStream(f);
937                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
938                        StringBuilder sb = new StringBuilder();
939                        for (PackageParser.Package pkg : mPackages.values()) {
940                            if (pkg.mLastPackageUsageTimeInMills == 0) {
941                                continue;
942                            }
943                            sb.setLength(0);
944                            sb.append(pkg.packageName);
945                            sb.append(' ');
946                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
947                            sb.append('\n');
948                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
949                        }
950                        out.flush();
951                        file.finishWrite(f);
952                    } catch (IOException e) {
953                        if (f != null) {
954                            file.failWrite(f);
955                        }
956                        Log.e(TAG, "Failed to write package usage times", e);
957                    }
958                }
959            }
960            mLastWritten.set(SystemClock.elapsedRealtime());
961        }
962
963        void readLP() {
964            synchronized (mFileLock) {
965                AtomicFile file = getFile();
966                BufferedInputStream in = null;
967                try {
968                    in = new BufferedInputStream(file.openRead());
969                    StringBuffer sb = new StringBuffer();
970                    while (true) {
971                        String packageName = readToken(in, sb, ' ');
972                        if (packageName == null) {
973                            break;
974                        }
975                        String timeInMillisString = readToken(in, sb, '\n');
976                        if (timeInMillisString == null) {
977                            throw new IOException("Failed to find last usage time for package "
978                                                  + packageName);
979                        }
980                        PackageParser.Package pkg = mPackages.get(packageName);
981                        if (pkg == null) {
982                            continue;
983                        }
984                        long timeInMillis;
985                        try {
986                            timeInMillis = Long.parseLong(timeInMillisString.toString());
987                        } catch (NumberFormatException e) {
988                            throw new IOException("Failed to parse " + timeInMillisString
989                                                  + " as a long.", e);
990                        }
991                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
992                    }
993                } catch (FileNotFoundException expected) {
994                    mIsHistoricalPackageUsageAvailable = false;
995                } catch (IOException e) {
996                    Log.w(TAG, "Failed to read package usage times", e);
997                } finally {
998                    IoUtils.closeQuietly(in);
999                }
1000            }
1001            mLastWritten.set(SystemClock.elapsedRealtime());
1002        }
1003
1004        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1005                throws IOException {
1006            sb.setLength(0);
1007            while (true) {
1008                int ch = in.read();
1009                if (ch == -1) {
1010                    if (sb.length() == 0) {
1011                        return null;
1012                    }
1013                    throw new IOException("Unexpected EOF");
1014                }
1015                if (ch == endOfToken) {
1016                    return sb.toString();
1017                }
1018                sb.append((char)ch);
1019            }
1020        }
1021
1022        private AtomicFile getFile() {
1023            File dataDir = Environment.getDataDirectory();
1024            File systemDir = new File(dataDir, "system");
1025            File fname = new File(systemDir, "package-usage.list");
1026            return new AtomicFile(fname);
1027        }
1028    }
1029
1030    class PackageHandler extends Handler {
1031        private boolean mBound = false;
1032        final ArrayList<HandlerParams> mPendingInstalls =
1033            new ArrayList<HandlerParams>();
1034
1035        private boolean connectToService() {
1036            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1037                    " DefaultContainerService");
1038            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1039            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1040            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1041                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1042                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1043                mBound = true;
1044                return true;
1045            }
1046            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1047            return false;
1048        }
1049
1050        private void disconnectService() {
1051            mContainerService = null;
1052            mBound = false;
1053            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1054            mContext.unbindService(mDefContainerConn);
1055            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1056        }
1057
1058        PackageHandler(Looper looper) {
1059            super(looper);
1060        }
1061
1062        public void handleMessage(Message msg) {
1063            try {
1064                doHandleMessage(msg);
1065            } finally {
1066                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1067            }
1068        }
1069
1070        void doHandleMessage(Message msg) {
1071            switch (msg.what) {
1072                case INIT_COPY: {
1073                    HandlerParams params = (HandlerParams) msg.obj;
1074                    int idx = mPendingInstalls.size();
1075                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1076                    // If a bind was already initiated we dont really
1077                    // need to do anything. The pending install
1078                    // will be processed later on.
1079                    if (!mBound) {
1080                        // If this is the only one pending we might
1081                        // have to bind to the service again.
1082                        if (!connectToService()) {
1083                            Slog.e(TAG, "Failed to bind to media container service");
1084                            params.serviceError();
1085                            return;
1086                        } else {
1087                            // Once we bind to the service, the first
1088                            // pending request will be processed.
1089                            mPendingInstalls.add(idx, params);
1090                        }
1091                    } else {
1092                        mPendingInstalls.add(idx, params);
1093                        // Already bound to the service. Just make
1094                        // sure we trigger off processing the first request.
1095                        if (idx == 0) {
1096                            mHandler.sendEmptyMessage(MCS_BOUND);
1097                        }
1098                    }
1099                    break;
1100                }
1101                case MCS_BOUND: {
1102                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1103                    if (msg.obj != null) {
1104                        mContainerService = (IMediaContainerService) msg.obj;
1105                    }
1106                    if (mContainerService == null) {
1107                        // Something seriously wrong. Bail out
1108                        Slog.e(TAG, "Cannot bind to media container service");
1109                        for (HandlerParams params : mPendingInstalls) {
1110                            // Indicate service bind error
1111                            params.serviceError();
1112                        }
1113                        mPendingInstalls.clear();
1114                    } else if (mPendingInstalls.size() > 0) {
1115                        HandlerParams params = mPendingInstalls.get(0);
1116                        if (params != null) {
1117                            if (params.startCopy()) {
1118                                // We are done...  look for more work or to
1119                                // go idle.
1120                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1121                                        "Checking for more work or unbind...");
1122                                // Delete pending install
1123                                if (mPendingInstalls.size() > 0) {
1124                                    mPendingInstalls.remove(0);
1125                                }
1126                                if (mPendingInstalls.size() == 0) {
1127                                    if (mBound) {
1128                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1129                                                "Posting delayed MCS_UNBIND");
1130                                        removeMessages(MCS_UNBIND);
1131                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1132                                        // Unbind after a little delay, to avoid
1133                                        // continual thrashing.
1134                                        sendMessageDelayed(ubmsg, 10000);
1135                                    }
1136                                } else {
1137                                    // There are more pending requests in queue.
1138                                    // Just post MCS_BOUND message to trigger processing
1139                                    // of next pending install.
1140                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1141                                            "Posting MCS_BOUND for next work");
1142                                    mHandler.sendEmptyMessage(MCS_BOUND);
1143                                }
1144                            }
1145                        }
1146                    } else {
1147                        // Should never happen ideally.
1148                        Slog.w(TAG, "Empty queue");
1149                    }
1150                    break;
1151                }
1152                case MCS_RECONNECT: {
1153                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1154                    if (mPendingInstalls.size() > 0) {
1155                        if (mBound) {
1156                            disconnectService();
1157                        }
1158                        if (!connectToService()) {
1159                            Slog.e(TAG, "Failed to bind to media container service");
1160                            for (HandlerParams params : mPendingInstalls) {
1161                                // Indicate service bind error
1162                                params.serviceError();
1163                            }
1164                            mPendingInstalls.clear();
1165                        }
1166                    }
1167                    break;
1168                }
1169                case MCS_UNBIND: {
1170                    // If there is no actual work left, then time to unbind.
1171                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1172
1173                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1174                        if (mBound) {
1175                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1176
1177                            disconnectService();
1178                        }
1179                    } else if (mPendingInstalls.size() > 0) {
1180                        // There are more pending requests in queue.
1181                        // Just post MCS_BOUND message to trigger processing
1182                        // of next pending install.
1183                        mHandler.sendEmptyMessage(MCS_BOUND);
1184                    }
1185
1186                    break;
1187                }
1188                case MCS_GIVE_UP: {
1189                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1190                    mPendingInstalls.remove(0);
1191                    break;
1192                }
1193                case SEND_PENDING_BROADCAST: {
1194                    String packages[];
1195                    ArrayList<String> components[];
1196                    int size = 0;
1197                    int uids[];
1198                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1199                    synchronized (mPackages) {
1200                        if (mPendingBroadcasts == null) {
1201                            return;
1202                        }
1203                        size = mPendingBroadcasts.size();
1204                        if (size <= 0) {
1205                            // Nothing to be done. Just return
1206                            return;
1207                        }
1208                        packages = new String[size];
1209                        components = new ArrayList[size];
1210                        uids = new int[size];
1211                        int i = 0;  // filling out the above arrays
1212
1213                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1214                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1215                            Iterator<Map.Entry<String, ArrayList<String>>> it
1216                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1217                                            .entrySet().iterator();
1218                            while (it.hasNext() && i < size) {
1219                                Map.Entry<String, ArrayList<String>> ent = it.next();
1220                                packages[i] = ent.getKey();
1221                                components[i] = ent.getValue();
1222                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1223                                uids[i] = (ps != null)
1224                                        ? UserHandle.getUid(packageUserId, ps.appId)
1225                                        : -1;
1226                                i++;
1227                            }
1228                        }
1229                        size = i;
1230                        mPendingBroadcasts.clear();
1231                    }
1232                    // Send broadcasts
1233                    for (int i = 0; i < size; i++) {
1234                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1235                    }
1236                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1237                    break;
1238                }
1239                case START_CLEANING_PACKAGE: {
1240                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1241                    final String packageName = (String)msg.obj;
1242                    final int userId = msg.arg1;
1243                    final boolean andCode = msg.arg2 != 0;
1244                    synchronized (mPackages) {
1245                        if (userId == UserHandle.USER_ALL) {
1246                            int[] users = sUserManager.getUserIds();
1247                            for (int user : users) {
1248                                mSettings.addPackageToCleanLPw(
1249                                        new PackageCleanItem(user, packageName, andCode));
1250                            }
1251                        } else {
1252                            mSettings.addPackageToCleanLPw(
1253                                    new PackageCleanItem(userId, packageName, andCode));
1254                        }
1255                    }
1256                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1257                    startCleaningPackages();
1258                } break;
1259                case POST_INSTALL: {
1260                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1261                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1262                    mRunningInstalls.delete(msg.arg1);
1263                    boolean deleteOld = false;
1264
1265                    if (data != null) {
1266                        InstallArgs args = data.args;
1267                        PackageInstalledInfo res = data.res;
1268
1269                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1270                            res.removedInfo.sendBroadcast(false, true, false);
1271                            Bundle extras = new Bundle(1);
1272                            extras.putInt(Intent.EXTRA_UID, res.uid);
1273
1274                            // Now that we successfully installed the package, grant runtime
1275                            // permissions if requested before broadcasting the install.
1276                            if ((args.installFlags
1277                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1278                                grantRequestedRuntimePermissions(res.pkg,
1279                                        args.user.getIdentifier());
1280                            }
1281
1282                            // Determine the set of users who are adding this
1283                            // package for the first time vs. those who are seeing
1284                            // an update.
1285                            int[] firstUsers;
1286                            int[] updateUsers = new int[0];
1287                            if (res.origUsers == null || res.origUsers.length == 0) {
1288                                firstUsers = res.newUsers;
1289                            } else {
1290                                firstUsers = new int[0];
1291                                for (int i=0; i<res.newUsers.length; i++) {
1292                                    int user = res.newUsers[i];
1293                                    boolean isNew = true;
1294                                    for (int j=0; j<res.origUsers.length; j++) {
1295                                        if (res.origUsers[j] == user) {
1296                                            isNew = false;
1297                                            break;
1298                                        }
1299                                    }
1300                                    if (isNew) {
1301                                        int[] newFirst = new int[firstUsers.length+1];
1302                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1303                                                firstUsers.length);
1304                                        newFirst[firstUsers.length] = user;
1305                                        firstUsers = newFirst;
1306                                    } else {
1307                                        int[] newUpdate = new int[updateUsers.length+1];
1308                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1309                                                updateUsers.length);
1310                                        newUpdate[updateUsers.length] = user;
1311                                        updateUsers = newUpdate;
1312                                    }
1313                                }
1314                            }
1315                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1316                                    res.pkg.applicationInfo.packageName,
1317                                    extras, null, null, firstUsers);
1318                            final boolean update = res.removedInfo.removedPackage != null;
1319                            if (update) {
1320                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1321                            }
1322                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1323                                    res.pkg.applicationInfo.packageName,
1324                                    extras, null, null, updateUsers);
1325                            if (update) {
1326                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1327                                        res.pkg.applicationInfo.packageName,
1328                                        extras, null, null, updateUsers);
1329                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1330                                        null, null,
1331                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1332
1333                                // treat asec-hosted packages like removable media on upgrade
1334                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1335                                    if (DEBUG_INSTALL) {
1336                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1337                                                + " is ASEC-hosted -> AVAILABLE");
1338                                    }
1339                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1340                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1341                                    pkgList.add(res.pkg.applicationInfo.packageName);
1342                                    sendResourcesChangedBroadcast(true, true,
1343                                            pkgList,uidArray, null);
1344                                }
1345                            }
1346                            if (res.removedInfo.args != null) {
1347                                // Remove the replaced package's older resources safely now
1348                                deleteOld = true;
1349                            }
1350
1351                            // Log current value of "unknown sources" setting
1352                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1353                                getUnknownSourcesSettings());
1354                        }
1355                        // Force a gc to clear up things
1356                        Runtime.getRuntime().gc();
1357                        // We delete after a gc for applications  on sdcard.
1358                        if (deleteOld) {
1359                            synchronized (mInstallLock) {
1360                                res.removedInfo.args.doPostDeleteLI(true);
1361                            }
1362                        }
1363                        if (args.observer != null) {
1364                            try {
1365                                Bundle extras = extrasForInstallResult(res);
1366                                args.observer.onPackageInstalled(res.name, res.returnCode,
1367                                        res.returnMsg, extras);
1368                            } catch (RemoteException e) {
1369                                Slog.i(TAG, "Observer no longer exists.");
1370                            }
1371                        }
1372                    } else {
1373                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1374                    }
1375                } break;
1376                case UPDATED_MEDIA_STATUS: {
1377                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1378                    boolean reportStatus = msg.arg1 == 1;
1379                    boolean doGc = msg.arg2 == 1;
1380                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1381                    if (doGc) {
1382                        // Force a gc to clear up stale containers.
1383                        Runtime.getRuntime().gc();
1384                    }
1385                    if (msg.obj != null) {
1386                        @SuppressWarnings("unchecked")
1387                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1388                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1389                        // Unload containers
1390                        unloadAllContainers(args);
1391                    }
1392                    if (reportStatus) {
1393                        try {
1394                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1395                            PackageHelper.getMountService().finishMediaUpdate();
1396                        } catch (RemoteException e) {
1397                            Log.e(TAG, "MountService not running?");
1398                        }
1399                    }
1400                } break;
1401                case WRITE_SETTINGS: {
1402                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1403                    synchronized (mPackages) {
1404                        removeMessages(WRITE_SETTINGS);
1405                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1406                        mSettings.writeLPr();
1407                        mDirtyUsers.clear();
1408                    }
1409                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1410                } break;
1411                case WRITE_PACKAGE_RESTRICTIONS: {
1412                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1413                    synchronized (mPackages) {
1414                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1415                        for (int userId : mDirtyUsers) {
1416                            mSettings.writePackageRestrictionsLPr(userId);
1417                        }
1418                        mDirtyUsers.clear();
1419                    }
1420                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1421                } break;
1422                case CHECK_PENDING_VERIFICATION: {
1423                    final int verificationId = msg.arg1;
1424                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1425
1426                    if ((state != null) && !state.timeoutExtended()) {
1427                        final InstallArgs args = state.getInstallArgs();
1428                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1429
1430                        Slog.i(TAG, "Verification timed out for " + originUri);
1431                        mPendingVerification.remove(verificationId);
1432
1433                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1434
1435                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1436                            Slog.i(TAG, "Continuing with installation of " + originUri);
1437                            state.setVerifierResponse(Binder.getCallingUid(),
1438                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1439                            broadcastPackageVerified(verificationId, originUri,
1440                                    PackageManager.VERIFICATION_ALLOW,
1441                                    state.getInstallArgs().getUser());
1442                            try {
1443                                ret = args.copyApk(mContainerService, true);
1444                            } catch (RemoteException e) {
1445                                Slog.e(TAG, "Could not contact the ContainerService");
1446                            }
1447                        } else {
1448                            broadcastPackageVerified(verificationId, originUri,
1449                                    PackageManager.VERIFICATION_REJECT,
1450                                    state.getInstallArgs().getUser());
1451                        }
1452
1453                        processPendingInstall(args, ret);
1454                        mHandler.sendEmptyMessage(MCS_UNBIND);
1455                    }
1456                    break;
1457                }
1458                case PACKAGE_VERIFIED: {
1459                    final int verificationId = msg.arg1;
1460
1461                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1462                    if (state == null) {
1463                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1464                        break;
1465                    }
1466
1467                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1468
1469                    state.setVerifierResponse(response.callerUid, response.code);
1470
1471                    if (state.isVerificationComplete()) {
1472                        mPendingVerification.remove(verificationId);
1473
1474                        final InstallArgs args = state.getInstallArgs();
1475                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1476
1477                        int ret;
1478                        if (state.isInstallAllowed()) {
1479                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1480                            broadcastPackageVerified(verificationId, originUri,
1481                                    response.code, state.getInstallArgs().getUser());
1482                            try {
1483                                ret = args.copyApk(mContainerService, true);
1484                            } catch (RemoteException e) {
1485                                Slog.e(TAG, "Could not contact the ContainerService");
1486                            }
1487                        } else {
1488                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1489                        }
1490
1491                        processPendingInstall(args, ret);
1492
1493                        mHandler.sendEmptyMessage(MCS_UNBIND);
1494                    }
1495
1496                    break;
1497                }
1498                case START_INTENT_FILTER_VERIFICATIONS: {
1499                    int userId = msg.arg1;
1500                    int verifierUid = msg.arg2;
1501                    PackageParser.Package pkg = (PackageParser.Package)msg.obj;
1502
1503                    verifyIntentFiltersIfNeeded(userId, verifierUid, pkg);
1504                    break;
1505                }
1506                case INTENT_FILTER_VERIFIED: {
1507                    final int verificationId = msg.arg1;
1508
1509                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1510                            verificationId);
1511                    if (state == null) {
1512                        Slog.w(TAG, "Invalid IntentFilter verification token "
1513                                + verificationId + " received");
1514                        break;
1515                    }
1516
1517                    final int userId = state.getUserId();
1518
1519                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1520                            "Processing IntentFilter verification with token:"
1521                            + verificationId + " and userId:" + userId);
1522
1523                    final IntentFilterVerificationResponse response =
1524                            (IntentFilterVerificationResponse) msg.obj;
1525
1526                    state.setVerifierResponse(response.callerUid, response.code);
1527
1528                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1529                            "IntentFilter verification with token:" + verificationId
1530                            + " and userId:" + userId
1531                            + " is settings verifier response with response code:"
1532                            + response.code);
1533
1534                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1535                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1536                                + response.getFailedDomainsString());
1537                    }
1538
1539                    if (state.isVerificationComplete()) {
1540                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1541                    } else {
1542                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1543                                "IntentFilter verification with token:" + verificationId
1544                                + " was not said to be complete");
1545                    }
1546
1547                    break;
1548                }
1549            }
1550        }
1551    }
1552
1553    private StorageEventListener mStorageListener = new StorageEventListener() {
1554        @Override
1555        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1556            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1557                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1558                    // TODO: ensure that private directories exist for all active users
1559                    // TODO: remove user data whose serial number doesn't match
1560                    loadPrivatePackages(vol);
1561                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1562                    unloadPrivatePackages(vol);
1563                }
1564            }
1565
1566            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1567                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1568                    updateExternalMediaStatus(true, false);
1569                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1570                    updateExternalMediaStatus(false, false);
1571                }
1572            }
1573        }
1574
1575        @Override
1576        public void onVolumeForgotten(String fsUuid) {
1577            // TODO: remove all packages hosted on this uuid
1578        }
1579    };
1580
1581    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1582        if (userId >= UserHandle.USER_OWNER) {
1583            grantRequestedRuntimePermissionsForUser(pkg, userId);
1584        } else if (userId == UserHandle.USER_ALL) {
1585            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1586                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1587            }
1588        }
1589
1590        // We could have touched GID membership, so flush out packages.list
1591        synchronized (mPackages) {
1592            mSettings.writePackageListLPr();
1593        }
1594    }
1595
1596    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1597        SettingBase sb = (SettingBase) pkg.mExtras;
1598        if (sb == null) {
1599            return;
1600        }
1601
1602        PermissionsState permissionsState = sb.getPermissionsState();
1603
1604        for (String permission : pkg.requestedPermissions) {
1605            BasePermission bp = mSettings.mPermissions.get(permission);
1606            if (bp != null && bp.isRuntime()) {
1607                permissionsState.grantRuntimePermission(bp, userId);
1608            }
1609        }
1610    }
1611
1612    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1613        Bundle extras = null;
1614        switch (res.returnCode) {
1615            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1616                extras = new Bundle();
1617                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1618                        res.origPermission);
1619                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1620                        res.origPackage);
1621                break;
1622            }
1623            case PackageManager.INSTALL_SUCCEEDED: {
1624                extras = new Bundle();
1625                extras.putBoolean(Intent.EXTRA_REPLACING,
1626                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1627                break;
1628            }
1629        }
1630        return extras;
1631    }
1632
1633    void scheduleWriteSettingsLocked() {
1634        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1635            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1636        }
1637    }
1638
1639    void scheduleWritePackageRestrictionsLocked(int userId) {
1640        if (!sUserManager.exists(userId)) return;
1641        mDirtyUsers.add(userId);
1642        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1643            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1644        }
1645    }
1646
1647    public static PackageManagerService main(Context context, Installer installer,
1648            boolean factoryTest, boolean onlyCore) {
1649        PackageManagerService m = new PackageManagerService(context, installer,
1650                factoryTest, onlyCore);
1651        ServiceManager.addService("package", m);
1652        return m;
1653    }
1654
1655    static String[] splitString(String str, char sep) {
1656        int count = 1;
1657        int i = 0;
1658        while ((i=str.indexOf(sep, i)) >= 0) {
1659            count++;
1660            i++;
1661        }
1662
1663        String[] res = new String[count];
1664        i=0;
1665        count = 0;
1666        int lastI=0;
1667        while ((i=str.indexOf(sep, i)) >= 0) {
1668            res[count] = str.substring(lastI, i);
1669            count++;
1670            i++;
1671            lastI = i;
1672        }
1673        res[count] = str.substring(lastI, str.length());
1674        return res;
1675    }
1676
1677    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1678        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1679                Context.DISPLAY_SERVICE);
1680        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1681    }
1682
1683    public PackageManagerService(Context context, Installer installer,
1684            boolean factoryTest, boolean onlyCore) {
1685        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1686                SystemClock.uptimeMillis());
1687
1688        if (mSdkVersion <= 0) {
1689            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1690        }
1691
1692        mContext = context;
1693        mFactoryTest = factoryTest;
1694        mOnlyCore = onlyCore;
1695        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1696        mMetrics = new DisplayMetrics();
1697        mSettings = new Settings(mPackages);
1698        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1699                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1700        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1701                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1702        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1703                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1704        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1705                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1706        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1707                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1708        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1709                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1710
1711        // TODO: add a property to control this?
1712        long dexOptLRUThresholdInMinutes;
1713        if (mLazyDexOpt) {
1714            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1715        } else {
1716            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1717        }
1718        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1719
1720        String separateProcesses = SystemProperties.get("debug.separate_processes");
1721        if (separateProcesses != null && separateProcesses.length() > 0) {
1722            if ("*".equals(separateProcesses)) {
1723                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1724                mSeparateProcesses = null;
1725                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1726            } else {
1727                mDefParseFlags = 0;
1728                mSeparateProcesses = separateProcesses.split(",");
1729                Slog.w(TAG, "Running with debug.separate_processes: "
1730                        + separateProcesses);
1731            }
1732        } else {
1733            mDefParseFlags = 0;
1734            mSeparateProcesses = null;
1735        }
1736
1737        mInstaller = installer;
1738        mPackageDexOptimizer = new PackageDexOptimizer(this);
1739        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1740
1741        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1742                FgThread.get().getLooper());
1743
1744        getDefaultDisplayMetrics(context, mMetrics);
1745
1746        SystemConfig systemConfig = SystemConfig.getInstance();
1747        mGlobalGids = systemConfig.getGlobalGids();
1748        mSystemPermissions = systemConfig.getSystemPermissions();
1749        mAvailableFeatures = systemConfig.getAvailableFeatures();
1750
1751        synchronized (mInstallLock) {
1752        // writer
1753        synchronized (mPackages) {
1754            mHandlerThread = new ServiceThread(TAG,
1755                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1756            mHandlerThread.start();
1757            mHandler = new PackageHandler(mHandlerThread.getLooper());
1758            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1759
1760            File dataDir = Environment.getDataDirectory();
1761            mAppDataDir = new File(dataDir, "data");
1762            mAppInstallDir = new File(dataDir, "app");
1763            mAppLib32InstallDir = new File(dataDir, "app-lib");
1764            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1765            mUserAppDataDir = new File(dataDir, "user");
1766            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1767
1768            sUserManager = new UserManagerService(context, this,
1769                    mInstallLock, mPackages);
1770
1771            // Propagate permission configuration in to package manager.
1772            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1773                    = systemConfig.getPermissions();
1774            for (int i=0; i<permConfig.size(); i++) {
1775                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1776                BasePermission bp = mSettings.mPermissions.get(perm.name);
1777                if (bp == null) {
1778                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1779                    mSettings.mPermissions.put(perm.name, bp);
1780                }
1781                if (perm.gids != null) {
1782                    bp.setGids(perm.gids, perm.perUser);
1783                }
1784            }
1785
1786            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1787            for (int i=0; i<libConfig.size(); i++) {
1788                mSharedLibraries.put(libConfig.keyAt(i),
1789                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1790            }
1791
1792            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1793
1794            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1795                    mSdkVersion, mOnlyCore);
1796
1797            String customResolverActivity = Resources.getSystem().getString(
1798                    R.string.config_customResolverActivity);
1799            if (TextUtils.isEmpty(customResolverActivity)) {
1800                customResolverActivity = null;
1801            } else {
1802                mCustomResolverComponentName = ComponentName.unflattenFromString(
1803                        customResolverActivity);
1804            }
1805
1806            long startTime = SystemClock.uptimeMillis();
1807
1808            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1809                    startTime);
1810
1811            // Set flag to monitor and not change apk file paths when
1812            // scanning install directories.
1813            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1814
1815            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1816
1817            /**
1818             * Add everything in the in the boot class path to the
1819             * list of process files because dexopt will have been run
1820             * if necessary during zygote startup.
1821             */
1822            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1823            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1824
1825            if (bootClassPath != null) {
1826                String[] bootClassPathElements = splitString(bootClassPath, ':');
1827                for (String element : bootClassPathElements) {
1828                    alreadyDexOpted.add(element);
1829                }
1830            } else {
1831                Slog.w(TAG, "No BOOTCLASSPATH found!");
1832            }
1833
1834            if (systemServerClassPath != null) {
1835                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1836                for (String element : systemServerClassPathElements) {
1837                    alreadyDexOpted.add(element);
1838                }
1839            } else {
1840                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1841            }
1842
1843            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1844            final String[] dexCodeInstructionSets =
1845                    getDexCodeInstructionSets(
1846                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1847
1848            /**
1849             * Ensure all external libraries have had dexopt run on them.
1850             */
1851            if (mSharedLibraries.size() > 0) {
1852                // NOTE: For now, we're compiling these system "shared libraries"
1853                // (and framework jars) into all available architectures. It's possible
1854                // to compile them only when we come across an app that uses them (there's
1855                // already logic for that in scanPackageLI) but that adds some complexity.
1856                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1857                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1858                        final String lib = libEntry.path;
1859                        if (lib == null) {
1860                            continue;
1861                        }
1862
1863                        try {
1864                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1865                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1866                                alreadyDexOpted.add(lib);
1867                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1868                            }
1869                        } catch (FileNotFoundException e) {
1870                            Slog.w(TAG, "Library not found: " + lib);
1871                        } catch (IOException e) {
1872                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1873                                    + e.getMessage());
1874                        }
1875                    }
1876                }
1877            }
1878
1879            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1880
1881            // Gross hack for now: we know this file doesn't contain any
1882            // code, so don't dexopt it to avoid the resulting log spew.
1883            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1884
1885            // Gross hack for now: we know this file is only part of
1886            // the boot class path for art, so don't dexopt it to
1887            // avoid the resulting log spew.
1888            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1889
1890            /**
1891             * There are a number of commands implemented in Java, which
1892             * we currently need to do the dexopt on so that they can be
1893             * run from a non-root shell.
1894             */
1895            String[] frameworkFiles = frameworkDir.list();
1896            if (frameworkFiles != null) {
1897                // TODO: We could compile these only for the most preferred ABI. We should
1898                // first double check that the dex files for these commands are not referenced
1899                // by other system apps.
1900                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1901                    for (int i=0; i<frameworkFiles.length; i++) {
1902                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1903                        String path = libPath.getPath();
1904                        // Skip the file if we already did it.
1905                        if (alreadyDexOpted.contains(path)) {
1906                            continue;
1907                        }
1908                        // Skip the file if it is not a type we want to dexopt.
1909                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1910                            continue;
1911                        }
1912                        try {
1913                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1914                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1915                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1916                            }
1917                        } catch (FileNotFoundException e) {
1918                            Slog.w(TAG, "Jar not found: " + path);
1919                        } catch (IOException e) {
1920                            Slog.w(TAG, "Exception reading jar: " + path, e);
1921                        }
1922                    }
1923                }
1924            }
1925
1926            // Collect vendor overlay packages.
1927            // (Do this before scanning any apps.)
1928            // For security and version matching reason, only consider
1929            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1930            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1931            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1932                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1933
1934            // Find base frameworks (resource packages without code).
1935            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1936                    | PackageParser.PARSE_IS_SYSTEM_DIR
1937                    | PackageParser.PARSE_IS_PRIVILEGED,
1938                    scanFlags | SCAN_NO_DEX, 0);
1939
1940            // Collected privileged system packages.
1941            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1942            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1943                    | PackageParser.PARSE_IS_SYSTEM_DIR
1944                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1945
1946            // Collect ordinary system packages.
1947            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1948            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1949                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1950
1951            // Collect all vendor packages.
1952            File vendorAppDir = new File("/vendor/app");
1953            try {
1954                vendorAppDir = vendorAppDir.getCanonicalFile();
1955            } catch (IOException e) {
1956                // failed to look up canonical path, continue with original one
1957            }
1958            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1959                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1960
1961            // Collect all OEM packages.
1962            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1963            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1964                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1965
1966            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1967            mInstaller.moveFiles();
1968
1969            // Prune any system packages that no longer exist.
1970            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1971            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1972            if (!mOnlyCore) {
1973                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1974                while (psit.hasNext()) {
1975                    PackageSetting ps = psit.next();
1976
1977                    /*
1978                     * If this is not a system app, it can't be a
1979                     * disable system app.
1980                     */
1981                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1982                        continue;
1983                    }
1984
1985                    /*
1986                     * If the package is scanned, it's not erased.
1987                     */
1988                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1989                    if (scannedPkg != null) {
1990                        /*
1991                         * If the system app is both scanned and in the
1992                         * disabled packages list, then it must have been
1993                         * added via OTA. Remove it from the currently
1994                         * scanned package so the previously user-installed
1995                         * application can be scanned.
1996                         */
1997                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1998                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1999                                    + ps.name + "; removing system app.  Last known codePath="
2000                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2001                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2002                                    + scannedPkg.mVersionCode);
2003                            removePackageLI(ps, true);
2004                            expectingBetter.put(ps.name, ps.codePath);
2005                        }
2006
2007                        continue;
2008                    }
2009
2010                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2011                        psit.remove();
2012                        logCriticalInfo(Log.WARN, "System package " + ps.name
2013                                + " no longer exists; wiping its data");
2014                        removeDataDirsLI(null, ps.name);
2015                    } else {
2016                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2017                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2018                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2019                        }
2020                    }
2021                }
2022            }
2023
2024            //look for any incomplete package installations
2025            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2026            //clean up list
2027            for(int i = 0; i < deletePkgsList.size(); i++) {
2028                //clean up here
2029                cleanupInstallFailedPackage(deletePkgsList.get(i));
2030            }
2031            //delete tmp files
2032            deleteTempPackageFiles();
2033
2034            // Remove any shared userIDs that have no associated packages
2035            mSettings.pruneSharedUsersLPw();
2036
2037            if (!mOnlyCore) {
2038                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2039                        SystemClock.uptimeMillis());
2040                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2041
2042                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2043                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2044
2045                /**
2046                 * Remove disable package settings for any updated system
2047                 * apps that were removed via an OTA. If they're not a
2048                 * previously-updated app, remove them completely.
2049                 * Otherwise, just revoke their system-level permissions.
2050                 */
2051                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2052                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2053                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2054
2055                    String msg;
2056                    if (deletedPkg == null) {
2057                        msg = "Updated system package " + deletedAppName
2058                                + " no longer exists; wiping its data";
2059                        removeDataDirsLI(null, deletedAppName);
2060                    } else {
2061                        msg = "Updated system app + " + deletedAppName
2062                                + " no longer present; removing system privileges for "
2063                                + deletedAppName;
2064
2065                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2066
2067                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2068                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2069                    }
2070                    logCriticalInfo(Log.WARN, msg);
2071                }
2072
2073                /**
2074                 * Make sure all system apps that we expected to appear on
2075                 * the userdata partition actually showed up. If they never
2076                 * appeared, crawl back and revive the system version.
2077                 */
2078                for (int i = 0; i < expectingBetter.size(); i++) {
2079                    final String packageName = expectingBetter.keyAt(i);
2080                    if (!mPackages.containsKey(packageName)) {
2081                        final File scanFile = expectingBetter.valueAt(i);
2082
2083                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2084                                + " but never showed up; reverting to system");
2085
2086                        final int reparseFlags;
2087                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2088                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2089                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2090                                    | PackageParser.PARSE_IS_PRIVILEGED;
2091                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2092                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2093                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2094                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2095                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2096                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2097                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2098                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2099                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2100                        } else {
2101                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2102                            continue;
2103                        }
2104
2105                        mSettings.enableSystemPackageLPw(packageName);
2106
2107                        try {
2108                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2109                        } catch (PackageManagerException e) {
2110                            Slog.e(TAG, "Failed to parse original system package: "
2111                                    + e.getMessage());
2112                        }
2113                    }
2114                }
2115            }
2116
2117            // Now that we know all of the shared libraries, update all clients to have
2118            // the correct library paths.
2119            updateAllSharedLibrariesLPw();
2120
2121            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2122                // NOTE: We ignore potential failures here during a system scan (like
2123                // the rest of the commands above) because there's precious little we
2124                // can do about it. A settings error is reported, though.
2125                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2126                        false /* force dexopt */, false /* defer dexopt */);
2127            }
2128
2129            // Now that we know all the packages we are keeping,
2130            // read and update their last usage times.
2131            mPackageUsage.readLP();
2132
2133            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2134                    SystemClock.uptimeMillis());
2135            Slog.i(TAG, "Time to scan packages: "
2136                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2137                    + " seconds");
2138
2139            // If the platform SDK has changed since the last time we booted,
2140            // we need to re-grant app permission to catch any new ones that
2141            // appear.  This is really a hack, and means that apps can in some
2142            // cases get permissions that the user didn't initially explicitly
2143            // allow...  it would be nice to have some better way to handle
2144            // this situation.
2145            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2146                    != mSdkVersion;
2147            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2148                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2149                    + "; regranting permissions for internal storage");
2150            mSettings.mInternalSdkPlatform = mSdkVersion;
2151
2152            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2153                    | (regrantPermissions
2154                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2155                            : 0));
2156
2157            // If this is the first boot, and it is a normal boot, then
2158            // we need to initialize the default preferred apps.
2159            if (!mRestoredSettings && !onlyCore) {
2160                mSettings.readDefaultPreferredAppsLPw(this, 0);
2161            }
2162
2163            // If this is first boot after an OTA, and a normal boot, then
2164            // we need to clear code cache directories.
2165            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2166            if (mIsUpgrade && !onlyCore) {
2167                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2168                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2169                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2170                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2171                }
2172                mSettings.mFingerprint = Build.FINGERPRINT;
2173            }
2174
2175            primeDomainVerificationsLPw();
2176            checkDefaultBrowser();
2177
2178            // All the changes are done during package scanning.
2179            mSettings.updateInternalDatabaseVersion();
2180
2181            // can downgrade to reader
2182            mSettings.writeLPr();
2183
2184            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2185                    SystemClock.uptimeMillis());
2186
2187            mRequiredVerifierPackage = getRequiredVerifierLPr();
2188
2189            mInstallerService = new PackageInstallerService(context, this);
2190
2191            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2192            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2193                    mIntentFilterVerifierComponent);
2194
2195        } // synchronized (mPackages)
2196        } // synchronized (mInstallLock)
2197
2198        // Now after opening every single application zip, make sure they
2199        // are all flushed.  Not really needed, but keeps things nice and
2200        // tidy.
2201        Runtime.getRuntime().gc();
2202    }
2203
2204    @Override
2205    public boolean isFirstBoot() {
2206        return !mRestoredSettings;
2207    }
2208
2209    @Override
2210    public boolean isOnlyCoreApps() {
2211        return mOnlyCore;
2212    }
2213
2214    @Override
2215    public boolean isUpgrade() {
2216        return mIsUpgrade;
2217    }
2218
2219    private String getRequiredVerifierLPr() {
2220        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2221        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2222                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2223
2224        String requiredVerifier = null;
2225
2226        final int N = receivers.size();
2227        for (int i = 0; i < N; i++) {
2228            final ResolveInfo info = receivers.get(i);
2229
2230            if (info.activityInfo == null) {
2231                continue;
2232            }
2233
2234            final String packageName = info.activityInfo.packageName;
2235
2236            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2237                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2238                continue;
2239            }
2240
2241            if (requiredVerifier != null) {
2242                throw new RuntimeException("There can be only one required verifier");
2243            }
2244
2245            requiredVerifier = packageName;
2246        }
2247
2248        return requiredVerifier;
2249    }
2250
2251    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2252        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2253        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2254                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2255
2256        ComponentName verifierComponentName = null;
2257
2258        int priority = -1000;
2259        final int N = receivers.size();
2260        for (int i = 0; i < N; i++) {
2261            final ResolveInfo info = receivers.get(i);
2262
2263            if (info.activityInfo == null) {
2264                continue;
2265            }
2266
2267            final String packageName = info.activityInfo.packageName;
2268
2269            final PackageSetting ps = mSettings.mPackages.get(packageName);
2270            if (ps == null) {
2271                continue;
2272            }
2273
2274            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2275                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2276                continue;
2277            }
2278
2279            // Select the IntentFilterVerifier with the highest priority
2280            if (priority < info.priority) {
2281                priority = info.priority;
2282                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2283                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2284                        + verifierComponentName + " with priority: " + info.priority);
2285            }
2286        }
2287
2288        return verifierComponentName;
2289    }
2290
2291    private void primeDomainVerificationsLPw() {
2292        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2293        boolean updated = false;
2294        ArraySet<String> allHostsSet = new ArraySet<>();
2295        for (PackageParser.Package pkg : mPackages.values()) {
2296            final String packageName = pkg.packageName;
2297            if (!hasDomainURLs(pkg)) {
2298                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2299                            "package with no domain URLs: " + packageName);
2300                continue;
2301            }
2302            if (!pkg.isSystemApp()) {
2303                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2304                        "No priming domain verifications for a non system package : " +
2305                                packageName);
2306                continue;
2307            }
2308            for (PackageParser.Activity a : pkg.activities) {
2309                for (ActivityIntentInfo filter : a.intents) {
2310                    if (hasValidDomains(filter)) {
2311                        allHostsSet.addAll(filter.getHostsList());
2312                    }
2313                }
2314            }
2315            if (allHostsSet.size() == 0) {
2316                allHostsSet.add("*");
2317            }
2318            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2319            IntentFilterVerificationInfo ivi =
2320                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2321            if (ivi != null) {
2322                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2323                        "Priming domain verifications for package: " + packageName +
2324                        " with hosts:" + ivi.getDomainsString());
2325                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2326                updated = true;
2327            }
2328            else {
2329                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2330                        "No priming domain verifications for package: " + packageName);
2331            }
2332            allHostsSet.clear();
2333        }
2334        if (updated) {
2335            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2336                    "Will need to write primed domain verifications");
2337        }
2338        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2339    }
2340
2341    private void checkDefaultBrowser() {
2342        final int myUserId = UserHandle.myUserId();
2343        final String packageName = getDefaultBrowserPackageName(myUserId);
2344        PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2345        if (info == null) {
2346            Slog.w(TAG, "Clearing default Browser as its package is no more installed: " +
2347                    packageName);
2348            setDefaultBrowserPackageName(null, myUserId);
2349        }
2350    }
2351
2352    @Override
2353    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2354            throws RemoteException {
2355        try {
2356            return super.onTransact(code, data, reply, flags);
2357        } catch (RuntimeException e) {
2358            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2359                Slog.wtf(TAG, "Package Manager Crash", e);
2360            }
2361            throw e;
2362        }
2363    }
2364
2365    void cleanupInstallFailedPackage(PackageSetting ps) {
2366        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2367
2368        removeDataDirsLI(ps.volumeUuid, ps.name);
2369        if (ps.codePath != null) {
2370            if (ps.codePath.isDirectory()) {
2371                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2372            } else {
2373                ps.codePath.delete();
2374            }
2375        }
2376        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2377            if (ps.resourcePath.isDirectory()) {
2378                FileUtils.deleteContents(ps.resourcePath);
2379            }
2380            ps.resourcePath.delete();
2381        }
2382        mSettings.removePackageLPw(ps.name);
2383    }
2384
2385    static int[] appendInts(int[] cur, int[] add) {
2386        if (add == null) return cur;
2387        if (cur == null) return add;
2388        final int N = add.length;
2389        for (int i=0; i<N; i++) {
2390            cur = appendInt(cur, add[i]);
2391        }
2392        return cur;
2393    }
2394
2395    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2396        if (!sUserManager.exists(userId)) return null;
2397        final PackageSetting ps = (PackageSetting) p.mExtras;
2398        if (ps == null) {
2399            return null;
2400        }
2401
2402        final PermissionsState permissionsState = ps.getPermissionsState();
2403
2404        final int[] gids = permissionsState.computeGids(userId);
2405        final Set<String> permissions = permissionsState.getPermissions(userId);
2406        final PackageUserState state = ps.readUserState(userId);
2407
2408        return PackageParser.generatePackageInfo(p, gids, flags,
2409                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2410    }
2411
2412    @Override
2413    public boolean isPackageFrozen(String packageName) {
2414        synchronized (mPackages) {
2415            final PackageSetting ps = mSettings.mPackages.get(packageName);
2416            if (ps != null) {
2417                return ps.frozen;
2418            }
2419        }
2420        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2421        return true;
2422    }
2423
2424    @Override
2425    public boolean isPackageAvailable(String packageName, int userId) {
2426        if (!sUserManager.exists(userId)) return false;
2427        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2428        synchronized (mPackages) {
2429            PackageParser.Package p = mPackages.get(packageName);
2430            if (p != null) {
2431                final PackageSetting ps = (PackageSetting) p.mExtras;
2432                if (ps != null) {
2433                    final PackageUserState state = ps.readUserState(userId);
2434                    if (state != null) {
2435                        return PackageParser.isAvailable(state);
2436                    }
2437                }
2438            }
2439        }
2440        return false;
2441    }
2442
2443    @Override
2444    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2445        if (!sUserManager.exists(userId)) return null;
2446        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2447        // reader
2448        synchronized (mPackages) {
2449            PackageParser.Package p = mPackages.get(packageName);
2450            if (DEBUG_PACKAGE_INFO)
2451                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2452            if (p != null) {
2453                return generatePackageInfo(p, flags, userId);
2454            }
2455            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2456                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2457            }
2458        }
2459        return null;
2460    }
2461
2462    @Override
2463    public String[] currentToCanonicalPackageNames(String[] names) {
2464        String[] out = new String[names.length];
2465        // reader
2466        synchronized (mPackages) {
2467            for (int i=names.length-1; i>=0; i--) {
2468                PackageSetting ps = mSettings.mPackages.get(names[i]);
2469                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2470            }
2471        }
2472        return out;
2473    }
2474
2475    @Override
2476    public String[] canonicalToCurrentPackageNames(String[] names) {
2477        String[] out = new String[names.length];
2478        // reader
2479        synchronized (mPackages) {
2480            for (int i=names.length-1; i>=0; i--) {
2481                String cur = mSettings.mRenamedPackages.get(names[i]);
2482                out[i] = cur != null ? cur : names[i];
2483            }
2484        }
2485        return out;
2486    }
2487
2488    @Override
2489    public int getPackageUid(String packageName, int userId) {
2490        if (!sUserManager.exists(userId)) return -1;
2491        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2492
2493        // reader
2494        synchronized (mPackages) {
2495            PackageParser.Package p = mPackages.get(packageName);
2496            if(p != null) {
2497                return UserHandle.getUid(userId, p.applicationInfo.uid);
2498            }
2499            PackageSetting ps = mSettings.mPackages.get(packageName);
2500            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2501                return -1;
2502            }
2503            p = ps.pkg;
2504            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2505        }
2506    }
2507
2508    @Override
2509    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2510        if (!sUserManager.exists(userId)) {
2511            return null;
2512        }
2513
2514        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2515                "getPackageGids");
2516
2517        // reader
2518        synchronized (mPackages) {
2519            PackageParser.Package p = mPackages.get(packageName);
2520            if (DEBUG_PACKAGE_INFO) {
2521                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2522            }
2523            if (p != null) {
2524                PackageSetting ps = (PackageSetting) p.mExtras;
2525                return ps.getPermissionsState().computeGids(userId);
2526            }
2527        }
2528
2529        return null;
2530    }
2531
2532    static PermissionInfo generatePermissionInfo(
2533            BasePermission bp, int flags) {
2534        if (bp.perm != null) {
2535            return PackageParser.generatePermissionInfo(bp.perm, flags);
2536        }
2537        PermissionInfo pi = new PermissionInfo();
2538        pi.name = bp.name;
2539        pi.packageName = bp.sourcePackage;
2540        pi.nonLocalizedLabel = bp.name;
2541        pi.protectionLevel = bp.protectionLevel;
2542        return pi;
2543    }
2544
2545    @Override
2546    public PermissionInfo getPermissionInfo(String name, int flags) {
2547        // reader
2548        synchronized (mPackages) {
2549            final BasePermission p = mSettings.mPermissions.get(name);
2550            if (p != null) {
2551                return generatePermissionInfo(p, flags);
2552            }
2553            return null;
2554        }
2555    }
2556
2557    @Override
2558    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2559        // reader
2560        synchronized (mPackages) {
2561            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2562            for (BasePermission p : mSettings.mPermissions.values()) {
2563                if (group == null) {
2564                    if (p.perm == null || p.perm.info.group == null) {
2565                        out.add(generatePermissionInfo(p, flags));
2566                    }
2567                } else {
2568                    if (p.perm != null && group.equals(p.perm.info.group)) {
2569                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2570                    }
2571                }
2572            }
2573
2574            if (out.size() > 0) {
2575                return out;
2576            }
2577            return mPermissionGroups.containsKey(group) ? out : null;
2578        }
2579    }
2580
2581    @Override
2582    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2583        // reader
2584        synchronized (mPackages) {
2585            return PackageParser.generatePermissionGroupInfo(
2586                    mPermissionGroups.get(name), flags);
2587        }
2588    }
2589
2590    @Override
2591    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2592        // reader
2593        synchronized (mPackages) {
2594            final int N = mPermissionGroups.size();
2595            ArrayList<PermissionGroupInfo> out
2596                    = new ArrayList<PermissionGroupInfo>(N);
2597            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2598                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2599            }
2600            return out;
2601        }
2602    }
2603
2604    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2605            int userId) {
2606        if (!sUserManager.exists(userId)) return null;
2607        PackageSetting ps = mSettings.mPackages.get(packageName);
2608        if (ps != null) {
2609            if (ps.pkg == null) {
2610                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2611                        flags, userId);
2612                if (pInfo != null) {
2613                    return pInfo.applicationInfo;
2614                }
2615                return null;
2616            }
2617            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2618                    ps.readUserState(userId), userId);
2619        }
2620        return null;
2621    }
2622
2623    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2624            int userId) {
2625        if (!sUserManager.exists(userId)) return null;
2626        PackageSetting ps = mSettings.mPackages.get(packageName);
2627        if (ps != null) {
2628            PackageParser.Package pkg = ps.pkg;
2629            if (pkg == null) {
2630                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2631                    return null;
2632                }
2633                // Only data remains, so we aren't worried about code paths
2634                pkg = new PackageParser.Package(packageName);
2635                pkg.applicationInfo.packageName = packageName;
2636                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2637                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2638                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2639                        packageName, userId).getAbsolutePath();
2640                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2641                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2642            }
2643            return generatePackageInfo(pkg, flags, userId);
2644        }
2645        return null;
2646    }
2647
2648    @Override
2649    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2650        if (!sUserManager.exists(userId)) return null;
2651        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2652        // writer
2653        synchronized (mPackages) {
2654            PackageParser.Package p = mPackages.get(packageName);
2655            if (DEBUG_PACKAGE_INFO) Log.v(
2656                    TAG, "getApplicationInfo " + packageName
2657                    + ": " + p);
2658            if (p != null) {
2659                PackageSetting ps = mSettings.mPackages.get(packageName);
2660                if (ps == null) return null;
2661                // Note: isEnabledLP() does not apply here - always return info
2662                return PackageParser.generateApplicationInfo(
2663                        p, flags, ps.readUserState(userId), userId);
2664            }
2665            if ("android".equals(packageName)||"system".equals(packageName)) {
2666                return mAndroidApplication;
2667            }
2668            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2669                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2670            }
2671        }
2672        return null;
2673    }
2674
2675    @Override
2676    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2677            final IPackageDataObserver observer) {
2678        mContext.enforceCallingOrSelfPermission(
2679                android.Manifest.permission.CLEAR_APP_CACHE, null);
2680        // Queue up an async operation since clearing cache may take a little while.
2681        mHandler.post(new Runnable() {
2682            public void run() {
2683                mHandler.removeCallbacks(this);
2684                int retCode = -1;
2685                synchronized (mInstallLock) {
2686                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2687                    if (retCode < 0) {
2688                        Slog.w(TAG, "Couldn't clear application caches");
2689                    }
2690                }
2691                if (observer != null) {
2692                    try {
2693                        observer.onRemoveCompleted(null, (retCode >= 0));
2694                    } catch (RemoteException e) {
2695                        Slog.w(TAG, "RemoveException when invoking call back");
2696                    }
2697                }
2698            }
2699        });
2700    }
2701
2702    @Override
2703    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2704            final IntentSender pi) {
2705        mContext.enforceCallingOrSelfPermission(
2706                android.Manifest.permission.CLEAR_APP_CACHE, null);
2707        // Queue up an async operation since clearing cache may take a little while.
2708        mHandler.post(new Runnable() {
2709            public void run() {
2710                mHandler.removeCallbacks(this);
2711                int retCode = -1;
2712                synchronized (mInstallLock) {
2713                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2714                    if (retCode < 0) {
2715                        Slog.w(TAG, "Couldn't clear application caches");
2716                    }
2717                }
2718                if(pi != null) {
2719                    try {
2720                        // Callback via pending intent
2721                        int code = (retCode >= 0) ? 1 : 0;
2722                        pi.sendIntent(null, code, null,
2723                                null, null);
2724                    } catch (SendIntentException e1) {
2725                        Slog.i(TAG, "Failed to send pending intent");
2726                    }
2727                }
2728            }
2729        });
2730    }
2731
2732    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2733        synchronized (mInstallLock) {
2734            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2735                throw new IOException("Failed to free enough space");
2736            }
2737        }
2738    }
2739
2740    @Override
2741    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2742        if (!sUserManager.exists(userId)) return null;
2743        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2744        synchronized (mPackages) {
2745            PackageParser.Activity a = mActivities.mActivities.get(component);
2746
2747            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2748            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2749                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2750                if (ps == null) return null;
2751                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2752                        userId);
2753            }
2754            if (mResolveComponentName.equals(component)) {
2755                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2756                        new PackageUserState(), userId);
2757            }
2758        }
2759        return null;
2760    }
2761
2762    @Override
2763    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2764            String resolvedType) {
2765        synchronized (mPackages) {
2766            PackageParser.Activity a = mActivities.mActivities.get(component);
2767            if (a == null) {
2768                return false;
2769            }
2770            for (int i=0; i<a.intents.size(); i++) {
2771                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2772                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2773                    return true;
2774                }
2775            }
2776            return false;
2777        }
2778    }
2779
2780    @Override
2781    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2782        if (!sUserManager.exists(userId)) return null;
2783        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2784        synchronized (mPackages) {
2785            PackageParser.Activity a = mReceivers.mActivities.get(component);
2786            if (DEBUG_PACKAGE_INFO) Log.v(
2787                TAG, "getReceiverInfo " + component + ": " + a);
2788            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2789                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2790                if (ps == null) return null;
2791                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2792                        userId);
2793            }
2794        }
2795        return null;
2796    }
2797
2798    @Override
2799    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2800        if (!sUserManager.exists(userId)) return null;
2801        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2802        synchronized (mPackages) {
2803            PackageParser.Service s = mServices.mServices.get(component);
2804            if (DEBUG_PACKAGE_INFO) Log.v(
2805                TAG, "getServiceInfo " + component + ": " + s);
2806            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2807                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2808                if (ps == null) return null;
2809                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2810                        userId);
2811            }
2812        }
2813        return null;
2814    }
2815
2816    @Override
2817    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2818        if (!sUserManager.exists(userId)) return null;
2819        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2820        synchronized (mPackages) {
2821            PackageParser.Provider p = mProviders.mProviders.get(component);
2822            if (DEBUG_PACKAGE_INFO) Log.v(
2823                TAG, "getProviderInfo " + component + ": " + p);
2824            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2825                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2826                if (ps == null) return null;
2827                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2828                        userId);
2829            }
2830        }
2831        return null;
2832    }
2833
2834    @Override
2835    public String[] getSystemSharedLibraryNames() {
2836        Set<String> libSet;
2837        synchronized (mPackages) {
2838            libSet = mSharedLibraries.keySet();
2839            int size = libSet.size();
2840            if (size > 0) {
2841                String[] libs = new String[size];
2842                libSet.toArray(libs);
2843                return libs;
2844            }
2845        }
2846        return null;
2847    }
2848
2849    /**
2850     * @hide
2851     */
2852    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2853        synchronized (mPackages) {
2854            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2855            if (lib != null && lib.apk != null) {
2856                return mPackages.get(lib.apk);
2857            }
2858        }
2859        return null;
2860    }
2861
2862    @Override
2863    public FeatureInfo[] getSystemAvailableFeatures() {
2864        Collection<FeatureInfo> featSet;
2865        synchronized (mPackages) {
2866            featSet = mAvailableFeatures.values();
2867            int size = featSet.size();
2868            if (size > 0) {
2869                FeatureInfo[] features = new FeatureInfo[size+1];
2870                featSet.toArray(features);
2871                FeatureInfo fi = new FeatureInfo();
2872                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2873                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2874                features[size] = fi;
2875                return features;
2876            }
2877        }
2878        return null;
2879    }
2880
2881    @Override
2882    public boolean hasSystemFeature(String name) {
2883        synchronized (mPackages) {
2884            return mAvailableFeatures.containsKey(name);
2885        }
2886    }
2887
2888    private void checkValidCaller(int uid, int userId) {
2889        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2890            return;
2891
2892        throw new SecurityException("Caller uid=" + uid
2893                + " is not privileged to communicate with user=" + userId);
2894    }
2895
2896    @Override
2897    public int checkPermission(String permName, String pkgName, int userId) {
2898        if (!sUserManager.exists(userId)) {
2899            return PackageManager.PERMISSION_DENIED;
2900        }
2901
2902        synchronized (mPackages) {
2903            final PackageParser.Package p = mPackages.get(pkgName);
2904            if (p != null && p.mExtras != null) {
2905                final PackageSetting ps = (PackageSetting) p.mExtras;
2906                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2907                    return PackageManager.PERMISSION_GRANTED;
2908                }
2909            }
2910        }
2911
2912        return PackageManager.PERMISSION_DENIED;
2913    }
2914
2915    @Override
2916    public int checkUidPermission(String permName, int uid) {
2917        final int userId = UserHandle.getUserId(uid);
2918
2919        if (!sUserManager.exists(userId)) {
2920            return PackageManager.PERMISSION_DENIED;
2921        }
2922
2923        synchronized (mPackages) {
2924            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2925            if (obj != null) {
2926                final SettingBase ps = (SettingBase) obj;
2927                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2928                    return PackageManager.PERMISSION_GRANTED;
2929                }
2930            } else {
2931                ArraySet<String> perms = mSystemPermissions.get(uid);
2932                if (perms != null && perms.contains(permName)) {
2933                    return PackageManager.PERMISSION_GRANTED;
2934                }
2935            }
2936        }
2937
2938        return PackageManager.PERMISSION_DENIED;
2939    }
2940
2941    /**
2942     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2943     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2944     * @param checkShell TODO(yamasani):
2945     * @param message the message to log on security exception
2946     */
2947    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2948            boolean checkShell, String message) {
2949        if (userId < 0) {
2950            throw new IllegalArgumentException("Invalid userId " + userId);
2951        }
2952        if (checkShell) {
2953            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2954        }
2955        if (userId == UserHandle.getUserId(callingUid)) return;
2956        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2957            if (requireFullPermission) {
2958                mContext.enforceCallingOrSelfPermission(
2959                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2960            } else {
2961                try {
2962                    mContext.enforceCallingOrSelfPermission(
2963                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2964                } catch (SecurityException se) {
2965                    mContext.enforceCallingOrSelfPermission(
2966                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2967                }
2968            }
2969        }
2970    }
2971
2972    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2973        if (callingUid == Process.SHELL_UID) {
2974            if (userHandle >= 0
2975                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2976                throw new SecurityException("Shell does not have permission to access user "
2977                        + userHandle);
2978            } else if (userHandle < 0) {
2979                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2980                        + Debug.getCallers(3));
2981            }
2982        }
2983    }
2984
2985    private BasePermission findPermissionTreeLP(String permName) {
2986        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2987            if (permName.startsWith(bp.name) &&
2988                    permName.length() > bp.name.length() &&
2989                    permName.charAt(bp.name.length()) == '.') {
2990                return bp;
2991            }
2992        }
2993        return null;
2994    }
2995
2996    private BasePermission checkPermissionTreeLP(String permName) {
2997        if (permName != null) {
2998            BasePermission bp = findPermissionTreeLP(permName);
2999            if (bp != null) {
3000                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3001                    return bp;
3002                }
3003                throw new SecurityException("Calling uid "
3004                        + Binder.getCallingUid()
3005                        + " is not allowed to add to permission tree "
3006                        + bp.name + " owned by uid " + bp.uid);
3007            }
3008        }
3009        throw new SecurityException("No permission tree found for " + permName);
3010    }
3011
3012    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3013        if (s1 == null) {
3014            return s2 == null;
3015        }
3016        if (s2 == null) {
3017            return false;
3018        }
3019        if (s1.getClass() != s2.getClass()) {
3020            return false;
3021        }
3022        return s1.equals(s2);
3023    }
3024
3025    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3026        if (pi1.icon != pi2.icon) return false;
3027        if (pi1.logo != pi2.logo) return false;
3028        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3029        if (!compareStrings(pi1.name, pi2.name)) return false;
3030        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3031        // We'll take care of setting this one.
3032        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3033        // These are not currently stored in settings.
3034        //if (!compareStrings(pi1.group, pi2.group)) return false;
3035        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3036        //if (pi1.labelRes != pi2.labelRes) return false;
3037        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3038        return true;
3039    }
3040
3041    int permissionInfoFootprint(PermissionInfo info) {
3042        int size = info.name.length();
3043        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3044        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3045        return size;
3046    }
3047
3048    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3049        int size = 0;
3050        for (BasePermission perm : mSettings.mPermissions.values()) {
3051            if (perm.uid == tree.uid) {
3052                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3053            }
3054        }
3055        return size;
3056    }
3057
3058    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3059        // We calculate the max size of permissions defined by this uid and throw
3060        // if that plus the size of 'info' would exceed our stated maximum.
3061        if (tree.uid != Process.SYSTEM_UID) {
3062            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3063            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3064                throw new SecurityException("Permission tree size cap exceeded");
3065            }
3066        }
3067    }
3068
3069    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3070        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3071            throw new SecurityException("Label must be specified in permission");
3072        }
3073        BasePermission tree = checkPermissionTreeLP(info.name);
3074        BasePermission bp = mSettings.mPermissions.get(info.name);
3075        boolean added = bp == null;
3076        boolean changed = true;
3077        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3078        if (added) {
3079            enforcePermissionCapLocked(info, tree);
3080            bp = new BasePermission(info.name, tree.sourcePackage,
3081                    BasePermission.TYPE_DYNAMIC);
3082        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3083            throw new SecurityException(
3084                    "Not allowed to modify non-dynamic permission "
3085                    + info.name);
3086        } else {
3087            if (bp.protectionLevel == fixedLevel
3088                    && bp.perm.owner.equals(tree.perm.owner)
3089                    && bp.uid == tree.uid
3090                    && comparePermissionInfos(bp.perm.info, info)) {
3091                changed = false;
3092            }
3093        }
3094        bp.protectionLevel = fixedLevel;
3095        info = new PermissionInfo(info);
3096        info.protectionLevel = fixedLevel;
3097        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3098        bp.perm.info.packageName = tree.perm.info.packageName;
3099        bp.uid = tree.uid;
3100        if (added) {
3101            mSettings.mPermissions.put(info.name, bp);
3102        }
3103        if (changed) {
3104            if (!async) {
3105                mSettings.writeLPr();
3106            } else {
3107                scheduleWriteSettingsLocked();
3108            }
3109        }
3110        return added;
3111    }
3112
3113    @Override
3114    public boolean addPermission(PermissionInfo info) {
3115        synchronized (mPackages) {
3116            return addPermissionLocked(info, false);
3117        }
3118    }
3119
3120    @Override
3121    public boolean addPermissionAsync(PermissionInfo info) {
3122        synchronized (mPackages) {
3123            return addPermissionLocked(info, true);
3124        }
3125    }
3126
3127    @Override
3128    public void removePermission(String name) {
3129        synchronized (mPackages) {
3130            checkPermissionTreeLP(name);
3131            BasePermission bp = mSettings.mPermissions.get(name);
3132            if (bp != null) {
3133                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3134                    throw new SecurityException(
3135                            "Not allowed to modify non-dynamic permission "
3136                            + name);
3137                }
3138                mSettings.mPermissions.remove(name);
3139                mSettings.writeLPr();
3140            }
3141        }
3142    }
3143
3144    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3145            BasePermission bp) {
3146        int index = pkg.requestedPermissions.indexOf(bp.name);
3147        if (index == -1) {
3148            throw new SecurityException("Package " + pkg.packageName
3149                    + " has not requested permission " + bp.name);
3150        }
3151        if (!bp.isRuntime()) {
3152            throw new SecurityException("Permission " + bp.name
3153                    + " is not a changeable permission type");
3154        }
3155    }
3156
3157    @Override
3158    public void grantRuntimePermission(String packageName, String name, int userId) {
3159        if (!sUserManager.exists(userId)) {
3160            Log.e(TAG, "No such user:" + userId);
3161            return;
3162        }
3163
3164        mContext.enforceCallingOrSelfPermission(
3165                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3166                "grantRuntimePermission");
3167
3168        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3169                "grantRuntimePermission");
3170
3171        boolean gidsChanged = false;
3172        final SettingBase sb;
3173
3174        synchronized (mPackages) {
3175            final PackageParser.Package pkg = mPackages.get(packageName);
3176            if (pkg == null) {
3177                throw new IllegalArgumentException("Unknown package: " + packageName);
3178            }
3179
3180            final BasePermission bp = mSettings.mPermissions.get(name);
3181            if (bp == null) {
3182                throw new IllegalArgumentException("Unknown permission: " + name);
3183            }
3184
3185            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3186
3187            sb = (SettingBase) pkg.mExtras;
3188            if (sb == null) {
3189                throw new IllegalArgumentException("Unknown package: " + packageName);
3190            }
3191
3192            final PermissionsState permissionsState = sb.getPermissionsState();
3193
3194            final int flags = permissionsState.getPermissionFlags(name, userId);
3195            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3196                throw new SecurityException("Cannot grant system fixed permission: "
3197                        + name + " for package: " + packageName);
3198            }
3199
3200            final int result = permissionsState.grantRuntimePermission(bp, userId);
3201            switch (result) {
3202                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3203                    return;
3204                }
3205
3206                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3207                    gidsChanged = true;
3208                } break;
3209            }
3210
3211            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3212
3213            // Not critical if that is lost - app has to request again.
3214            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3215        }
3216
3217        if (gidsChanged) {
3218            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3219        }
3220    }
3221
3222    @Override
3223    public void revokeRuntimePermission(String packageName, String name, int userId) {
3224        if (!sUserManager.exists(userId)) {
3225            Log.e(TAG, "No such user:" + userId);
3226            return;
3227        }
3228
3229        mContext.enforceCallingOrSelfPermission(
3230                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3231                "revokeRuntimePermission");
3232
3233        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3234                "revokeRuntimePermission");
3235
3236        final SettingBase sb;
3237
3238        synchronized (mPackages) {
3239            final PackageParser.Package pkg = mPackages.get(packageName);
3240            if (pkg == null) {
3241                throw new IllegalArgumentException("Unknown package: " + packageName);
3242            }
3243
3244            final BasePermission bp = mSettings.mPermissions.get(name);
3245            if (bp == null) {
3246                throw new IllegalArgumentException("Unknown permission: " + name);
3247            }
3248
3249            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3250
3251            sb = (SettingBase) pkg.mExtras;
3252            if (sb == null) {
3253                throw new IllegalArgumentException("Unknown package: " + packageName);
3254            }
3255
3256            final PermissionsState permissionsState = sb.getPermissionsState();
3257
3258            final int flags = permissionsState.getPermissionFlags(name, userId);
3259            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3260                throw new SecurityException("Cannot revoke system fixed permission: "
3261                        + name + " for package: " + packageName);
3262            }
3263
3264            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3265                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3266                return;
3267            }
3268
3269            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3270
3271            // Critical, after this call app should never have the permission.
3272            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3273        }
3274
3275        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3276    }
3277
3278    @Override
3279    public int getPermissionFlags(String name, String packageName, int userId) {
3280        if (!sUserManager.exists(userId)) {
3281            return 0;
3282        }
3283
3284        mContext.enforceCallingOrSelfPermission(
3285                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3286                "getPermissionFlags");
3287
3288        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3289                "getPermissionFlags");
3290
3291        synchronized (mPackages) {
3292            final PackageParser.Package pkg = mPackages.get(packageName);
3293            if (pkg == null) {
3294                throw new IllegalArgumentException("Unknown package: " + packageName);
3295            }
3296
3297            final BasePermission bp = mSettings.mPermissions.get(name);
3298            if (bp == null) {
3299                throw new IllegalArgumentException("Unknown permission: " + name);
3300            }
3301
3302            SettingBase sb = (SettingBase) pkg.mExtras;
3303            if (sb == null) {
3304                throw new IllegalArgumentException("Unknown package: " + packageName);
3305            }
3306
3307            PermissionsState permissionsState = sb.getPermissionsState();
3308            return permissionsState.getPermissionFlags(name, userId);
3309        }
3310    }
3311
3312    @Override
3313    public void updatePermissionFlags(String name, String packageName, int flagMask,
3314            int flagValues, int userId) {
3315        if (!sUserManager.exists(userId)) {
3316            return;
3317        }
3318
3319        mContext.enforceCallingOrSelfPermission(
3320                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3321                "updatePermissionFlags");
3322
3323        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3324                "updatePermissionFlags");
3325
3326        // Only the system can change policy flags.
3327        if (getCallingUid() != Process.SYSTEM_UID) {
3328            flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3329            flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3330        }
3331
3332        // Only the package manager can change system flags.
3333        flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3334        flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3335
3336        synchronized (mPackages) {
3337            final PackageParser.Package pkg = mPackages.get(packageName);
3338            if (pkg == null) {
3339                throw new IllegalArgumentException("Unknown package: " + packageName);
3340            }
3341
3342            final BasePermission bp = mSettings.mPermissions.get(name);
3343            if (bp == null) {
3344                throw new IllegalArgumentException("Unknown permission: " + name);
3345            }
3346
3347            SettingBase sb = (SettingBase) pkg.mExtras;
3348            if (sb == null) {
3349                throw new IllegalArgumentException("Unknown package: " + packageName);
3350            }
3351
3352            PermissionsState permissionsState = sb.getPermissionsState();
3353
3354            // Only the package manager can change flags for system component permissions.
3355            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3356            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3357                return;
3358            }
3359
3360            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3361                // Install and runtime permissions are stored in different places,
3362                // so figure out what permission changed and persist the change.
3363                if (permissionsState.getInstallPermissionState(name) != null) {
3364                    scheduleWriteSettingsLocked();
3365                } else if (permissionsState.getRuntimePermissionState(name, userId) != null) {
3366                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3367                }
3368            }
3369        }
3370    }
3371
3372    @Override
3373    public boolean shouldShowRequestPermissionRationale(String permissionName,
3374            String packageName, int userId) {
3375        if (UserHandle.getCallingUserId() != userId) {
3376            mContext.enforceCallingPermission(
3377                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3378                    "canShowRequestPermissionRationale for user " + userId);
3379        }
3380
3381        final int uid = getPackageUid(packageName, userId);
3382        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3383            return false;
3384        }
3385
3386        if (checkPermission(permissionName, packageName, userId)
3387                == PackageManager.PERMISSION_GRANTED) {
3388            return false;
3389        }
3390
3391        final int flags;
3392
3393        final long identity = Binder.clearCallingIdentity();
3394        try {
3395            flags = getPermissionFlags(permissionName,
3396                    packageName, userId);
3397        } finally {
3398            Binder.restoreCallingIdentity(identity);
3399        }
3400
3401        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3402                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3403                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3404
3405        if ((flags & fixedFlags) != 0) {
3406            return false;
3407        }
3408
3409        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3410    }
3411
3412    @Override
3413    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3414        mContext.enforceCallingOrSelfPermission(
3415                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3416                "addOnPermissionsChangeListener");
3417
3418        synchronized (mPackages) {
3419            mOnPermissionChangeListeners.addListenerLocked(listener);
3420        }
3421    }
3422
3423    @Override
3424    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3425        synchronized (mPackages) {
3426            mOnPermissionChangeListeners.removeListenerLocked(listener);
3427        }
3428    }
3429
3430    @Override
3431    public boolean isProtectedBroadcast(String actionName) {
3432        synchronized (mPackages) {
3433            return mProtectedBroadcasts.contains(actionName);
3434        }
3435    }
3436
3437    @Override
3438    public int checkSignatures(String pkg1, String pkg2) {
3439        synchronized (mPackages) {
3440            final PackageParser.Package p1 = mPackages.get(pkg1);
3441            final PackageParser.Package p2 = mPackages.get(pkg2);
3442            if (p1 == null || p1.mExtras == null
3443                    || p2 == null || p2.mExtras == null) {
3444                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3445            }
3446            return compareSignatures(p1.mSignatures, p2.mSignatures);
3447        }
3448    }
3449
3450    @Override
3451    public int checkUidSignatures(int uid1, int uid2) {
3452        // Map to base uids.
3453        uid1 = UserHandle.getAppId(uid1);
3454        uid2 = UserHandle.getAppId(uid2);
3455        // reader
3456        synchronized (mPackages) {
3457            Signature[] s1;
3458            Signature[] s2;
3459            Object obj = mSettings.getUserIdLPr(uid1);
3460            if (obj != null) {
3461                if (obj instanceof SharedUserSetting) {
3462                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3463                } else if (obj instanceof PackageSetting) {
3464                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3465                } else {
3466                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3467                }
3468            } else {
3469                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3470            }
3471            obj = mSettings.getUserIdLPr(uid2);
3472            if (obj != null) {
3473                if (obj instanceof SharedUserSetting) {
3474                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3475                } else if (obj instanceof PackageSetting) {
3476                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3477                } else {
3478                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3479                }
3480            } else {
3481                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3482            }
3483            return compareSignatures(s1, s2);
3484        }
3485    }
3486
3487    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3488        final long identity = Binder.clearCallingIdentity();
3489        try {
3490            if (sb instanceof SharedUserSetting) {
3491                SharedUserSetting sus = (SharedUserSetting) sb;
3492                final int packageCount = sus.packages.size();
3493                for (int i = 0; i < packageCount; i++) {
3494                    PackageSetting susPs = sus.packages.valueAt(i);
3495                    if (userId == UserHandle.USER_ALL) {
3496                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3497                    } else {
3498                        final int uid = UserHandle.getUid(userId, susPs.appId);
3499                        killUid(uid, reason);
3500                    }
3501                }
3502            } else if (sb instanceof PackageSetting) {
3503                PackageSetting ps = (PackageSetting) sb;
3504                if (userId == UserHandle.USER_ALL) {
3505                    killApplication(ps.pkg.packageName, ps.appId, reason);
3506                } else {
3507                    final int uid = UserHandle.getUid(userId, ps.appId);
3508                    killUid(uid, reason);
3509                }
3510            }
3511        } finally {
3512            Binder.restoreCallingIdentity(identity);
3513        }
3514    }
3515
3516    private static void killUid(int uid, String reason) {
3517        IActivityManager am = ActivityManagerNative.getDefault();
3518        if (am != null) {
3519            try {
3520                am.killUid(uid, reason);
3521            } catch (RemoteException e) {
3522                /* ignore - same process */
3523            }
3524        }
3525    }
3526
3527    /**
3528     * Compares two sets of signatures. Returns:
3529     * <br />
3530     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3531     * <br />
3532     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3533     * <br />
3534     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3535     * <br />
3536     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3537     * <br />
3538     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3539     */
3540    static int compareSignatures(Signature[] s1, Signature[] s2) {
3541        if (s1 == null) {
3542            return s2 == null
3543                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3544                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3545        }
3546
3547        if (s2 == null) {
3548            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3549        }
3550
3551        if (s1.length != s2.length) {
3552            return PackageManager.SIGNATURE_NO_MATCH;
3553        }
3554
3555        // Since both signature sets are of size 1, we can compare without HashSets.
3556        if (s1.length == 1) {
3557            return s1[0].equals(s2[0]) ?
3558                    PackageManager.SIGNATURE_MATCH :
3559                    PackageManager.SIGNATURE_NO_MATCH;
3560        }
3561
3562        ArraySet<Signature> set1 = new ArraySet<Signature>();
3563        for (Signature sig : s1) {
3564            set1.add(sig);
3565        }
3566        ArraySet<Signature> set2 = new ArraySet<Signature>();
3567        for (Signature sig : s2) {
3568            set2.add(sig);
3569        }
3570        // Make sure s2 contains all signatures in s1.
3571        if (set1.equals(set2)) {
3572            return PackageManager.SIGNATURE_MATCH;
3573        }
3574        return PackageManager.SIGNATURE_NO_MATCH;
3575    }
3576
3577    /**
3578     * If the database version for this type of package (internal storage or
3579     * external storage) is less than the version where package signatures
3580     * were updated, return true.
3581     */
3582    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3583        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3584                DatabaseVersion.SIGNATURE_END_ENTITY))
3585                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3586                        DatabaseVersion.SIGNATURE_END_ENTITY));
3587    }
3588
3589    /**
3590     * Used for backward compatibility to make sure any packages with
3591     * certificate chains get upgraded to the new style. {@code existingSigs}
3592     * will be in the old format (since they were stored on disk from before the
3593     * system upgrade) and {@code scannedSigs} will be in the newer format.
3594     */
3595    private int compareSignaturesCompat(PackageSignatures existingSigs,
3596            PackageParser.Package scannedPkg) {
3597        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3598            return PackageManager.SIGNATURE_NO_MATCH;
3599        }
3600
3601        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3602        for (Signature sig : existingSigs.mSignatures) {
3603            existingSet.add(sig);
3604        }
3605        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3606        for (Signature sig : scannedPkg.mSignatures) {
3607            try {
3608                Signature[] chainSignatures = sig.getChainSignatures();
3609                for (Signature chainSig : chainSignatures) {
3610                    scannedCompatSet.add(chainSig);
3611                }
3612            } catch (CertificateEncodingException e) {
3613                scannedCompatSet.add(sig);
3614            }
3615        }
3616        /*
3617         * Make sure the expanded scanned set contains all signatures in the
3618         * existing one.
3619         */
3620        if (scannedCompatSet.equals(existingSet)) {
3621            // Migrate the old signatures to the new scheme.
3622            existingSigs.assignSignatures(scannedPkg.mSignatures);
3623            // The new KeySets will be re-added later in the scanning process.
3624            synchronized (mPackages) {
3625                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3626            }
3627            return PackageManager.SIGNATURE_MATCH;
3628        }
3629        return PackageManager.SIGNATURE_NO_MATCH;
3630    }
3631
3632    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3633        if (isExternal(scannedPkg)) {
3634            return mSettings.isExternalDatabaseVersionOlderThan(
3635                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3636        } else {
3637            return mSettings.isInternalDatabaseVersionOlderThan(
3638                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3639        }
3640    }
3641
3642    private int compareSignaturesRecover(PackageSignatures existingSigs,
3643            PackageParser.Package scannedPkg) {
3644        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3645            return PackageManager.SIGNATURE_NO_MATCH;
3646        }
3647
3648        String msg = null;
3649        try {
3650            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3651                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3652                        + scannedPkg.packageName);
3653                return PackageManager.SIGNATURE_MATCH;
3654            }
3655        } catch (CertificateException e) {
3656            msg = e.getMessage();
3657        }
3658
3659        logCriticalInfo(Log.INFO,
3660                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3661        return PackageManager.SIGNATURE_NO_MATCH;
3662    }
3663
3664    @Override
3665    public String[] getPackagesForUid(int uid) {
3666        uid = UserHandle.getAppId(uid);
3667        // reader
3668        synchronized (mPackages) {
3669            Object obj = mSettings.getUserIdLPr(uid);
3670            if (obj instanceof SharedUserSetting) {
3671                final SharedUserSetting sus = (SharedUserSetting) obj;
3672                final int N = sus.packages.size();
3673                final String[] res = new String[N];
3674                final Iterator<PackageSetting> it = sus.packages.iterator();
3675                int i = 0;
3676                while (it.hasNext()) {
3677                    res[i++] = it.next().name;
3678                }
3679                return res;
3680            } else if (obj instanceof PackageSetting) {
3681                final PackageSetting ps = (PackageSetting) obj;
3682                return new String[] { ps.name };
3683            }
3684        }
3685        return null;
3686    }
3687
3688    @Override
3689    public String getNameForUid(int uid) {
3690        // reader
3691        synchronized (mPackages) {
3692            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3693            if (obj instanceof SharedUserSetting) {
3694                final SharedUserSetting sus = (SharedUserSetting) obj;
3695                return sus.name + ":" + sus.userId;
3696            } else if (obj instanceof PackageSetting) {
3697                final PackageSetting ps = (PackageSetting) obj;
3698                return ps.name;
3699            }
3700        }
3701        return null;
3702    }
3703
3704    @Override
3705    public int getUidForSharedUser(String sharedUserName) {
3706        if(sharedUserName == null) {
3707            return -1;
3708        }
3709        // reader
3710        synchronized (mPackages) {
3711            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3712            if (suid == null) {
3713                return -1;
3714            }
3715            return suid.userId;
3716        }
3717    }
3718
3719    @Override
3720    public int getFlagsForUid(int uid) {
3721        synchronized (mPackages) {
3722            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3723            if (obj instanceof SharedUserSetting) {
3724                final SharedUserSetting sus = (SharedUserSetting) obj;
3725                return sus.pkgFlags;
3726            } else if (obj instanceof PackageSetting) {
3727                final PackageSetting ps = (PackageSetting) obj;
3728                return ps.pkgFlags;
3729            }
3730        }
3731        return 0;
3732    }
3733
3734    @Override
3735    public int getPrivateFlagsForUid(int uid) {
3736        synchronized (mPackages) {
3737            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3738            if (obj instanceof SharedUserSetting) {
3739                final SharedUserSetting sus = (SharedUserSetting) obj;
3740                return sus.pkgPrivateFlags;
3741            } else if (obj instanceof PackageSetting) {
3742                final PackageSetting ps = (PackageSetting) obj;
3743                return ps.pkgPrivateFlags;
3744            }
3745        }
3746        return 0;
3747    }
3748
3749    @Override
3750    public boolean isUidPrivileged(int uid) {
3751        uid = UserHandle.getAppId(uid);
3752        // reader
3753        synchronized (mPackages) {
3754            Object obj = mSettings.getUserIdLPr(uid);
3755            if (obj instanceof SharedUserSetting) {
3756                final SharedUserSetting sus = (SharedUserSetting) obj;
3757                final Iterator<PackageSetting> it = sus.packages.iterator();
3758                while (it.hasNext()) {
3759                    if (it.next().isPrivileged()) {
3760                        return true;
3761                    }
3762                }
3763            } else if (obj instanceof PackageSetting) {
3764                final PackageSetting ps = (PackageSetting) obj;
3765                return ps.isPrivileged();
3766            }
3767        }
3768        return false;
3769    }
3770
3771    @Override
3772    public String[] getAppOpPermissionPackages(String permissionName) {
3773        synchronized (mPackages) {
3774            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3775            if (pkgs == null) {
3776                return null;
3777            }
3778            return pkgs.toArray(new String[pkgs.size()]);
3779        }
3780    }
3781
3782    @Override
3783    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3784            int flags, int userId) {
3785        if (!sUserManager.exists(userId)) return null;
3786        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3787        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3788        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3789    }
3790
3791    @Override
3792    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3793            IntentFilter filter, int match, ComponentName activity) {
3794        final int userId = UserHandle.getCallingUserId();
3795        if (DEBUG_PREFERRED) {
3796            Log.v(TAG, "setLastChosenActivity intent=" + intent
3797                + " resolvedType=" + resolvedType
3798                + " flags=" + flags
3799                + " filter=" + filter
3800                + " match=" + match
3801                + " activity=" + activity);
3802            filter.dump(new PrintStreamPrinter(System.out), "    ");
3803        }
3804        intent.setComponent(null);
3805        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3806        // Find any earlier preferred or last chosen entries and nuke them
3807        findPreferredActivity(intent, resolvedType,
3808                flags, query, 0, false, true, false, userId);
3809        // Add the new activity as the last chosen for this filter
3810        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3811                "Setting last chosen");
3812    }
3813
3814    @Override
3815    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3816        final int userId = UserHandle.getCallingUserId();
3817        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3818        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3819        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3820                false, false, false, userId);
3821    }
3822
3823    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3824            int flags, List<ResolveInfo> query, int userId) {
3825        if (query != null) {
3826            final int N = query.size();
3827            if (N == 1) {
3828                return query.get(0);
3829            } else if (N > 1) {
3830                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3831                // If there is more than one activity with the same priority,
3832                // then let the user decide between them.
3833                ResolveInfo r0 = query.get(0);
3834                ResolveInfo r1 = query.get(1);
3835                if (DEBUG_INTENT_MATCHING || debug) {
3836                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3837                            + r1.activityInfo.name + "=" + r1.priority);
3838                }
3839                // If the first activity has a higher priority, or a different
3840                // default, then it is always desireable to pick it.
3841                if (r0.priority != r1.priority
3842                        || r0.preferredOrder != r1.preferredOrder
3843                        || r0.isDefault != r1.isDefault) {
3844                    return query.get(0);
3845                }
3846                // If we have saved a preference for a preferred activity for
3847                // this Intent, use that.
3848                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3849                        flags, query, r0.priority, true, false, debug, userId);
3850                if (ri != null) {
3851                    return ri;
3852                }
3853                if (userId != 0) {
3854                    ri = new ResolveInfo(mResolveInfo);
3855                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3856                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3857                            ri.activityInfo.applicationInfo);
3858                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3859                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3860                    return ri;
3861                }
3862                return mResolveInfo;
3863            }
3864        }
3865        return null;
3866    }
3867
3868    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3869            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3870        final int N = query.size();
3871        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3872                .get(userId);
3873        // Get the list of persistent preferred activities that handle the intent
3874        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3875        List<PersistentPreferredActivity> pprefs = ppir != null
3876                ? ppir.queryIntent(intent, resolvedType,
3877                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3878                : null;
3879        if (pprefs != null && pprefs.size() > 0) {
3880            final int M = pprefs.size();
3881            for (int i=0; i<M; i++) {
3882                final PersistentPreferredActivity ppa = pprefs.get(i);
3883                if (DEBUG_PREFERRED || debug) {
3884                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3885                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3886                            + "\n  component=" + ppa.mComponent);
3887                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3888                }
3889                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3890                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3891                if (DEBUG_PREFERRED || debug) {
3892                    Slog.v(TAG, "Found persistent preferred activity:");
3893                    if (ai != null) {
3894                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3895                    } else {
3896                        Slog.v(TAG, "  null");
3897                    }
3898                }
3899                if (ai == null) {
3900                    // This previously registered persistent preferred activity
3901                    // component is no longer known. Ignore it and do NOT remove it.
3902                    continue;
3903                }
3904                for (int j=0; j<N; j++) {
3905                    final ResolveInfo ri = query.get(j);
3906                    if (!ri.activityInfo.applicationInfo.packageName
3907                            .equals(ai.applicationInfo.packageName)) {
3908                        continue;
3909                    }
3910                    if (!ri.activityInfo.name.equals(ai.name)) {
3911                        continue;
3912                    }
3913                    //  Found a persistent preference that can handle the intent.
3914                    if (DEBUG_PREFERRED || debug) {
3915                        Slog.v(TAG, "Returning persistent preferred activity: " +
3916                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3917                    }
3918                    return ri;
3919                }
3920            }
3921        }
3922        return null;
3923    }
3924
3925    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3926            List<ResolveInfo> query, int priority, boolean always,
3927            boolean removeMatches, boolean debug, int userId) {
3928        if (!sUserManager.exists(userId)) return null;
3929        // writer
3930        synchronized (mPackages) {
3931            if (intent.getSelector() != null) {
3932                intent = intent.getSelector();
3933            }
3934            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3935
3936            // Try to find a matching persistent preferred activity.
3937            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3938                    debug, userId);
3939
3940            // If a persistent preferred activity matched, use it.
3941            if (pri != null) {
3942                return pri;
3943            }
3944
3945            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3946            // Get the list of preferred activities that handle the intent
3947            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3948            List<PreferredActivity> prefs = pir != null
3949                    ? pir.queryIntent(intent, resolvedType,
3950                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3951                    : null;
3952            if (prefs != null && prefs.size() > 0) {
3953                boolean changed = false;
3954                try {
3955                    // First figure out how good the original match set is.
3956                    // We will only allow preferred activities that came
3957                    // from the same match quality.
3958                    int match = 0;
3959
3960                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3961
3962                    final int N = query.size();
3963                    for (int j=0; j<N; j++) {
3964                        final ResolveInfo ri = query.get(j);
3965                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3966                                + ": 0x" + Integer.toHexString(match));
3967                        if (ri.match > match) {
3968                            match = ri.match;
3969                        }
3970                    }
3971
3972                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3973                            + Integer.toHexString(match));
3974
3975                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3976                    final int M = prefs.size();
3977                    for (int i=0; i<M; i++) {
3978                        final PreferredActivity pa = prefs.get(i);
3979                        if (DEBUG_PREFERRED || debug) {
3980                            Slog.v(TAG, "Checking PreferredActivity ds="
3981                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3982                                    + "\n  component=" + pa.mPref.mComponent);
3983                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3984                        }
3985                        if (pa.mPref.mMatch != match) {
3986                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3987                                    + Integer.toHexString(pa.mPref.mMatch));
3988                            continue;
3989                        }
3990                        // If it's not an "always" type preferred activity and that's what we're
3991                        // looking for, skip it.
3992                        if (always && !pa.mPref.mAlways) {
3993                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3994                            continue;
3995                        }
3996                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3997                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3998                        if (DEBUG_PREFERRED || debug) {
3999                            Slog.v(TAG, "Found preferred activity:");
4000                            if (ai != null) {
4001                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4002                            } else {
4003                                Slog.v(TAG, "  null");
4004                            }
4005                        }
4006                        if (ai == null) {
4007                            // This previously registered preferred activity
4008                            // component is no longer known.  Most likely an update
4009                            // to the app was installed and in the new version this
4010                            // component no longer exists.  Clean it up by removing
4011                            // it from the preferred activities list, and skip it.
4012                            Slog.w(TAG, "Removing dangling preferred activity: "
4013                                    + pa.mPref.mComponent);
4014                            pir.removeFilter(pa);
4015                            changed = true;
4016                            continue;
4017                        }
4018                        for (int j=0; j<N; j++) {
4019                            final ResolveInfo ri = query.get(j);
4020                            if (!ri.activityInfo.applicationInfo.packageName
4021                                    .equals(ai.applicationInfo.packageName)) {
4022                                continue;
4023                            }
4024                            if (!ri.activityInfo.name.equals(ai.name)) {
4025                                continue;
4026                            }
4027
4028                            if (removeMatches) {
4029                                pir.removeFilter(pa);
4030                                changed = true;
4031                                if (DEBUG_PREFERRED) {
4032                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4033                                }
4034                                break;
4035                            }
4036
4037                            // Okay we found a previously set preferred or last chosen app.
4038                            // If the result set is different from when this
4039                            // was created, we need to clear it and re-ask the
4040                            // user their preference, if we're looking for an "always" type entry.
4041                            if (always && !pa.mPref.sameSet(query)) {
4042                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4043                                        + intent + " type " + resolvedType);
4044                                if (DEBUG_PREFERRED) {
4045                                    Slog.v(TAG, "Removing preferred activity since set changed "
4046                                            + pa.mPref.mComponent);
4047                                }
4048                                pir.removeFilter(pa);
4049                                // Re-add the filter as a "last chosen" entry (!always)
4050                                PreferredActivity lastChosen = new PreferredActivity(
4051                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4052                                pir.addFilter(lastChosen);
4053                                changed = true;
4054                                return null;
4055                            }
4056
4057                            // Yay! Either the set matched or we're looking for the last chosen
4058                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4059                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4060                            return ri;
4061                        }
4062                    }
4063                } finally {
4064                    if (changed) {
4065                        if (DEBUG_PREFERRED) {
4066                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4067                        }
4068                        scheduleWritePackageRestrictionsLocked(userId);
4069                    }
4070                }
4071            }
4072        }
4073        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4074        return null;
4075    }
4076
4077    /*
4078     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4079     */
4080    @Override
4081    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4082            int targetUserId) {
4083        mContext.enforceCallingOrSelfPermission(
4084                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4085        List<CrossProfileIntentFilter> matches =
4086                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4087        if (matches != null) {
4088            int size = matches.size();
4089            for (int i = 0; i < size; i++) {
4090                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4091            }
4092        }
4093        return false;
4094    }
4095
4096    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4097            String resolvedType, int userId) {
4098        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4099        if (resolver != null) {
4100            return resolver.queryIntent(intent, resolvedType, false, userId);
4101        }
4102        return null;
4103    }
4104
4105    @Override
4106    public List<ResolveInfo> queryIntentActivities(Intent intent,
4107            String resolvedType, int flags, int userId) {
4108        if (!sUserManager.exists(userId)) return Collections.emptyList();
4109        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4110        ComponentName comp = intent.getComponent();
4111        if (comp == null) {
4112            if (intent.getSelector() != null) {
4113                intent = intent.getSelector();
4114                comp = intent.getComponent();
4115            }
4116        }
4117
4118        if (comp != null) {
4119            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4120            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4121            if (ai != null) {
4122                final ResolveInfo ri = new ResolveInfo();
4123                ri.activityInfo = ai;
4124                list.add(ri);
4125            }
4126            return list;
4127        }
4128
4129        // reader
4130        synchronized (mPackages) {
4131            final String pkgName = intent.getPackage();
4132            if (pkgName == null) {
4133                List<CrossProfileIntentFilter> matchingFilters =
4134                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4135                // Check for results that need to skip the current profile.
4136                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4137                        resolvedType, flags, userId);
4138                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4139                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4140                    result.add(resolveInfo);
4141                    return filterIfNotPrimaryUser(result, userId);
4142                }
4143
4144                // Check for results in the current profile.
4145                List<ResolveInfo> result = mActivities.queryIntent(
4146                        intent, resolvedType, flags, userId);
4147
4148                // Check for cross profile results.
4149                resolveInfo = queryCrossProfileIntents(
4150                        matchingFilters, intent, resolvedType, flags, userId);
4151                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4152                    result.add(resolveInfo);
4153                    Collections.sort(result, mResolvePrioritySorter);
4154                }
4155                result = filterIfNotPrimaryUser(result, userId);
4156                if (result.size() > 1 && hasWebURI(intent)) {
4157                    return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result);
4158                }
4159                return result;
4160            }
4161            final PackageParser.Package pkg = mPackages.get(pkgName);
4162            if (pkg != null) {
4163                return filterIfNotPrimaryUser(
4164                        mActivities.queryIntentForPackage(
4165                                intent, resolvedType, flags, pkg.activities, userId),
4166                        userId);
4167            }
4168            return new ArrayList<ResolveInfo>();
4169        }
4170    }
4171
4172    private boolean isUserEnabled(int userId) {
4173        long callingId = Binder.clearCallingIdentity();
4174        try {
4175            UserInfo userInfo = sUserManager.getUserInfo(userId);
4176            return userInfo != null && userInfo.isEnabled();
4177        } finally {
4178            Binder.restoreCallingIdentity(callingId);
4179        }
4180    }
4181
4182    /**
4183     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4184     *
4185     * @return filtered list
4186     */
4187    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4188        if (userId == UserHandle.USER_OWNER) {
4189            return resolveInfos;
4190        }
4191        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4192            ResolveInfo info = resolveInfos.get(i);
4193            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4194                resolveInfos.remove(i);
4195            }
4196        }
4197        return resolveInfos;
4198    }
4199
4200    private static boolean hasWebURI(Intent intent) {
4201        if (intent.getData() == null) {
4202            return false;
4203        }
4204        final String scheme = intent.getScheme();
4205        if (TextUtils.isEmpty(scheme)) {
4206            return false;
4207        }
4208        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4209    }
4210
4211    private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr(
4212            int flags, List<ResolveInfo> candidates) {
4213        if (DEBUG_PREFERRED) {
4214            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4215                    candidates.size());
4216        }
4217
4218        final int userId = UserHandle.getCallingUserId();
4219        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4220        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4221        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4222        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4223        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4224
4225        synchronized (mPackages) {
4226            final int count = candidates.size();
4227            // First, try to use the domain prefered App. Partition the candidates into four lists:
4228            // one for the final results, one for the "do not use ever", one for "undefined status"
4229            // and finally one for "Browser App type".
4230            for (int n=0; n<count; n++) {
4231                ResolveInfo info = candidates.get(n);
4232                String packageName = info.activityInfo.packageName;
4233                PackageSetting ps = mSettings.mPackages.get(packageName);
4234                if (ps != null) {
4235                    // Add to the special match all list (Browser use case)
4236                    if (info.handleAllWebDataURI) {
4237                        matchAllList.add(info);
4238                        continue;
4239                    }
4240                    // Try to get the status from User settings first
4241                    int status = getDomainVerificationStatusLPr(ps, userId);
4242                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4243                        alwaysList.add(info);
4244                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4245                        neverList.add(info);
4246                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4247                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4248                        undefinedList.add(info);
4249                    }
4250                }
4251            }
4252            // First try to add the "always" if there is any
4253            if (alwaysList.size() > 0) {
4254                result.addAll(alwaysList);
4255            } else {
4256                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4257                result.addAll(undefinedList);
4258                // Also add Browsers (all of them or only the default one)
4259                if ((flags & MATCH_ALL) != 0) {
4260                    result.addAll(matchAllList);
4261                } else {
4262                    // Try to add the Default Browser if we can
4263                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4264                            UserHandle.myUserId());
4265                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4266                        boolean defaultBrowserFound = false;
4267                        final int browserCount = matchAllList.size();
4268                        for (int n=0; n<browserCount; n++) {
4269                            ResolveInfo browser = matchAllList.get(n);
4270                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4271                                result.add(browser);
4272                                defaultBrowserFound = true;
4273                                break;
4274                            }
4275                        }
4276                        if (!defaultBrowserFound) {
4277                            result.addAll(matchAllList);
4278                        }
4279                    } else {
4280                        result.addAll(matchAllList);
4281                    }
4282                }
4283
4284                // If there is nothing selected, add all candidates and remove the ones that the User
4285                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4286                if (result.size() == 0) {
4287                    result.addAll(candidates);
4288                    result.removeAll(neverList);
4289                }
4290            }
4291        }
4292        if (DEBUG_PREFERRED) {
4293            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4294                    result.size());
4295        }
4296        return result;
4297    }
4298
4299    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4300        int status = ps.getDomainVerificationStatusForUser(userId);
4301        // if none available, get the master status
4302        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4303            if (ps.getIntentFilterVerificationInfo() != null) {
4304                status = ps.getIntentFilterVerificationInfo().getStatus();
4305            }
4306        }
4307        return status;
4308    }
4309
4310    private ResolveInfo querySkipCurrentProfileIntents(
4311            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4312            int flags, int sourceUserId) {
4313        if (matchingFilters != null) {
4314            int size = matchingFilters.size();
4315            for (int i = 0; i < size; i ++) {
4316                CrossProfileIntentFilter filter = matchingFilters.get(i);
4317                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4318                    // Checking if there are activities in the target user that can handle the
4319                    // intent.
4320                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4321                            flags, sourceUserId);
4322                    if (resolveInfo != null) {
4323                        return resolveInfo;
4324                    }
4325                }
4326            }
4327        }
4328        return null;
4329    }
4330
4331    // Return matching ResolveInfo if any for skip current profile intent filters.
4332    private ResolveInfo queryCrossProfileIntents(
4333            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4334            int flags, int sourceUserId) {
4335        if (matchingFilters != null) {
4336            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4337            // match the same intent. For performance reasons, it is better not to
4338            // run queryIntent twice for the same userId
4339            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4340            int size = matchingFilters.size();
4341            for (int i = 0; i < size; i++) {
4342                CrossProfileIntentFilter filter = matchingFilters.get(i);
4343                int targetUserId = filter.getTargetUserId();
4344                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4345                        && !alreadyTriedUserIds.get(targetUserId)) {
4346                    // Checking if there are activities in the target user that can handle the
4347                    // intent.
4348                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4349                            flags, sourceUserId);
4350                    if (resolveInfo != null) return resolveInfo;
4351                    alreadyTriedUserIds.put(targetUserId, true);
4352                }
4353            }
4354        }
4355        return null;
4356    }
4357
4358    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4359            String resolvedType, int flags, int sourceUserId) {
4360        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4361                resolvedType, flags, filter.getTargetUserId());
4362        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4363            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4364        }
4365        return null;
4366    }
4367
4368    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4369            int sourceUserId, int targetUserId) {
4370        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4371        String className;
4372        if (targetUserId == UserHandle.USER_OWNER) {
4373            className = FORWARD_INTENT_TO_USER_OWNER;
4374        } else {
4375            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4376        }
4377        ComponentName forwardingActivityComponentName = new ComponentName(
4378                mAndroidApplication.packageName, className);
4379        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4380                sourceUserId);
4381        if (targetUserId == UserHandle.USER_OWNER) {
4382            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4383            forwardingResolveInfo.noResourceId = true;
4384        }
4385        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4386        forwardingResolveInfo.priority = 0;
4387        forwardingResolveInfo.preferredOrder = 0;
4388        forwardingResolveInfo.match = 0;
4389        forwardingResolveInfo.isDefault = true;
4390        forwardingResolveInfo.filter = filter;
4391        forwardingResolveInfo.targetUserId = targetUserId;
4392        return forwardingResolveInfo;
4393    }
4394
4395    @Override
4396    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4397            Intent[] specifics, String[] specificTypes, Intent intent,
4398            String resolvedType, int flags, int userId) {
4399        if (!sUserManager.exists(userId)) return Collections.emptyList();
4400        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4401                false, "query intent activity options");
4402        final String resultsAction = intent.getAction();
4403
4404        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4405                | PackageManager.GET_RESOLVED_FILTER, userId);
4406
4407        if (DEBUG_INTENT_MATCHING) {
4408            Log.v(TAG, "Query " + intent + ": " + results);
4409        }
4410
4411        int specificsPos = 0;
4412        int N;
4413
4414        // todo: note that the algorithm used here is O(N^2).  This
4415        // isn't a problem in our current environment, but if we start running
4416        // into situations where we have more than 5 or 10 matches then this
4417        // should probably be changed to something smarter...
4418
4419        // First we go through and resolve each of the specific items
4420        // that were supplied, taking care of removing any corresponding
4421        // duplicate items in the generic resolve list.
4422        if (specifics != null) {
4423            for (int i=0; i<specifics.length; i++) {
4424                final Intent sintent = specifics[i];
4425                if (sintent == null) {
4426                    continue;
4427                }
4428
4429                if (DEBUG_INTENT_MATCHING) {
4430                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4431                }
4432
4433                String action = sintent.getAction();
4434                if (resultsAction != null && resultsAction.equals(action)) {
4435                    // If this action was explicitly requested, then don't
4436                    // remove things that have it.
4437                    action = null;
4438                }
4439
4440                ResolveInfo ri = null;
4441                ActivityInfo ai = null;
4442
4443                ComponentName comp = sintent.getComponent();
4444                if (comp == null) {
4445                    ri = resolveIntent(
4446                        sintent,
4447                        specificTypes != null ? specificTypes[i] : null,
4448                            flags, userId);
4449                    if (ri == null) {
4450                        continue;
4451                    }
4452                    if (ri == mResolveInfo) {
4453                        // ACK!  Must do something better with this.
4454                    }
4455                    ai = ri.activityInfo;
4456                    comp = new ComponentName(ai.applicationInfo.packageName,
4457                            ai.name);
4458                } else {
4459                    ai = getActivityInfo(comp, flags, userId);
4460                    if (ai == null) {
4461                        continue;
4462                    }
4463                }
4464
4465                // Look for any generic query activities that are duplicates
4466                // of this specific one, and remove them from the results.
4467                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4468                N = results.size();
4469                int j;
4470                for (j=specificsPos; j<N; j++) {
4471                    ResolveInfo sri = results.get(j);
4472                    if ((sri.activityInfo.name.equals(comp.getClassName())
4473                            && sri.activityInfo.applicationInfo.packageName.equals(
4474                                    comp.getPackageName()))
4475                        || (action != null && sri.filter.matchAction(action))) {
4476                        results.remove(j);
4477                        if (DEBUG_INTENT_MATCHING) Log.v(
4478                            TAG, "Removing duplicate item from " + j
4479                            + " due to specific " + specificsPos);
4480                        if (ri == null) {
4481                            ri = sri;
4482                        }
4483                        j--;
4484                        N--;
4485                    }
4486                }
4487
4488                // Add this specific item to its proper place.
4489                if (ri == null) {
4490                    ri = new ResolveInfo();
4491                    ri.activityInfo = ai;
4492                }
4493                results.add(specificsPos, ri);
4494                ri.specificIndex = i;
4495                specificsPos++;
4496            }
4497        }
4498
4499        // Now we go through the remaining generic results and remove any
4500        // duplicate actions that are found here.
4501        N = results.size();
4502        for (int i=specificsPos; i<N-1; i++) {
4503            final ResolveInfo rii = results.get(i);
4504            if (rii.filter == null) {
4505                continue;
4506            }
4507
4508            // Iterate over all of the actions of this result's intent
4509            // filter...  typically this should be just one.
4510            final Iterator<String> it = rii.filter.actionsIterator();
4511            if (it == null) {
4512                continue;
4513            }
4514            while (it.hasNext()) {
4515                final String action = it.next();
4516                if (resultsAction != null && resultsAction.equals(action)) {
4517                    // If this action was explicitly requested, then don't
4518                    // remove things that have it.
4519                    continue;
4520                }
4521                for (int j=i+1; j<N; j++) {
4522                    final ResolveInfo rij = results.get(j);
4523                    if (rij.filter != null && rij.filter.hasAction(action)) {
4524                        results.remove(j);
4525                        if (DEBUG_INTENT_MATCHING) Log.v(
4526                            TAG, "Removing duplicate item from " + j
4527                            + " due to action " + action + " at " + i);
4528                        j--;
4529                        N--;
4530                    }
4531                }
4532            }
4533
4534            // If the caller didn't request filter information, drop it now
4535            // so we don't have to marshall/unmarshall it.
4536            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4537                rii.filter = null;
4538            }
4539        }
4540
4541        // Filter out the caller activity if so requested.
4542        if (caller != null) {
4543            N = results.size();
4544            for (int i=0; i<N; i++) {
4545                ActivityInfo ainfo = results.get(i).activityInfo;
4546                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4547                        && caller.getClassName().equals(ainfo.name)) {
4548                    results.remove(i);
4549                    break;
4550                }
4551            }
4552        }
4553
4554        // If the caller didn't request filter information,
4555        // drop them now so we don't have to
4556        // marshall/unmarshall it.
4557        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4558            N = results.size();
4559            for (int i=0; i<N; i++) {
4560                results.get(i).filter = null;
4561            }
4562        }
4563
4564        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4565        return results;
4566    }
4567
4568    @Override
4569    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4570            int userId) {
4571        if (!sUserManager.exists(userId)) return Collections.emptyList();
4572        ComponentName comp = intent.getComponent();
4573        if (comp == null) {
4574            if (intent.getSelector() != null) {
4575                intent = intent.getSelector();
4576                comp = intent.getComponent();
4577            }
4578        }
4579        if (comp != null) {
4580            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4581            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4582            if (ai != null) {
4583                ResolveInfo ri = new ResolveInfo();
4584                ri.activityInfo = ai;
4585                list.add(ri);
4586            }
4587            return list;
4588        }
4589
4590        // reader
4591        synchronized (mPackages) {
4592            String pkgName = intent.getPackage();
4593            if (pkgName == null) {
4594                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4595            }
4596            final PackageParser.Package pkg = mPackages.get(pkgName);
4597            if (pkg != null) {
4598                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4599                        userId);
4600            }
4601            return null;
4602        }
4603    }
4604
4605    @Override
4606    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4607        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4608        if (!sUserManager.exists(userId)) return null;
4609        if (query != null) {
4610            if (query.size() >= 1) {
4611                // If there is more than one service with the same priority,
4612                // just arbitrarily pick the first one.
4613                return query.get(0);
4614            }
4615        }
4616        return null;
4617    }
4618
4619    @Override
4620    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4621            int userId) {
4622        if (!sUserManager.exists(userId)) return Collections.emptyList();
4623        ComponentName comp = intent.getComponent();
4624        if (comp == null) {
4625            if (intent.getSelector() != null) {
4626                intent = intent.getSelector();
4627                comp = intent.getComponent();
4628            }
4629        }
4630        if (comp != null) {
4631            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4632            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4633            if (si != null) {
4634                final ResolveInfo ri = new ResolveInfo();
4635                ri.serviceInfo = si;
4636                list.add(ri);
4637            }
4638            return list;
4639        }
4640
4641        // reader
4642        synchronized (mPackages) {
4643            String pkgName = intent.getPackage();
4644            if (pkgName == null) {
4645                return mServices.queryIntent(intent, resolvedType, flags, userId);
4646            }
4647            final PackageParser.Package pkg = mPackages.get(pkgName);
4648            if (pkg != null) {
4649                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4650                        userId);
4651            }
4652            return null;
4653        }
4654    }
4655
4656    @Override
4657    public List<ResolveInfo> queryIntentContentProviders(
4658            Intent intent, String resolvedType, int flags, int userId) {
4659        if (!sUserManager.exists(userId)) return Collections.emptyList();
4660        ComponentName comp = intent.getComponent();
4661        if (comp == null) {
4662            if (intent.getSelector() != null) {
4663                intent = intent.getSelector();
4664                comp = intent.getComponent();
4665            }
4666        }
4667        if (comp != null) {
4668            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4669            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4670            if (pi != null) {
4671                final ResolveInfo ri = new ResolveInfo();
4672                ri.providerInfo = pi;
4673                list.add(ri);
4674            }
4675            return list;
4676        }
4677
4678        // reader
4679        synchronized (mPackages) {
4680            String pkgName = intent.getPackage();
4681            if (pkgName == null) {
4682                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4683            }
4684            final PackageParser.Package pkg = mPackages.get(pkgName);
4685            if (pkg != null) {
4686                return mProviders.queryIntentForPackage(
4687                        intent, resolvedType, flags, pkg.providers, userId);
4688            }
4689            return null;
4690        }
4691    }
4692
4693    @Override
4694    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4695        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4696
4697        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4698
4699        // writer
4700        synchronized (mPackages) {
4701            ArrayList<PackageInfo> list;
4702            if (listUninstalled) {
4703                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4704                for (PackageSetting ps : mSettings.mPackages.values()) {
4705                    PackageInfo pi;
4706                    if (ps.pkg != null) {
4707                        pi = generatePackageInfo(ps.pkg, flags, userId);
4708                    } else {
4709                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4710                    }
4711                    if (pi != null) {
4712                        list.add(pi);
4713                    }
4714                }
4715            } else {
4716                list = new ArrayList<PackageInfo>(mPackages.size());
4717                for (PackageParser.Package p : mPackages.values()) {
4718                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4719                    if (pi != null) {
4720                        list.add(pi);
4721                    }
4722                }
4723            }
4724
4725            return new ParceledListSlice<PackageInfo>(list);
4726        }
4727    }
4728
4729    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4730            String[] permissions, boolean[] tmp, int flags, int userId) {
4731        int numMatch = 0;
4732        final PermissionsState permissionsState = ps.getPermissionsState();
4733        for (int i=0; i<permissions.length; i++) {
4734            final String permission = permissions[i];
4735            if (permissionsState.hasPermission(permission, userId)) {
4736                tmp[i] = true;
4737                numMatch++;
4738            } else {
4739                tmp[i] = false;
4740            }
4741        }
4742        if (numMatch == 0) {
4743            return;
4744        }
4745        PackageInfo pi;
4746        if (ps.pkg != null) {
4747            pi = generatePackageInfo(ps.pkg, flags, userId);
4748        } else {
4749            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4750        }
4751        // The above might return null in cases of uninstalled apps or install-state
4752        // skew across users/profiles.
4753        if (pi != null) {
4754            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4755                if (numMatch == permissions.length) {
4756                    pi.requestedPermissions = permissions;
4757                } else {
4758                    pi.requestedPermissions = new String[numMatch];
4759                    numMatch = 0;
4760                    for (int i=0; i<permissions.length; i++) {
4761                        if (tmp[i]) {
4762                            pi.requestedPermissions[numMatch] = permissions[i];
4763                            numMatch++;
4764                        }
4765                    }
4766                }
4767            }
4768            list.add(pi);
4769        }
4770    }
4771
4772    @Override
4773    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4774            String[] permissions, int flags, int userId) {
4775        if (!sUserManager.exists(userId)) return null;
4776        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4777
4778        // writer
4779        synchronized (mPackages) {
4780            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4781            boolean[] tmpBools = new boolean[permissions.length];
4782            if (listUninstalled) {
4783                for (PackageSetting ps : mSettings.mPackages.values()) {
4784                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4785                }
4786            } else {
4787                for (PackageParser.Package pkg : mPackages.values()) {
4788                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4789                    if (ps != null) {
4790                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4791                                userId);
4792                    }
4793                }
4794            }
4795
4796            return new ParceledListSlice<PackageInfo>(list);
4797        }
4798    }
4799
4800    @Override
4801    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4802        if (!sUserManager.exists(userId)) return null;
4803        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4804
4805        // writer
4806        synchronized (mPackages) {
4807            ArrayList<ApplicationInfo> list;
4808            if (listUninstalled) {
4809                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4810                for (PackageSetting ps : mSettings.mPackages.values()) {
4811                    ApplicationInfo ai;
4812                    if (ps.pkg != null) {
4813                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4814                                ps.readUserState(userId), userId);
4815                    } else {
4816                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4817                    }
4818                    if (ai != null) {
4819                        list.add(ai);
4820                    }
4821                }
4822            } else {
4823                list = new ArrayList<ApplicationInfo>(mPackages.size());
4824                for (PackageParser.Package p : mPackages.values()) {
4825                    if (p.mExtras != null) {
4826                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4827                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4828                        if (ai != null) {
4829                            list.add(ai);
4830                        }
4831                    }
4832                }
4833            }
4834
4835            return new ParceledListSlice<ApplicationInfo>(list);
4836        }
4837    }
4838
4839    public List<ApplicationInfo> getPersistentApplications(int flags) {
4840        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4841
4842        // reader
4843        synchronized (mPackages) {
4844            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4845            final int userId = UserHandle.getCallingUserId();
4846            while (i.hasNext()) {
4847                final PackageParser.Package p = i.next();
4848                if (p.applicationInfo != null
4849                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4850                        && (!mSafeMode || isSystemApp(p))) {
4851                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4852                    if (ps != null) {
4853                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4854                                ps.readUserState(userId), userId);
4855                        if (ai != null) {
4856                            finalList.add(ai);
4857                        }
4858                    }
4859                }
4860            }
4861        }
4862
4863        return finalList;
4864    }
4865
4866    @Override
4867    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4868        if (!sUserManager.exists(userId)) return null;
4869        // reader
4870        synchronized (mPackages) {
4871            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4872            PackageSetting ps = provider != null
4873                    ? mSettings.mPackages.get(provider.owner.packageName)
4874                    : null;
4875            return ps != null
4876                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4877                    && (!mSafeMode || (provider.info.applicationInfo.flags
4878                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4879                    ? PackageParser.generateProviderInfo(provider, flags,
4880                            ps.readUserState(userId), userId)
4881                    : null;
4882        }
4883    }
4884
4885    /**
4886     * @deprecated
4887     */
4888    @Deprecated
4889    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4890        // reader
4891        synchronized (mPackages) {
4892            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4893                    .entrySet().iterator();
4894            final int userId = UserHandle.getCallingUserId();
4895            while (i.hasNext()) {
4896                Map.Entry<String, PackageParser.Provider> entry = i.next();
4897                PackageParser.Provider p = entry.getValue();
4898                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4899
4900                if (ps != null && p.syncable
4901                        && (!mSafeMode || (p.info.applicationInfo.flags
4902                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4903                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4904                            ps.readUserState(userId), userId);
4905                    if (info != null) {
4906                        outNames.add(entry.getKey());
4907                        outInfo.add(info);
4908                    }
4909                }
4910            }
4911        }
4912    }
4913
4914    @Override
4915    public List<ProviderInfo> queryContentProviders(String processName,
4916            int uid, int flags) {
4917        ArrayList<ProviderInfo> finalList = null;
4918        // reader
4919        synchronized (mPackages) {
4920            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4921            final int userId = processName != null ?
4922                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4923            while (i.hasNext()) {
4924                final PackageParser.Provider p = i.next();
4925                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4926                if (ps != null && p.info.authority != null
4927                        && (processName == null
4928                                || (p.info.processName.equals(processName)
4929                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4930                        && mSettings.isEnabledLPr(p.info, flags, userId)
4931                        && (!mSafeMode
4932                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4933                    if (finalList == null) {
4934                        finalList = new ArrayList<ProviderInfo>(3);
4935                    }
4936                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4937                            ps.readUserState(userId), userId);
4938                    if (info != null) {
4939                        finalList.add(info);
4940                    }
4941                }
4942            }
4943        }
4944
4945        if (finalList != null) {
4946            Collections.sort(finalList, mProviderInitOrderSorter);
4947        }
4948
4949        return finalList;
4950    }
4951
4952    @Override
4953    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4954            int flags) {
4955        // reader
4956        synchronized (mPackages) {
4957            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4958            return PackageParser.generateInstrumentationInfo(i, flags);
4959        }
4960    }
4961
4962    @Override
4963    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4964            int flags) {
4965        ArrayList<InstrumentationInfo> finalList =
4966            new ArrayList<InstrumentationInfo>();
4967
4968        // reader
4969        synchronized (mPackages) {
4970            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4971            while (i.hasNext()) {
4972                final PackageParser.Instrumentation p = i.next();
4973                if (targetPackage == null
4974                        || targetPackage.equals(p.info.targetPackage)) {
4975                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4976                            flags);
4977                    if (ii != null) {
4978                        finalList.add(ii);
4979                    }
4980                }
4981            }
4982        }
4983
4984        return finalList;
4985    }
4986
4987    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4988        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4989        if (overlays == null) {
4990            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4991            return;
4992        }
4993        for (PackageParser.Package opkg : overlays.values()) {
4994            // Not much to do if idmap fails: we already logged the error
4995            // and we certainly don't want to abort installation of pkg simply
4996            // because an overlay didn't fit properly. For these reasons,
4997            // ignore the return value of createIdmapForPackagePairLI.
4998            createIdmapForPackagePairLI(pkg, opkg);
4999        }
5000    }
5001
5002    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5003            PackageParser.Package opkg) {
5004        if (!opkg.mTrustedOverlay) {
5005            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5006                    opkg.baseCodePath + ": overlay not trusted");
5007            return false;
5008        }
5009        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5010        if (overlaySet == null) {
5011            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5012                    opkg.baseCodePath + " but target package has no known overlays");
5013            return false;
5014        }
5015        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5016        // TODO: generate idmap for split APKs
5017        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5018            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5019                    + opkg.baseCodePath);
5020            return false;
5021        }
5022        PackageParser.Package[] overlayArray =
5023            overlaySet.values().toArray(new PackageParser.Package[0]);
5024        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5025            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5026                return p1.mOverlayPriority - p2.mOverlayPriority;
5027            }
5028        };
5029        Arrays.sort(overlayArray, cmp);
5030
5031        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5032        int i = 0;
5033        for (PackageParser.Package p : overlayArray) {
5034            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5035        }
5036        return true;
5037    }
5038
5039    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5040        final File[] files = dir.listFiles();
5041        if (ArrayUtils.isEmpty(files)) {
5042            Log.d(TAG, "No files in app dir " + dir);
5043            return;
5044        }
5045
5046        if (DEBUG_PACKAGE_SCANNING) {
5047            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5048                    + " flags=0x" + Integer.toHexString(parseFlags));
5049        }
5050
5051        for (File file : files) {
5052            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5053                    && !PackageInstallerService.isStageName(file.getName());
5054            if (!isPackage) {
5055                // Ignore entries which are not packages
5056                continue;
5057            }
5058            try {
5059                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5060                        scanFlags, currentTime, null);
5061            } catch (PackageManagerException e) {
5062                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5063
5064                // Delete invalid userdata apps
5065                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5066                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5067                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5068                    if (file.isDirectory()) {
5069                        mInstaller.rmPackageDir(file.getAbsolutePath());
5070                    } else {
5071                        file.delete();
5072                    }
5073                }
5074            }
5075        }
5076    }
5077
5078    private static File getSettingsProblemFile() {
5079        File dataDir = Environment.getDataDirectory();
5080        File systemDir = new File(dataDir, "system");
5081        File fname = new File(systemDir, "uiderrors.txt");
5082        return fname;
5083    }
5084
5085    static void reportSettingsProblem(int priority, String msg) {
5086        logCriticalInfo(priority, msg);
5087    }
5088
5089    static void logCriticalInfo(int priority, String msg) {
5090        Slog.println(priority, TAG, msg);
5091        EventLogTags.writePmCriticalInfo(msg);
5092        try {
5093            File fname = getSettingsProblemFile();
5094            FileOutputStream out = new FileOutputStream(fname, true);
5095            PrintWriter pw = new FastPrintWriter(out);
5096            SimpleDateFormat formatter = new SimpleDateFormat();
5097            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5098            pw.println(dateString + ": " + msg);
5099            pw.close();
5100            FileUtils.setPermissions(
5101                    fname.toString(),
5102                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5103                    -1, -1);
5104        } catch (java.io.IOException e) {
5105        }
5106    }
5107
5108    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5109            PackageParser.Package pkg, File srcFile, int parseFlags)
5110            throws PackageManagerException {
5111        if (ps != null
5112                && ps.codePath.equals(srcFile)
5113                && ps.timeStamp == srcFile.lastModified()
5114                && !isCompatSignatureUpdateNeeded(pkg)
5115                && !isRecoverSignatureUpdateNeeded(pkg)) {
5116            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5117            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5118            ArraySet<PublicKey> signingKs;
5119            synchronized (mPackages) {
5120                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5121            }
5122            if (ps.signatures.mSignatures != null
5123                    && ps.signatures.mSignatures.length != 0
5124                    && signingKs != null) {
5125                // Optimization: reuse the existing cached certificates
5126                // if the package appears to be unchanged.
5127                pkg.mSignatures = ps.signatures.mSignatures;
5128                pkg.mSigningKeys = signingKs;
5129                return;
5130            }
5131
5132            Slog.w(TAG, "PackageSetting for " + ps.name
5133                    + " is missing signatures.  Collecting certs again to recover them.");
5134        } else {
5135            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5136        }
5137
5138        try {
5139            pp.collectCertificates(pkg, parseFlags);
5140            pp.collectManifestDigest(pkg);
5141        } catch (PackageParserException e) {
5142            throw PackageManagerException.from(e);
5143        }
5144    }
5145
5146    /*
5147     *  Scan a package and return the newly parsed package.
5148     *  Returns null in case of errors and the error code is stored in mLastScanError
5149     */
5150    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5151            long currentTime, UserHandle user) throws PackageManagerException {
5152        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5153        parseFlags |= mDefParseFlags;
5154        PackageParser pp = new PackageParser();
5155        pp.setSeparateProcesses(mSeparateProcesses);
5156        pp.setOnlyCoreApps(mOnlyCore);
5157        pp.setDisplayMetrics(mMetrics);
5158
5159        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5160            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5161        }
5162
5163        final PackageParser.Package pkg;
5164        try {
5165            pkg = pp.parsePackage(scanFile, parseFlags);
5166        } catch (PackageParserException e) {
5167            throw PackageManagerException.from(e);
5168        }
5169
5170        PackageSetting ps = null;
5171        PackageSetting updatedPkg;
5172        // reader
5173        synchronized (mPackages) {
5174            // Look to see if we already know about this package.
5175            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5176            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5177                // This package has been renamed to its original name.  Let's
5178                // use that.
5179                ps = mSettings.peekPackageLPr(oldName);
5180            }
5181            // If there was no original package, see one for the real package name.
5182            if (ps == null) {
5183                ps = mSettings.peekPackageLPr(pkg.packageName);
5184            }
5185            // Check to see if this package could be hiding/updating a system
5186            // package.  Must look for it either under the original or real
5187            // package name depending on our state.
5188            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5189            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5190        }
5191        boolean updatedPkgBetter = false;
5192        // First check if this is a system package that may involve an update
5193        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5194            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5195            // it needs to drop FLAG_PRIVILEGED.
5196            if (locationIsPrivileged(scanFile)) {
5197                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5198            } else {
5199                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5200            }
5201
5202            if (ps != null && !ps.codePath.equals(scanFile)) {
5203                // The path has changed from what was last scanned...  check the
5204                // version of the new path against what we have stored to determine
5205                // what to do.
5206                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5207                if (pkg.mVersionCode <= ps.versionCode) {
5208                    // The system package has been updated and the code path does not match
5209                    // Ignore entry. Skip it.
5210                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5211                            + " ignored: updated version " + ps.versionCode
5212                            + " better than this " + pkg.mVersionCode);
5213                    if (!updatedPkg.codePath.equals(scanFile)) {
5214                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5215                                + ps.name + " changing from " + updatedPkg.codePathString
5216                                + " to " + scanFile);
5217                        updatedPkg.codePath = scanFile;
5218                        updatedPkg.codePathString = scanFile.toString();
5219                        updatedPkg.resourcePath = scanFile;
5220                        updatedPkg.resourcePathString = scanFile.toString();
5221                    }
5222                    updatedPkg.pkg = pkg;
5223                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5224                } else {
5225                    // The current app on the system partition is better than
5226                    // what we have updated to on the data partition; switch
5227                    // back to the system partition version.
5228                    // At this point, its safely assumed that package installation for
5229                    // apps in system partition will go through. If not there won't be a working
5230                    // version of the app
5231                    // writer
5232                    synchronized (mPackages) {
5233                        // Just remove the loaded entries from package lists.
5234                        mPackages.remove(ps.name);
5235                    }
5236
5237                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5238                            + " reverting from " + ps.codePathString
5239                            + ": new version " + pkg.mVersionCode
5240                            + " better than installed " + ps.versionCode);
5241
5242                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5243                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5244                    synchronized (mInstallLock) {
5245                        args.cleanUpResourcesLI();
5246                    }
5247                    synchronized (mPackages) {
5248                        mSettings.enableSystemPackageLPw(ps.name);
5249                    }
5250                    updatedPkgBetter = true;
5251                }
5252            }
5253        }
5254
5255        if (updatedPkg != null) {
5256            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5257            // initially
5258            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5259
5260            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5261            // flag set initially
5262            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5263                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5264            }
5265        }
5266
5267        // Verify certificates against what was last scanned
5268        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5269
5270        /*
5271         * A new system app appeared, but we already had a non-system one of the
5272         * same name installed earlier.
5273         */
5274        boolean shouldHideSystemApp = false;
5275        if (updatedPkg == null && ps != null
5276                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5277            /*
5278             * Check to make sure the signatures match first. If they don't,
5279             * wipe the installed application and its data.
5280             */
5281            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5282                    != PackageManager.SIGNATURE_MATCH) {
5283                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5284                        + " signatures don't match existing userdata copy; removing");
5285                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5286                ps = null;
5287            } else {
5288                /*
5289                 * If the newly-added system app is an older version than the
5290                 * already installed version, hide it. It will be scanned later
5291                 * and re-added like an update.
5292                 */
5293                if (pkg.mVersionCode <= ps.versionCode) {
5294                    shouldHideSystemApp = true;
5295                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5296                            + " but new version " + pkg.mVersionCode + " better than installed "
5297                            + ps.versionCode + "; hiding system");
5298                } else {
5299                    /*
5300                     * The newly found system app is a newer version that the
5301                     * one previously installed. Simply remove the
5302                     * already-installed application and replace it with our own
5303                     * while keeping the application data.
5304                     */
5305                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5306                            + " reverting from " + ps.codePathString + ": new version "
5307                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5308                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5309                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5310                    synchronized (mInstallLock) {
5311                        args.cleanUpResourcesLI();
5312                    }
5313                }
5314            }
5315        }
5316
5317        // The apk is forward locked (not public) if its code and resources
5318        // are kept in different files. (except for app in either system or
5319        // vendor path).
5320        // TODO grab this value from PackageSettings
5321        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5322            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5323                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5324            }
5325        }
5326
5327        // TODO: extend to support forward-locked splits
5328        String resourcePath = null;
5329        String baseResourcePath = null;
5330        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5331            if (ps != null && ps.resourcePathString != null) {
5332                resourcePath = ps.resourcePathString;
5333                baseResourcePath = ps.resourcePathString;
5334            } else {
5335                // Should not happen at all. Just log an error.
5336                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5337            }
5338        } else {
5339            resourcePath = pkg.codePath;
5340            baseResourcePath = pkg.baseCodePath;
5341        }
5342
5343        // Set application objects path explicitly.
5344        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5345        pkg.applicationInfo.setCodePath(pkg.codePath);
5346        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5347        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5348        pkg.applicationInfo.setResourcePath(resourcePath);
5349        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5350        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5351
5352        // Note that we invoke the following method only if we are about to unpack an application
5353        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5354                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5355
5356        /*
5357         * If the system app should be overridden by a previously installed
5358         * data, hide the system app now and let the /data/app scan pick it up
5359         * again.
5360         */
5361        if (shouldHideSystemApp) {
5362            synchronized (mPackages) {
5363                /*
5364                 * We have to grant systems permissions before we hide, because
5365                 * grantPermissions will assume the package update is trying to
5366                 * expand its permissions.
5367                 */
5368                grantPermissionsLPw(pkg, true, pkg.packageName);
5369                mSettings.disableSystemPackageLPw(pkg.packageName);
5370            }
5371        }
5372
5373        return scannedPkg;
5374    }
5375
5376    private static String fixProcessName(String defProcessName,
5377            String processName, int uid) {
5378        if (processName == null) {
5379            return defProcessName;
5380        }
5381        return processName;
5382    }
5383
5384    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5385            throws PackageManagerException {
5386        if (pkgSetting.signatures.mSignatures != null) {
5387            // Already existing package. Make sure signatures match
5388            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5389                    == PackageManager.SIGNATURE_MATCH;
5390            if (!match) {
5391                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5392                        == PackageManager.SIGNATURE_MATCH;
5393            }
5394            if (!match) {
5395                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5396                        == PackageManager.SIGNATURE_MATCH;
5397            }
5398            if (!match) {
5399                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5400                        + pkg.packageName + " signatures do not match the "
5401                        + "previously installed version; ignoring!");
5402            }
5403        }
5404
5405        // Check for shared user signatures
5406        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5407            // Already existing package. Make sure signatures match
5408            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5409                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5410            if (!match) {
5411                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5412                        == PackageManager.SIGNATURE_MATCH;
5413            }
5414            if (!match) {
5415                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5416                        == PackageManager.SIGNATURE_MATCH;
5417            }
5418            if (!match) {
5419                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5420                        "Package " + pkg.packageName
5421                        + " has no signatures that match those in shared user "
5422                        + pkgSetting.sharedUser.name + "; ignoring!");
5423            }
5424        }
5425    }
5426
5427    /**
5428     * Enforces that only the system UID or root's UID can call a method exposed
5429     * via Binder.
5430     *
5431     * @param message used as message if SecurityException is thrown
5432     * @throws SecurityException if the caller is not system or root
5433     */
5434    private static final void enforceSystemOrRoot(String message) {
5435        final int uid = Binder.getCallingUid();
5436        if (uid != Process.SYSTEM_UID && uid != 0) {
5437            throw new SecurityException(message);
5438        }
5439    }
5440
5441    @Override
5442    public void performBootDexOpt() {
5443        enforceSystemOrRoot("Only the system can request dexopt be performed");
5444
5445        // Before everything else, see whether we need to fstrim.
5446        try {
5447            IMountService ms = PackageHelper.getMountService();
5448            if (ms != null) {
5449                final boolean isUpgrade = isUpgrade();
5450                boolean doTrim = isUpgrade;
5451                if (doTrim) {
5452                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5453                } else {
5454                    final long interval = android.provider.Settings.Global.getLong(
5455                            mContext.getContentResolver(),
5456                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5457                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5458                    if (interval > 0) {
5459                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5460                        if (timeSinceLast > interval) {
5461                            doTrim = true;
5462                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5463                                    + "; running immediately");
5464                        }
5465                    }
5466                }
5467                if (doTrim) {
5468                    if (!isFirstBoot()) {
5469                        try {
5470                            ActivityManagerNative.getDefault().showBootMessage(
5471                                    mContext.getResources().getString(
5472                                            R.string.android_upgrading_fstrim), true);
5473                        } catch (RemoteException e) {
5474                        }
5475                    }
5476                    ms.runMaintenance();
5477                }
5478            } else {
5479                Slog.e(TAG, "Mount service unavailable!");
5480            }
5481        } catch (RemoteException e) {
5482            // Can't happen; MountService is local
5483        }
5484
5485        final ArraySet<PackageParser.Package> pkgs;
5486        synchronized (mPackages) {
5487            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5488        }
5489
5490        if (pkgs != null) {
5491            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5492            // in case the device runs out of space.
5493            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5494            // Give priority to core apps.
5495            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5496                PackageParser.Package pkg = it.next();
5497                if (pkg.coreApp) {
5498                    if (DEBUG_DEXOPT) {
5499                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5500                    }
5501                    sortedPkgs.add(pkg);
5502                    it.remove();
5503                }
5504            }
5505            // Give priority to system apps that listen for pre boot complete.
5506            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5507            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5508            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5509                PackageParser.Package pkg = it.next();
5510                if (pkgNames.contains(pkg.packageName)) {
5511                    if (DEBUG_DEXOPT) {
5512                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5513                    }
5514                    sortedPkgs.add(pkg);
5515                    it.remove();
5516                }
5517            }
5518            // Give priority to system apps.
5519            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5520                PackageParser.Package pkg = it.next();
5521                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5522                    if (DEBUG_DEXOPT) {
5523                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5524                    }
5525                    sortedPkgs.add(pkg);
5526                    it.remove();
5527                }
5528            }
5529            // Give priority to updated system apps.
5530            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5531                PackageParser.Package pkg = it.next();
5532                if (pkg.isUpdatedSystemApp()) {
5533                    if (DEBUG_DEXOPT) {
5534                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5535                    }
5536                    sortedPkgs.add(pkg);
5537                    it.remove();
5538                }
5539            }
5540            // Give priority to apps that listen for boot complete.
5541            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5542            pkgNames = getPackageNamesForIntent(intent);
5543            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5544                PackageParser.Package pkg = it.next();
5545                if (pkgNames.contains(pkg.packageName)) {
5546                    if (DEBUG_DEXOPT) {
5547                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5548                    }
5549                    sortedPkgs.add(pkg);
5550                    it.remove();
5551                }
5552            }
5553            // Filter out packages that aren't recently used.
5554            filterRecentlyUsedApps(pkgs);
5555            // Add all remaining apps.
5556            for (PackageParser.Package pkg : pkgs) {
5557                if (DEBUG_DEXOPT) {
5558                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5559                }
5560                sortedPkgs.add(pkg);
5561            }
5562
5563            // If we want to be lazy, filter everything that wasn't recently used.
5564            if (mLazyDexOpt) {
5565                filterRecentlyUsedApps(sortedPkgs);
5566            }
5567
5568            int i = 0;
5569            int total = sortedPkgs.size();
5570            File dataDir = Environment.getDataDirectory();
5571            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5572            if (lowThreshold == 0) {
5573                throw new IllegalStateException("Invalid low memory threshold");
5574            }
5575            for (PackageParser.Package pkg : sortedPkgs) {
5576                long usableSpace = dataDir.getUsableSpace();
5577                if (usableSpace < lowThreshold) {
5578                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5579                    break;
5580                }
5581                performBootDexOpt(pkg, ++i, total);
5582            }
5583        }
5584    }
5585
5586    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5587        // Filter out packages that aren't recently used.
5588        //
5589        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5590        // should do a full dexopt.
5591        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5592            int total = pkgs.size();
5593            int skipped = 0;
5594            long now = System.currentTimeMillis();
5595            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5596                PackageParser.Package pkg = i.next();
5597                long then = pkg.mLastPackageUsageTimeInMills;
5598                if (then + mDexOptLRUThresholdInMills < now) {
5599                    if (DEBUG_DEXOPT) {
5600                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5601                              ((then == 0) ? "never" : new Date(then)));
5602                    }
5603                    i.remove();
5604                    skipped++;
5605                }
5606            }
5607            if (DEBUG_DEXOPT) {
5608                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5609            }
5610        }
5611    }
5612
5613    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5614        List<ResolveInfo> ris = null;
5615        try {
5616            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5617                    intent, null, 0, UserHandle.USER_OWNER);
5618        } catch (RemoteException e) {
5619        }
5620        ArraySet<String> pkgNames = new ArraySet<String>();
5621        if (ris != null) {
5622            for (ResolveInfo ri : ris) {
5623                pkgNames.add(ri.activityInfo.packageName);
5624            }
5625        }
5626        return pkgNames;
5627    }
5628
5629    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5630        if (DEBUG_DEXOPT) {
5631            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5632        }
5633        if (!isFirstBoot()) {
5634            try {
5635                ActivityManagerNative.getDefault().showBootMessage(
5636                        mContext.getResources().getString(R.string.android_upgrading_apk,
5637                                curr, total), true);
5638            } catch (RemoteException e) {
5639            }
5640        }
5641        PackageParser.Package p = pkg;
5642        synchronized (mInstallLock) {
5643            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5644                    false /* force dex */, false /* defer */, true /* include dependencies */);
5645        }
5646    }
5647
5648    @Override
5649    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5650        return performDexOpt(packageName, instructionSet, false);
5651    }
5652
5653    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5654        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5655        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5656        if (!dexopt && !updateUsage) {
5657            // We aren't going to dexopt or update usage, so bail early.
5658            return false;
5659        }
5660        PackageParser.Package p;
5661        final String targetInstructionSet;
5662        synchronized (mPackages) {
5663            p = mPackages.get(packageName);
5664            if (p == null) {
5665                return false;
5666            }
5667            if (updateUsage) {
5668                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5669            }
5670            mPackageUsage.write(false);
5671            if (!dexopt) {
5672                // We aren't going to dexopt, so bail early.
5673                return false;
5674            }
5675
5676            targetInstructionSet = instructionSet != null ? instructionSet :
5677                    getPrimaryInstructionSet(p.applicationInfo);
5678            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5679                return false;
5680            }
5681        }
5682
5683        synchronized (mInstallLock) {
5684            final String[] instructionSets = new String[] { targetInstructionSet };
5685            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5686                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5687            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5688        }
5689    }
5690
5691    public ArraySet<String> getPackagesThatNeedDexOpt() {
5692        ArraySet<String> pkgs = null;
5693        synchronized (mPackages) {
5694            for (PackageParser.Package p : mPackages.values()) {
5695                if (DEBUG_DEXOPT) {
5696                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5697                }
5698                if (!p.mDexOptPerformed.isEmpty()) {
5699                    continue;
5700                }
5701                if (pkgs == null) {
5702                    pkgs = new ArraySet<String>();
5703                }
5704                pkgs.add(p.packageName);
5705            }
5706        }
5707        return pkgs;
5708    }
5709
5710    public void shutdown() {
5711        mPackageUsage.write(true);
5712    }
5713
5714    @Override
5715    public void forceDexOpt(String packageName) {
5716        enforceSystemOrRoot("forceDexOpt");
5717
5718        PackageParser.Package pkg;
5719        synchronized (mPackages) {
5720            pkg = mPackages.get(packageName);
5721            if (pkg == null) {
5722                throw new IllegalArgumentException("Missing package: " + packageName);
5723            }
5724        }
5725
5726        synchronized (mInstallLock) {
5727            final String[] instructionSets = new String[] {
5728                    getPrimaryInstructionSet(pkg.applicationInfo) };
5729            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5730                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5731            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5732                throw new IllegalStateException("Failed to dexopt: " + res);
5733            }
5734        }
5735    }
5736
5737    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5738        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5739            Slog.w(TAG, "Unable to update from " + oldPkg.name
5740                    + " to " + newPkg.packageName
5741                    + ": old package not in system partition");
5742            return false;
5743        } else if (mPackages.get(oldPkg.name) != null) {
5744            Slog.w(TAG, "Unable to update from " + oldPkg.name
5745                    + " to " + newPkg.packageName
5746                    + ": old package still exists");
5747            return false;
5748        }
5749        return true;
5750    }
5751
5752    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5753        int[] users = sUserManager.getUserIds();
5754        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5755        if (res < 0) {
5756            return res;
5757        }
5758        for (int user : users) {
5759            if (user != 0) {
5760                res = mInstaller.createUserData(volumeUuid, packageName,
5761                        UserHandle.getUid(user, uid), user, seinfo);
5762                if (res < 0) {
5763                    return res;
5764                }
5765            }
5766        }
5767        return res;
5768    }
5769
5770    private int removeDataDirsLI(String volumeUuid, String packageName) {
5771        int[] users = sUserManager.getUserIds();
5772        int res = 0;
5773        for (int user : users) {
5774            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5775            if (resInner < 0) {
5776                res = resInner;
5777            }
5778        }
5779
5780        return res;
5781    }
5782
5783    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5784        int[] users = sUserManager.getUserIds();
5785        int res = 0;
5786        for (int user : users) {
5787            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5788            if (resInner < 0) {
5789                res = resInner;
5790            }
5791        }
5792        return res;
5793    }
5794
5795    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5796            PackageParser.Package changingLib) {
5797        if (file.path != null) {
5798            usesLibraryFiles.add(file.path);
5799            return;
5800        }
5801        PackageParser.Package p = mPackages.get(file.apk);
5802        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5803            // If we are doing this while in the middle of updating a library apk,
5804            // then we need to make sure to use that new apk for determining the
5805            // dependencies here.  (We haven't yet finished committing the new apk
5806            // to the package manager state.)
5807            if (p == null || p.packageName.equals(changingLib.packageName)) {
5808                p = changingLib;
5809            }
5810        }
5811        if (p != null) {
5812            usesLibraryFiles.addAll(p.getAllCodePaths());
5813        }
5814    }
5815
5816    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5817            PackageParser.Package changingLib) throws PackageManagerException {
5818        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5819            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5820            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5821            for (int i=0; i<N; i++) {
5822                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5823                if (file == null) {
5824                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5825                            "Package " + pkg.packageName + " requires unavailable shared library "
5826                            + pkg.usesLibraries.get(i) + "; failing!");
5827                }
5828                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5829            }
5830            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5831            for (int i=0; i<N; i++) {
5832                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5833                if (file == null) {
5834                    Slog.w(TAG, "Package " + pkg.packageName
5835                            + " desires unavailable shared library "
5836                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5837                } else {
5838                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5839                }
5840            }
5841            N = usesLibraryFiles.size();
5842            if (N > 0) {
5843                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5844            } else {
5845                pkg.usesLibraryFiles = null;
5846            }
5847        }
5848    }
5849
5850    private static boolean hasString(List<String> list, List<String> which) {
5851        if (list == null) {
5852            return false;
5853        }
5854        for (int i=list.size()-1; i>=0; i--) {
5855            for (int j=which.size()-1; j>=0; j--) {
5856                if (which.get(j).equals(list.get(i))) {
5857                    return true;
5858                }
5859            }
5860        }
5861        return false;
5862    }
5863
5864    private void updateAllSharedLibrariesLPw() {
5865        for (PackageParser.Package pkg : mPackages.values()) {
5866            try {
5867                updateSharedLibrariesLPw(pkg, null);
5868            } catch (PackageManagerException e) {
5869                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5870            }
5871        }
5872    }
5873
5874    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5875            PackageParser.Package changingPkg) {
5876        ArrayList<PackageParser.Package> res = null;
5877        for (PackageParser.Package pkg : mPackages.values()) {
5878            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5879                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5880                if (res == null) {
5881                    res = new ArrayList<PackageParser.Package>();
5882                }
5883                res.add(pkg);
5884                try {
5885                    updateSharedLibrariesLPw(pkg, changingPkg);
5886                } catch (PackageManagerException e) {
5887                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5888                }
5889            }
5890        }
5891        return res;
5892    }
5893
5894    /**
5895     * Derive the value of the {@code cpuAbiOverride} based on the provided
5896     * value and an optional stored value from the package settings.
5897     */
5898    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5899        String cpuAbiOverride = null;
5900
5901        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5902            cpuAbiOverride = null;
5903        } else if (abiOverride != null) {
5904            cpuAbiOverride = abiOverride;
5905        } else if (settings != null) {
5906            cpuAbiOverride = settings.cpuAbiOverrideString;
5907        }
5908
5909        return cpuAbiOverride;
5910    }
5911
5912    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5913            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5914        boolean success = false;
5915        try {
5916            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5917                    currentTime, user);
5918            success = true;
5919            return res;
5920        } finally {
5921            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5922                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
5923            }
5924        }
5925    }
5926
5927    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5928            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5929        final File scanFile = new File(pkg.codePath);
5930        if (pkg.applicationInfo.getCodePath() == null ||
5931                pkg.applicationInfo.getResourcePath() == null) {
5932            // Bail out. The resource and code paths haven't been set.
5933            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5934                    "Code and resource paths haven't been set correctly");
5935        }
5936
5937        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5938            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5939        } else {
5940            // Only allow system apps to be flagged as core apps.
5941            pkg.coreApp = false;
5942        }
5943
5944        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5945            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5946        }
5947
5948        if (mCustomResolverComponentName != null &&
5949                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5950            setUpCustomResolverActivity(pkg);
5951        }
5952
5953        if (pkg.packageName.equals("android")) {
5954            synchronized (mPackages) {
5955                if (mAndroidApplication != null) {
5956                    Slog.w(TAG, "*************************************************");
5957                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5958                    Slog.w(TAG, " file=" + scanFile);
5959                    Slog.w(TAG, "*************************************************");
5960                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5961                            "Core android package being redefined.  Skipping.");
5962                }
5963
5964                // Set up information for our fall-back user intent resolution activity.
5965                mPlatformPackage = pkg;
5966                pkg.mVersionCode = mSdkVersion;
5967                mAndroidApplication = pkg.applicationInfo;
5968
5969                if (!mResolverReplaced) {
5970                    mResolveActivity.applicationInfo = mAndroidApplication;
5971                    mResolveActivity.name = ResolverActivity.class.getName();
5972                    mResolveActivity.packageName = mAndroidApplication.packageName;
5973                    mResolveActivity.processName = "system:ui";
5974                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5975                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5976                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5977                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5978                    mResolveActivity.exported = true;
5979                    mResolveActivity.enabled = true;
5980                    mResolveInfo.activityInfo = mResolveActivity;
5981                    mResolveInfo.priority = 0;
5982                    mResolveInfo.preferredOrder = 0;
5983                    mResolveInfo.match = 0;
5984                    mResolveComponentName = new ComponentName(
5985                            mAndroidApplication.packageName, mResolveActivity.name);
5986                }
5987            }
5988        }
5989
5990        if (DEBUG_PACKAGE_SCANNING) {
5991            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5992                Log.d(TAG, "Scanning package " + pkg.packageName);
5993        }
5994
5995        if (mPackages.containsKey(pkg.packageName)
5996                || mSharedLibraries.containsKey(pkg.packageName)) {
5997            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5998                    "Application package " + pkg.packageName
5999                    + " already installed.  Skipping duplicate.");
6000        }
6001
6002        // If we're only installing presumed-existing packages, require that the
6003        // scanned APK is both already known and at the path previously established
6004        // for it.  Previously unknown packages we pick up normally, but if we have an
6005        // a priori expectation about this package's install presence, enforce it.
6006        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6007            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6008            if (known != null) {
6009                if (DEBUG_PACKAGE_SCANNING) {
6010                    Log.d(TAG, "Examining " + pkg.codePath
6011                            + " and requiring known paths " + known.codePathString
6012                            + " & " + known.resourcePathString);
6013                }
6014                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6015                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6016                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6017                            "Application package " + pkg.packageName
6018                            + " found at " + pkg.applicationInfo.getCodePath()
6019                            + " but expected at " + known.codePathString + "; ignoring.");
6020                }
6021            }
6022        }
6023
6024        // Initialize package source and resource directories
6025        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6026        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6027
6028        SharedUserSetting suid = null;
6029        PackageSetting pkgSetting = null;
6030
6031        if (!isSystemApp(pkg)) {
6032            // Only system apps can use these features.
6033            pkg.mOriginalPackages = null;
6034            pkg.mRealPackage = null;
6035            pkg.mAdoptPermissions = null;
6036        }
6037
6038        // writer
6039        synchronized (mPackages) {
6040            if (pkg.mSharedUserId != null) {
6041                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6042                if (suid == null) {
6043                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6044                            "Creating application package " + pkg.packageName
6045                            + " for shared user failed");
6046                }
6047                if (DEBUG_PACKAGE_SCANNING) {
6048                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6049                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6050                                + "): packages=" + suid.packages);
6051                }
6052            }
6053
6054            // Check if we are renaming from an original package name.
6055            PackageSetting origPackage = null;
6056            String realName = null;
6057            if (pkg.mOriginalPackages != null) {
6058                // This package may need to be renamed to a previously
6059                // installed name.  Let's check on that...
6060                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6061                if (pkg.mOriginalPackages.contains(renamed)) {
6062                    // This package had originally been installed as the
6063                    // original name, and we have already taken care of
6064                    // transitioning to the new one.  Just update the new
6065                    // one to continue using the old name.
6066                    realName = pkg.mRealPackage;
6067                    if (!pkg.packageName.equals(renamed)) {
6068                        // Callers into this function may have already taken
6069                        // care of renaming the package; only do it here if
6070                        // it is not already done.
6071                        pkg.setPackageName(renamed);
6072                    }
6073
6074                } else {
6075                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6076                        if ((origPackage = mSettings.peekPackageLPr(
6077                                pkg.mOriginalPackages.get(i))) != null) {
6078                            // We do have the package already installed under its
6079                            // original name...  should we use it?
6080                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6081                                // New package is not compatible with original.
6082                                origPackage = null;
6083                                continue;
6084                            } else if (origPackage.sharedUser != null) {
6085                                // Make sure uid is compatible between packages.
6086                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6087                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6088                                            + " to " + pkg.packageName + ": old uid "
6089                                            + origPackage.sharedUser.name
6090                                            + " differs from " + pkg.mSharedUserId);
6091                                    origPackage = null;
6092                                    continue;
6093                                }
6094                            } else {
6095                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6096                                        + pkg.packageName + " to old name " + origPackage.name);
6097                            }
6098                            break;
6099                        }
6100                    }
6101                }
6102            }
6103
6104            if (mTransferedPackages.contains(pkg.packageName)) {
6105                Slog.w(TAG, "Package " + pkg.packageName
6106                        + " was transferred to another, but its .apk remains");
6107            }
6108
6109            // Just create the setting, don't add it yet. For already existing packages
6110            // the PkgSetting exists already and doesn't have to be created.
6111            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6112                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6113                    pkg.applicationInfo.primaryCpuAbi,
6114                    pkg.applicationInfo.secondaryCpuAbi,
6115                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6116                    user, false);
6117            if (pkgSetting == null) {
6118                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6119                        "Creating application package " + pkg.packageName + " failed");
6120            }
6121
6122            if (pkgSetting.origPackage != null) {
6123                // If we are first transitioning from an original package,
6124                // fix up the new package's name now.  We need to do this after
6125                // looking up the package under its new name, so getPackageLP
6126                // can take care of fiddling things correctly.
6127                pkg.setPackageName(origPackage.name);
6128
6129                // File a report about this.
6130                String msg = "New package " + pkgSetting.realName
6131                        + " renamed to replace old package " + pkgSetting.name;
6132                reportSettingsProblem(Log.WARN, msg);
6133
6134                // Make a note of it.
6135                mTransferedPackages.add(origPackage.name);
6136
6137                // No longer need to retain this.
6138                pkgSetting.origPackage = null;
6139            }
6140
6141            if (realName != null) {
6142                // Make a note of it.
6143                mTransferedPackages.add(pkg.packageName);
6144            }
6145
6146            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6147                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6148            }
6149
6150            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6151                // Check all shared libraries and map to their actual file path.
6152                // We only do this here for apps not on a system dir, because those
6153                // are the only ones that can fail an install due to this.  We
6154                // will take care of the system apps by updating all of their
6155                // library paths after the scan is done.
6156                updateSharedLibrariesLPw(pkg, null);
6157            }
6158
6159            if (mFoundPolicyFile) {
6160                SELinuxMMAC.assignSeinfoValue(pkg);
6161            }
6162
6163            pkg.applicationInfo.uid = pkgSetting.appId;
6164            pkg.mExtras = pkgSetting;
6165            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6166                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6167                    // We just determined the app is signed correctly, so bring
6168                    // over the latest parsed certs.
6169                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6170                } else {
6171                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6172                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6173                                "Package " + pkg.packageName + " upgrade keys do not match the "
6174                                + "previously installed version");
6175                    } else {
6176                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6177                        String msg = "System package " + pkg.packageName
6178                            + " signature changed; retaining data.";
6179                        reportSettingsProblem(Log.WARN, msg);
6180                    }
6181                }
6182            } else {
6183                try {
6184                    verifySignaturesLP(pkgSetting, pkg);
6185                    // We just determined the app is signed correctly, so bring
6186                    // over the latest parsed certs.
6187                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6188                } catch (PackageManagerException e) {
6189                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6190                        throw e;
6191                    }
6192                    // The signature has changed, but this package is in the system
6193                    // image...  let's recover!
6194                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6195                    // However...  if this package is part of a shared user, but it
6196                    // doesn't match the signature of the shared user, let's fail.
6197                    // What this means is that you can't change the signatures
6198                    // associated with an overall shared user, which doesn't seem all
6199                    // that unreasonable.
6200                    if (pkgSetting.sharedUser != null) {
6201                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6202                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6203                            throw new PackageManagerException(
6204                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6205                                            "Signature mismatch for shared user : "
6206                                            + pkgSetting.sharedUser);
6207                        }
6208                    }
6209                    // File a report about this.
6210                    String msg = "System package " + pkg.packageName
6211                        + " signature changed; retaining data.";
6212                    reportSettingsProblem(Log.WARN, msg);
6213                }
6214            }
6215            // Verify that this new package doesn't have any content providers
6216            // that conflict with existing packages.  Only do this if the
6217            // package isn't already installed, since we don't want to break
6218            // things that are installed.
6219            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6220                final int N = pkg.providers.size();
6221                int i;
6222                for (i=0; i<N; i++) {
6223                    PackageParser.Provider p = pkg.providers.get(i);
6224                    if (p.info.authority != null) {
6225                        String names[] = p.info.authority.split(";");
6226                        for (int j = 0; j < names.length; j++) {
6227                            if (mProvidersByAuthority.containsKey(names[j])) {
6228                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6229                                final String otherPackageName =
6230                                        ((other != null && other.getComponentName() != null) ?
6231                                                other.getComponentName().getPackageName() : "?");
6232                                throw new PackageManagerException(
6233                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6234                                                "Can't install because provider name " + names[j]
6235                                                + " (in package " + pkg.applicationInfo.packageName
6236                                                + ") is already used by " + otherPackageName);
6237                            }
6238                        }
6239                    }
6240                }
6241            }
6242
6243            if (pkg.mAdoptPermissions != null) {
6244                // This package wants to adopt ownership of permissions from
6245                // another package.
6246                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6247                    final String origName = pkg.mAdoptPermissions.get(i);
6248                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6249                    if (orig != null) {
6250                        if (verifyPackageUpdateLPr(orig, pkg)) {
6251                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6252                                    + pkg.packageName);
6253                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6254                        }
6255                    }
6256                }
6257            }
6258        }
6259
6260        final String pkgName = pkg.packageName;
6261
6262        final long scanFileTime = scanFile.lastModified();
6263        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6264        pkg.applicationInfo.processName = fixProcessName(
6265                pkg.applicationInfo.packageName,
6266                pkg.applicationInfo.processName,
6267                pkg.applicationInfo.uid);
6268
6269        File dataPath;
6270        if (mPlatformPackage == pkg) {
6271            // The system package is special.
6272            dataPath = new File(Environment.getDataDirectory(), "system");
6273
6274            pkg.applicationInfo.dataDir = dataPath.getPath();
6275
6276        } else {
6277            // This is a normal package, need to make its data directory.
6278            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6279                    UserHandle.USER_OWNER);
6280
6281            boolean uidError = false;
6282            if (dataPath.exists()) {
6283                int currentUid = 0;
6284                try {
6285                    StructStat stat = Os.stat(dataPath.getPath());
6286                    currentUid = stat.st_uid;
6287                } catch (ErrnoException e) {
6288                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6289                }
6290
6291                // If we have mismatched owners for the data path, we have a problem.
6292                if (currentUid != pkg.applicationInfo.uid) {
6293                    boolean recovered = false;
6294                    if (currentUid == 0) {
6295                        // The directory somehow became owned by root.  Wow.
6296                        // This is probably because the system was stopped while
6297                        // installd was in the middle of messing with its libs
6298                        // directory.  Ask installd to fix that.
6299                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6300                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6301                        if (ret >= 0) {
6302                            recovered = true;
6303                            String msg = "Package " + pkg.packageName
6304                                    + " unexpectedly changed to uid 0; recovered to " +
6305                                    + pkg.applicationInfo.uid;
6306                            reportSettingsProblem(Log.WARN, msg);
6307                        }
6308                    }
6309                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6310                            || (scanFlags&SCAN_BOOTING) != 0)) {
6311                        // If this is a system app, we can at least delete its
6312                        // current data so the application will still work.
6313                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6314                        if (ret >= 0) {
6315                            // TODO: Kill the processes first
6316                            // Old data gone!
6317                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6318                                    ? "System package " : "Third party package ";
6319                            String msg = prefix + pkg.packageName
6320                                    + " has changed from uid: "
6321                                    + currentUid + " to "
6322                                    + pkg.applicationInfo.uid + "; old data erased";
6323                            reportSettingsProblem(Log.WARN, msg);
6324                            recovered = true;
6325
6326                            // And now re-install the app.
6327                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6328                                    pkg.applicationInfo.seinfo);
6329                            if (ret == -1) {
6330                                // Ack should not happen!
6331                                msg = prefix + pkg.packageName
6332                                        + " could not have data directory re-created after delete.";
6333                                reportSettingsProblem(Log.WARN, msg);
6334                                throw new PackageManagerException(
6335                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6336                            }
6337                        }
6338                        if (!recovered) {
6339                            mHasSystemUidErrors = true;
6340                        }
6341                    } else if (!recovered) {
6342                        // If we allow this install to proceed, we will be broken.
6343                        // Abort, abort!
6344                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6345                                "scanPackageLI");
6346                    }
6347                    if (!recovered) {
6348                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6349                            + pkg.applicationInfo.uid + "/fs_"
6350                            + currentUid;
6351                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6352                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6353                        String msg = "Package " + pkg.packageName
6354                                + " has mismatched uid: "
6355                                + currentUid + " on disk, "
6356                                + pkg.applicationInfo.uid + " in settings";
6357                        // writer
6358                        synchronized (mPackages) {
6359                            mSettings.mReadMessages.append(msg);
6360                            mSettings.mReadMessages.append('\n');
6361                            uidError = true;
6362                            if (!pkgSetting.uidError) {
6363                                reportSettingsProblem(Log.ERROR, msg);
6364                            }
6365                        }
6366                    }
6367                }
6368                pkg.applicationInfo.dataDir = dataPath.getPath();
6369                if (mShouldRestoreconData) {
6370                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6371                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6372                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6373                }
6374            } else {
6375                if (DEBUG_PACKAGE_SCANNING) {
6376                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6377                        Log.v(TAG, "Want this data dir: " + dataPath);
6378                }
6379                //invoke installer to do the actual installation
6380                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6381                        pkg.applicationInfo.seinfo);
6382                if (ret < 0) {
6383                    // Error from installer
6384                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6385                            "Unable to create data dirs [errorCode=" + ret + "]");
6386                }
6387
6388                if (dataPath.exists()) {
6389                    pkg.applicationInfo.dataDir = dataPath.getPath();
6390                } else {
6391                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6392                    pkg.applicationInfo.dataDir = null;
6393                }
6394            }
6395
6396            pkgSetting.uidError = uidError;
6397        }
6398
6399        final String path = scanFile.getPath();
6400        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6401
6402        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6403            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6404
6405            // Some system apps still use directory structure for native libraries
6406            // in which case we might end up not detecting abi solely based on apk
6407            // structure. Try to detect abi based on directory structure.
6408            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6409                    pkg.applicationInfo.primaryCpuAbi == null) {
6410                setBundledAppAbisAndRoots(pkg, pkgSetting);
6411                setNativeLibraryPaths(pkg);
6412            }
6413
6414        } else {
6415            if ((scanFlags & SCAN_MOVE) != 0) {
6416                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6417                // but we already have this packages package info in the PackageSetting. We just
6418                // use that and derive the native library path based on the new codepath.
6419                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6420                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6421            }
6422
6423            // Set native library paths again. For moves, the path will be updated based on the
6424            // ABIs we've determined above. For non-moves, the path will be updated based on the
6425            // ABIs we determined during compilation, but the path will depend on the final
6426            // package path (after the rename away from the stage path).
6427            setNativeLibraryPaths(pkg);
6428        }
6429
6430        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6431        final int[] userIds = sUserManager.getUserIds();
6432        synchronized (mInstallLock) {
6433            // Create a native library symlink only if we have native libraries
6434            // and if the native libraries are 32 bit libraries. We do not provide
6435            // this symlink for 64 bit libraries.
6436            if (pkg.applicationInfo.primaryCpuAbi != null &&
6437                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6438                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6439                for (int userId : userIds) {
6440                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6441                            nativeLibPath, userId) < 0) {
6442                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6443                                "Failed linking native library dir (user=" + userId + ")");
6444                    }
6445                }
6446            }
6447        }
6448
6449        // This is a special case for the "system" package, where the ABI is
6450        // dictated by the zygote configuration (and init.rc). We should keep track
6451        // of this ABI so that we can deal with "normal" applications that run under
6452        // the same UID correctly.
6453        if (mPlatformPackage == pkg) {
6454            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6455                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6456        }
6457
6458        // If there's a mismatch between the abi-override in the package setting
6459        // and the abiOverride specified for the install. Warn about this because we
6460        // would've already compiled the app without taking the package setting into
6461        // account.
6462        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6463            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6464                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6465                        " for package: " + pkg.packageName);
6466            }
6467        }
6468
6469        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6470        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6471        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6472
6473        // Copy the derived override back to the parsed package, so that we can
6474        // update the package settings accordingly.
6475        pkg.cpuAbiOverride = cpuAbiOverride;
6476
6477        if (DEBUG_ABI_SELECTION) {
6478            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6479                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6480                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6481        }
6482
6483        // Push the derived path down into PackageSettings so we know what to
6484        // clean up at uninstall time.
6485        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6486
6487        if (DEBUG_ABI_SELECTION) {
6488            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6489                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6490                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6491        }
6492
6493        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6494            // We don't do this here during boot because we can do it all
6495            // at once after scanning all existing packages.
6496            //
6497            // We also do this *before* we perform dexopt on this package, so that
6498            // we can avoid redundant dexopts, and also to make sure we've got the
6499            // code and package path correct.
6500            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6501                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6502        }
6503
6504        if ((scanFlags & SCAN_NO_DEX) == 0) {
6505            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6506                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6507            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6508                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6509            }
6510        }
6511        if (mFactoryTest && pkg.requestedPermissions.contains(
6512                android.Manifest.permission.FACTORY_TEST)) {
6513            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6514        }
6515
6516        ArrayList<PackageParser.Package> clientLibPkgs = null;
6517
6518        // writer
6519        synchronized (mPackages) {
6520            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6521                // Only system apps can add new shared libraries.
6522                if (pkg.libraryNames != null) {
6523                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6524                        String name = pkg.libraryNames.get(i);
6525                        boolean allowed = false;
6526                        if (pkg.isUpdatedSystemApp()) {
6527                            // New library entries can only be added through the
6528                            // system image.  This is important to get rid of a lot
6529                            // of nasty edge cases: for example if we allowed a non-
6530                            // system update of the app to add a library, then uninstalling
6531                            // the update would make the library go away, and assumptions
6532                            // we made such as through app install filtering would now
6533                            // have allowed apps on the device which aren't compatible
6534                            // with it.  Better to just have the restriction here, be
6535                            // conservative, and create many fewer cases that can negatively
6536                            // impact the user experience.
6537                            final PackageSetting sysPs = mSettings
6538                                    .getDisabledSystemPkgLPr(pkg.packageName);
6539                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6540                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6541                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6542                                        allowed = true;
6543                                        allowed = true;
6544                                        break;
6545                                    }
6546                                }
6547                            }
6548                        } else {
6549                            allowed = true;
6550                        }
6551                        if (allowed) {
6552                            if (!mSharedLibraries.containsKey(name)) {
6553                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6554                            } else if (!name.equals(pkg.packageName)) {
6555                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6556                                        + name + " already exists; skipping");
6557                            }
6558                        } else {
6559                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6560                                    + name + " that is not declared on system image; skipping");
6561                        }
6562                    }
6563                    if ((scanFlags&SCAN_BOOTING) == 0) {
6564                        // If we are not booting, we need to update any applications
6565                        // that are clients of our shared library.  If we are booting,
6566                        // this will all be done once the scan is complete.
6567                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6568                    }
6569                }
6570            }
6571        }
6572
6573        // We also need to dexopt any apps that are dependent on this library.  Note that
6574        // if these fail, we should abort the install since installing the library will
6575        // result in some apps being broken.
6576        if (clientLibPkgs != null) {
6577            if ((scanFlags & SCAN_NO_DEX) == 0) {
6578                for (int i = 0; i < clientLibPkgs.size(); i++) {
6579                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6580                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6581                            null /* instruction sets */, forceDex,
6582                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6583                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6584                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6585                                "scanPackageLI failed to dexopt clientLibPkgs");
6586                    }
6587                }
6588            }
6589        }
6590
6591        // Also need to kill any apps that are dependent on the library.
6592        if (clientLibPkgs != null) {
6593            for (int i=0; i<clientLibPkgs.size(); i++) {
6594                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6595                killApplication(clientPkg.applicationInfo.packageName,
6596                        clientPkg.applicationInfo.uid, "update lib");
6597            }
6598        }
6599
6600        // Make sure we're not adding any bogus keyset info
6601        KeySetManagerService ksms = mSettings.mKeySetManagerService;
6602        ksms.assertScannedPackageValid(pkg);
6603
6604        // writer
6605        synchronized (mPackages) {
6606            // We don't expect installation to fail beyond this point
6607
6608            // Add the new setting to mSettings
6609            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6610            // Add the new setting to mPackages
6611            mPackages.put(pkg.applicationInfo.packageName, pkg);
6612            // Make sure we don't accidentally delete its data.
6613            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6614            while (iter.hasNext()) {
6615                PackageCleanItem item = iter.next();
6616                if (pkgName.equals(item.packageName)) {
6617                    iter.remove();
6618                }
6619            }
6620
6621            // Take care of first install / last update times.
6622            if (currentTime != 0) {
6623                if (pkgSetting.firstInstallTime == 0) {
6624                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6625                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6626                    pkgSetting.lastUpdateTime = currentTime;
6627                }
6628            } else if (pkgSetting.firstInstallTime == 0) {
6629                // We need *something*.  Take time time stamp of the file.
6630                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6631            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6632                if (scanFileTime != pkgSetting.timeStamp) {
6633                    // A package on the system image has changed; consider this
6634                    // to be an update.
6635                    pkgSetting.lastUpdateTime = scanFileTime;
6636                }
6637            }
6638
6639            // Add the package's KeySets to the global KeySetManagerService
6640            ksms.addScannedPackageLPw(pkg);
6641
6642            int N = pkg.providers.size();
6643            StringBuilder r = null;
6644            int i;
6645            for (i=0; i<N; i++) {
6646                PackageParser.Provider p = pkg.providers.get(i);
6647                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6648                        p.info.processName, pkg.applicationInfo.uid);
6649                mProviders.addProvider(p);
6650                p.syncable = p.info.isSyncable;
6651                if (p.info.authority != null) {
6652                    String names[] = p.info.authority.split(";");
6653                    p.info.authority = null;
6654                    for (int j = 0; j < names.length; j++) {
6655                        if (j == 1 && p.syncable) {
6656                            // We only want the first authority for a provider to possibly be
6657                            // syncable, so if we already added this provider using a different
6658                            // authority clear the syncable flag. We copy the provider before
6659                            // changing it because the mProviders object contains a reference
6660                            // to a provider that we don't want to change.
6661                            // Only do this for the second authority since the resulting provider
6662                            // object can be the same for all future authorities for this provider.
6663                            p = new PackageParser.Provider(p);
6664                            p.syncable = false;
6665                        }
6666                        if (!mProvidersByAuthority.containsKey(names[j])) {
6667                            mProvidersByAuthority.put(names[j], p);
6668                            if (p.info.authority == null) {
6669                                p.info.authority = names[j];
6670                            } else {
6671                                p.info.authority = p.info.authority + ";" + names[j];
6672                            }
6673                            if (DEBUG_PACKAGE_SCANNING) {
6674                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6675                                    Log.d(TAG, "Registered content provider: " + names[j]
6676                                            + ", className = " + p.info.name + ", isSyncable = "
6677                                            + p.info.isSyncable);
6678                            }
6679                        } else {
6680                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6681                            Slog.w(TAG, "Skipping provider name " + names[j] +
6682                                    " (in package " + pkg.applicationInfo.packageName +
6683                                    "): name already used by "
6684                                    + ((other != null && other.getComponentName() != null)
6685                                            ? other.getComponentName().getPackageName() : "?"));
6686                        }
6687                    }
6688                }
6689                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6690                    if (r == null) {
6691                        r = new StringBuilder(256);
6692                    } else {
6693                        r.append(' ');
6694                    }
6695                    r.append(p.info.name);
6696                }
6697            }
6698            if (r != null) {
6699                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6700            }
6701
6702            N = pkg.services.size();
6703            r = null;
6704            for (i=0; i<N; i++) {
6705                PackageParser.Service s = pkg.services.get(i);
6706                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6707                        s.info.processName, pkg.applicationInfo.uid);
6708                mServices.addService(s);
6709                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6710                    if (r == null) {
6711                        r = new StringBuilder(256);
6712                    } else {
6713                        r.append(' ');
6714                    }
6715                    r.append(s.info.name);
6716                }
6717            }
6718            if (r != null) {
6719                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6720            }
6721
6722            N = pkg.receivers.size();
6723            r = null;
6724            for (i=0; i<N; i++) {
6725                PackageParser.Activity a = pkg.receivers.get(i);
6726                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6727                        a.info.processName, pkg.applicationInfo.uid);
6728                mReceivers.addActivity(a, "receiver");
6729                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6730                    if (r == null) {
6731                        r = new StringBuilder(256);
6732                    } else {
6733                        r.append(' ');
6734                    }
6735                    r.append(a.info.name);
6736                }
6737            }
6738            if (r != null) {
6739                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6740            }
6741
6742            N = pkg.activities.size();
6743            r = null;
6744            for (i=0; i<N; i++) {
6745                PackageParser.Activity a = pkg.activities.get(i);
6746                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6747                        a.info.processName, pkg.applicationInfo.uid);
6748                mActivities.addActivity(a, "activity");
6749                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6750                    if (r == null) {
6751                        r = new StringBuilder(256);
6752                    } else {
6753                        r.append(' ');
6754                    }
6755                    r.append(a.info.name);
6756                }
6757            }
6758            if (r != null) {
6759                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6760            }
6761
6762            N = pkg.permissionGroups.size();
6763            r = null;
6764            for (i=0; i<N; i++) {
6765                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6766                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6767                if (cur == null) {
6768                    mPermissionGroups.put(pg.info.name, pg);
6769                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6770                        if (r == null) {
6771                            r = new StringBuilder(256);
6772                        } else {
6773                            r.append(' ');
6774                        }
6775                        r.append(pg.info.name);
6776                    }
6777                } else {
6778                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6779                            + pg.info.packageName + " ignored: original from "
6780                            + cur.info.packageName);
6781                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6782                        if (r == null) {
6783                            r = new StringBuilder(256);
6784                        } else {
6785                            r.append(' ');
6786                        }
6787                        r.append("DUP:");
6788                        r.append(pg.info.name);
6789                    }
6790                }
6791            }
6792            if (r != null) {
6793                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6794            }
6795
6796            N = pkg.permissions.size();
6797            r = null;
6798            for (i=0; i<N; i++) {
6799                PackageParser.Permission p = pkg.permissions.get(i);
6800
6801                // Now that permission groups have a special meaning, we ignore permission
6802                // groups for legacy apps to prevent unexpected behavior. In particular,
6803                // permissions for one app being granted to someone just becuase they happen
6804                // to be in a group defined by another app (before this had no implications).
6805                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6806                    p.group = mPermissionGroups.get(p.info.group);
6807                    // Warn for a permission in an unknown group.
6808                    if (p.info.group != null && p.group == null) {
6809                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6810                                + p.info.packageName + " in an unknown group " + p.info.group);
6811                    }
6812                }
6813
6814                ArrayMap<String, BasePermission> permissionMap =
6815                        p.tree ? mSettings.mPermissionTrees
6816                                : mSettings.mPermissions;
6817                BasePermission bp = permissionMap.get(p.info.name);
6818
6819                // Allow system apps to redefine non-system permissions
6820                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6821                    final boolean currentOwnerIsSystem = (bp.perm != null
6822                            && isSystemApp(bp.perm.owner));
6823                    if (isSystemApp(p.owner)) {
6824                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6825                            // It's a built-in permission and no owner, take ownership now
6826                            bp.packageSetting = pkgSetting;
6827                            bp.perm = p;
6828                            bp.uid = pkg.applicationInfo.uid;
6829                            bp.sourcePackage = p.info.packageName;
6830                        } else if (!currentOwnerIsSystem) {
6831                            String msg = "New decl " + p.owner + " of permission  "
6832                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6833                            reportSettingsProblem(Log.WARN, msg);
6834                            bp = null;
6835                        }
6836                    }
6837                }
6838
6839                if (bp == null) {
6840                    bp = new BasePermission(p.info.name, p.info.packageName,
6841                            BasePermission.TYPE_NORMAL);
6842                    permissionMap.put(p.info.name, bp);
6843                }
6844
6845                if (bp.perm == null) {
6846                    if (bp.sourcePackage == null
6847                            || bp.sourcePackage.equals(p.info.packageName)) {
6848                        BasePermission tree = findPermissionTreeLP(p.info.name);
6849                        if (tree == null
6850                                || tree.sourcePackage.equals(p.info.packageName)) {
6851                            bp.packageSetting = pkgSetting;
6852                            bp.perm = p;
6853                            bp.uid = pkg.applicationInfo.uid;
6854                            bp.sourcePackage = p.info.packageName;
6855                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6856                                if (r == null) {
6857                                    r = new StringBuilder(256);
6858                                } else {
6859                                    r.append(' ');
6860                                }
6861                                r.append(p.info.name);
6862                            }
6863                        } else {
6864                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6865                                    + p.info.packageName + " ignored: base tree "
6866                                    + tree.name + " is from package "
6867                                    + tree.sourcePackage);
6868                        }
6869                    } else {
6870                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6871                                + p.info.packageName + " ignored: original from "
6872                                + bp.sourcePackage);
6873                    }
6874                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6875                    if (r == null) {
6876                        r = new StringBuilder(256);
6877                    } else {
6878                        r.append(' ');
6879                    }
6880                    r.append("DUP:");
6881                    r.append(p.info.name);
6882                }
6883                if (bp.perm == p) {
6884                    bp.protectionLevel = p.info.protectionLevel;
6885                }
6886            }
6887
6888            if (r != null) {
6889                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6890            }
6891
6892            N = pkg.instrumentation.size();
6893            r = null;
6894            for (i=0; i<N; i++) {
6895                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6896                a.info.packageName = pkg.applicationInfo.packageName;
6897                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6898                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6899                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6900                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6901                a.info.dataDir = pkg.applicationInfo.dataDir;
6902
6903                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6904                // need other information about the application, like the ABI and what not ?
6905                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6906                mInstrumentation.put(a.getComponentName(), a);
6907                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6908                    if (r == null) {
6909                        r = new StringBuilder(256);
6910                    } else {
6911                        r.append(' ');
6912                    }
6913                    r.append(a.info.name);
6914                }
6915            }
6916            if (r != null) {
6917                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6918            }
6919
6920            if (pkg.protectedBroadcasts != null) {
6921                N = pkg.protectedBroadcasts.size();
6922                for (i=0; i<N; i++) {
6923                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6924                }
6925            }
6926
6927            pkgSetting.setTimeStamp(scanFileTime);
6928
6929            // Create idmap files for pairs of (packages, overlay packages).
6930            // Note: "android", ie framework-res.apk, is handled by native layers.
6931            if (pkg.mOverlayTarget != null) {
6932                // This is an overlay package.
6933                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6934                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6935                        mOverlays.put(pkg.mOverlayTarget,
6936                                new ArrayMap<String, PackageParser.Package>());
6937                    }
6938                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6939                    map.put(pkg.packageName, pkg);
6940                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6941                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6942                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6943                                "scanPackageLI failed to createIdmap");
6944                    }
6945                }
6946            } else if (mOverlays.containsKey(pkg.packageName) &&
6947                    !pkg.packageName.equals("android")) {
6948                // This is a regular package, with one or more known overlay packages.
6949                createIdmapsForPackageLI(pkg);
6950            }
6951        }
6952
6953        return pkg;
6954    }
6955
6956    /**
6957     * Derive the ABI of a non-system package located at {@code scanFile}. This information
6958     * is derived purely on the basis of the contents of {@code scanFile} and
6959     * {@code cpuAbiOverride}.
6960     *
6961     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
6962     */
6963    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
6964                                 String cpuAbiOverride, boolean extractLibs)
6965            throws PackageManagerException {
6966        // TODO: We can probably be smarter about this stuff. For installed apps,
6967        // we can calculate this information at install time once and for all. For
6968        // system apps, we can probably assume that this information doesn't change
6969        // after the first boot scan. As things stand, we do lots of unnecessary work.
6970
6971        // Give ourselves some initial paths; we'll come back for another
6972        // pass once we've determined ABI below.
6973        setNativeLibraryPaths(pkg);
6974
6975        // We would never need to extract libs for forward-locked and external packages,
6976        // since the container service will do it for us. We shouldn't attempt to
6977        // extract libs from system app when it was not updated.
6978        if (pkg.isForwardLocked() || isExternal(pkg) ||
6979            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
6980            extractLibs = false;
6981        }
6982
6983        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6984        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6985
6986        NativeLibraryHelper.Handle handle = null;
6987        try {
6988            handle = NativeLibraryHelper.Handle.create(scanFile);
6989            // TODO(multiArch): This can be null for apps that didn't go through the
6990            // usual installation process. We can calculate it again, like we
6991            // do during install time.
6992            //
6993            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6994            // unnecessary.
6995            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6996
6997            // Null out the abis so that they can be recalculated.
6998            pkg.applicationInfo.primaryCpuAbi = null;
6999            pkg.applicationInfo.secondaryCpuAbi = null;
7000            if (isMultiArch(pkg.applicationInfo)) {
7001                // Warn if we've set an abiOverride for multi-lib packages..
7002                // By definition, we need to copy both 32 and 64 bit libraries for
7003                // such packages.
7004                if (pkg.cpuAbiOverride != null
7005                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7006                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7007                }
7008
7009                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7010                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7011                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7012                    if (extractLibs) {
7013                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7014                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7015                                useIsaSpecificSubdirs);
7016                    } else {
7017                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7018                    }
7019                }
7020
7021                maybeThrowExceptionForMultiArchCopy(
7022                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7023
7024                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7025                    if (extractLibs) {
7026                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7027                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7028                                useIsaSpecificSubdirs);
7029                    } else {
7030                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7031                    }
7032                }
7033
7034                maybeThrowExceptionForMultiArchCopy(
7035                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7036
7037                if (abi64 >= 0) {
7038                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7039                }
7040
7041                if (abi32 >= 0) {
7042                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7043                    if (abi64 >= 0) {
7044                        pkg.applicationInfo.secondaryCpuAbi = abi;
7045                    } else {
7046                        pkg.applicationInfo.primaryCpuAbi = abi;
7047                    }
7048                }
7049            } else {
7050                String[] abiList = (cpuAbiOverride != null) ?
7051                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7052
7053                // Enable gross and lame hacks for apps that are built with old
7054                // SDK tools. We must scan their APKs for renderscript bitcode and
7055                // not launch them if it's present. Don't bother checking on devices
7056                // that don't have 64 bit support.
7057                boolean needsRenderScriptOverride = false;
7058                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7059                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7060                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7061                    needsRenderScriptOverride = true;
7062                }
7063
7064                final int copyRet;
7065                if (extractLibs) {
7066                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7067                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7068                } else {
7069                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7070                }
7071
7072                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7073                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7074                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7075                }
7076
7077                if (copyRet >= 0) {
7078                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7079                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7080                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7081                } else if (needsRenderScriptOverride) {
7082                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7083                }
7084            }
7085        } catch (IOException ioe) {
7086            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7087        } finally {
7088            IoUtils.closeQuietly(handle);
7089        }
7090
7091        // Now that we've calculated the ABIs and determined if it's an internal app,
7092        // we will go ahead and populate the nativeLibraryPath.
7093        setNativeLibraryPaths(pkg);
7094    }
7095
7096    /**
7097     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7098     * i.e, so that all packages can be run inside a single process if required.
7099     *
7100     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7101     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7102     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7103     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7104     * updating a package that belongs to a shared user.
7105     *
7106     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7107     * adds unnecessary complexity.
7108     */
7109    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7110            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7111        String requiredInstructionSet = null;
7112        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7113            requiredInstructionSet = VMRuntime.getInstructionSet(
7114                     scannedPackage.applicationInfo.primaryCpuAbi);
7115        }
7116
7117        PackageSetting requirer = null;
7118        for (PackageSetting ps : packagesForUser) {
7119            // If packagesForUser contains scannedPackage, we skip it. This will happen
7120            // when scannedPackage is an update of an existing package. Without this check,
7121            // we will never be able to change the ABI of any package belonging to a shared
7122            // user, even if it's compatible with other packages.
7123            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7124                if (ps.primaryCpuAbiString == null) {
7125                    continue;
7126                }
7127
7128                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7129                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7130                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7131                    // this but there's not much we can do.
7132                    String errorMessage = "Instruction set mismatch, "
7133                            + ((requirer == null) ? "[caller]" : requirer)
7134                            + " requires " + requiredInstructionSet + " whereas " + ps
7135                            + " requires " + instructionSet;
7136                    Slog.w(TAG, errorMessage);
7137                }
7138
7139                if (requiredInstructionSet == null) {
7140                    requiredInstructionSet = instructionSet;
7141                    requirer = ps;
7142                }
7143            }
7144        }
7145
7146        if (requiredInstructionSet != null) {
7147            String adjustedAbi;
7148            if (requirer != null) {
7149                // requirer != null implies that either scannedPackage was null or that scannedPackage
7150                // did not require an ABI, in which case we have to adjust scannedPackage to match
7151                // the ABI of the set (which is the same as requirer's ABI)
7152                adjustedAbi = requirer.primaryCpuAbiString;
7153                if (scannedPackage != null) {
7154                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7155                }
7156            } else {
7157                // requirer == null implies that we're updating all ABIs in the set to
7158                // match scannedPackage.
7159                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7160            }
7161
7162            for (PackageSetting ps : packagesForUser) {
7163                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7164                    if (ps.primaryCpuAbiString != null) {
7165                        continue;
7166                    }
7167
7168                    ps.primaryCpuAbiString = adjustedAbi;
7169                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7170                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7171                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7172
7173                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7174                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7175                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7176                            ps.primaryCpuAbiString = null;
7177                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7178                            return;
7179                        } else {
7180                            mInstaller.rmdex(ps.codePathString,
7181                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7182                        }
7183                    }
7184                }
7185            }
7186        }
7187    }
7188
7189    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7190        synchronized (mPackages) {
7191            mResolverReplaced = true;
7192            // Set up information for custom user intent resolution activity.
7193            mResolveActivity.applicationInfo = pkg.applicationInfo;
7194            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7195            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7196            mResolveActivity.processName = pkg.applicationInfo.packageName;
7197            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7198            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7199                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7200            mResolveActivity.theme = 0;
7201            mResolveActivity.exported = true;
7202            mResolveActivity.enabled = true;
7203            mResolveInfo.activityInfo = mResolveActivity;
7204            mResolveInfo.priority = 0;
7205            mResolveInfo.preferredOrder = 0;
7206            mResolveInfo.match = 0;
7207            mResolveComponentName = mCustomResolverComponentName;
7208            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7209                    mResolveComponentName);
7210        }
7211    }
7212
7213    private static String calculateBundledApkRoot(final String codePathString) {
7214        final File codePath = new File(codePathString);
7215        final File codeRoot;
7216        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7217            codeRoot = Environment.getRootDirectory();
7218        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7219            codeRoot = Environment.getOemDirectory();
7220        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7221            codeRoot = Environment.getVendorDirectory();
7222        } else {
7223            // Unrecognized code path; take its top real segment as the apk root:
7224            // e.g. /something/app/blah.apk => /something
7225            try {
7226                File f = codePath.getCanonicalFile();
7227                File parent = f.getParentFile();    // non-null because codePath is a file
7228                File tmp;
7229                while ((tmp = parent.getParentFile()) != null) {
7230                    f = parent;
7231                    parent = tmp;
7232                }
7233                codeRoot = f;
7234                Slog.w(TAG, "Unrecognized code path "
7235                        + codePath + " - using " + codeRoot);
7236            } catch (IOException e) {
7237                // Can't canonicalize the code path -- shenanigans?
7238                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7239                return Environment.getRootDirectory().getPath();
7240            }
7241        }
7242        return codeRoot.getPath();
7243    }
7244
7245    /**
7246     * Derive and set the location of native libraries for the given package,
7247     * which varies depending on where and how the package was installed.
7248     */
7249    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7250        final ApplicationInfo info = pkg.applicationInfo;
7251        final String codePath = pkg.codePath;
7252        final File codeFile = new File(codePath);
7253        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7254        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7255
7256        info.nativeLibraryRootDir = null;
7257        info.nativeLibraryRootRequiresIsa = false;
7258        info.nativeLibraryDir = null;
7259        info.secondaryNativeLibraryDir = null;
7260
7261        if (isApkFile(codeFile)) {
7262            // Monolithic install
7263            if (bundledApp) {
7264                // If "/system/lib64/apkname" exists, assume that is the per-package
7265                // native library directory to use; otherwise use "/system/lib/apkname".
7266                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7267                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7268                        getPrimaryInstructionSet(info));
7269
7270                // This is a bundled system app so choose the path based on the ABI.
7271                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7272                // is just the default path.
7273                final String apkName = deriveCodePathName(codePath);
7274                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7275                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7276                        apkName).getAbsolutePath();
7277
7278                if (info.secondaryCpuAbi != null) {
7279                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7280                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7281                            secondaryLibDir, apkName).getAbsolutePath();
7282                }
7283            } else if (asecApp) {
7284                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7285                        .getAbsolutePath();
7286            } else {
7287                final String apkName = deriveCodePathName(codePath);
7288                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7289                        .getAbsolutePath();
7290            }
7291
7292            info.nativeLibraryRootRequiresIsa = false;
7293            info.nativeLibraryDir = info.nativeLibraryRootDir;
7294        } else {
7295            // Cluster install
7296            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7297            info.nativeLibraryRootRequiresIsa = true;
7298
7299            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7300                    getPrimaryInstructionSet(info)).getAbsolutePath();
7301
7302            if (info.secondaryCpuAbi != null) {
7303                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7304                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7305            }
7306        }
7307    }
7308
7309    /**
7310     * Calculate the abis and roots for a bundled app. These can uniquely
7311     * be determined from the contents of the system partition, i.e whether
7312     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7313     * of this information, and instead assume that the system was built
7314     * sensibly.
7315     */
7316    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7317                                           PackageSetting pkgSetting) {
7318        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7319
7320        // If "/system/lib64/apkname" exists, assume that is the per-package
7321        // native library directory to use; otherwise use "/system/lib/apkname".
7322        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7323        setBundledAppAbi(pkg, apkRoot, apkName);
7324        // pkgSetting might be null during rescan following uninstall of updates
7325        // to a bundled app, so accommodate that possibility.  The settings in
7326        // that case will be established later from the parsed package.
7327        //
7328        // If the settings aren't null, sync them up with what we've just derived.
7329        // note that apkRoot isn't stored in the package settings.
7330        if (pkgSetting != null) {
7331            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7332            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7333        }
7334    }
7335
7336    /**
7337     * Deduces the ABI of a bundled app and sets the relevant fields on the
7338     * parsed pkg object.
7339     *
7340     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7341     *        under which system libraries are installed.
7342     * @param apkName the name of the installed package.
7343     */
7344    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7345        final File codeFile = new File(pkg.codePath);
7346
7347        final boolean has64BitLibs;
7348        final boolean has32BitLibs;
7349        if (isApkFile(codeFile)) {
7350            // Monolithic install
7351            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7352            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7353        } else {
7354            // Cluster install
7355            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7356            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7357                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7358                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7359                has64BitLibs = (new File(rootDir, isa)).exists();
7360            } else {
7361                has64BitLibs = false;
7362            }
7363            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7364                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7365                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7366                has32BitLibs = (new File(rootDir, isa)).exists();
7367            } else {
7368                has32BitLibs = false;
7369            }
7370        }
7371
7372        if (has64BitLibs && !has32BitLibs) {
7373            // The package has 64 bit libs, but not 32 bit libs. Its primary
7374            // ABI should be 64 bit. We can safely assume here that the bundled
7375            // native libraries correspond to the most preferred ABI in the list.
7376
7377            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7378            pkg.applicationInfo.secondaryCpuAbi = null;
7379        } else if (has32BitLibs && !has64BitLibs) {
7380            // The package has 32 bit libs but not 64 bit libs. Its primary
7381            // ABI should be 32 bit.
7382
7383            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7384            pkg.applicationInfo.secondaryCpuAbi = null;
7385        } else if (has32BitLibs && has64BitLibs) {
7386            // The application has both 64 and 32 bit bundled libraries. We check
7387            // here that the app declares multiArch support, and warn if it doesn't.
7388            //
7389            // We will be lenient here and record both ABIs. The primary will be the
7390            // ABI that's higher on the list, i.e, a device that's configured to prefer
7391            // 64 bit apps will see a 64 bit primary ABI,
7392
7393            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7394                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7395            }
7396
7397            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7398                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7399                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7400            } else {
7401                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7402                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7403            }
7404        } else {
7405            pkg.applicationInfo.primaryCpuAbi = null;
7406            pkg.applicationInfo.secondaryCpuAbi = null;
7407        }
7408    }
7409
7410    private void killApplication(String pkgName, int appId, String reason) {
7411        // Request the ActivityManager to kill the process(only for existing packages)
7412        // so that we do not end up in a confused state while the user is still using the older
7413        // version of the application while the new one gets installed.
7414        IActivityManager am = ActivityManagerNative.getDefault();
7415        if (am != null) {
7416            try {
7417                am.killApplicationWithAppId(pkgName, appId, reason);
7418            } catch (RemoteException e) {
7419            }
7420        }
7421    }
7422
7423    void removePackageLI(PackageSetting ps, boolean chatty) {
7424        if (DEBUG_INSTALL) {
7425            if (chatty)
7426                Log.d(TAG, "Removing package " + ps.name);
7427        }
7428
7429        // writer
7430        synchronized (mPackages) {
7431            mPackages.remove(ps.name);
7432            final PackageParser.Package pkg = ps.pkg;
7433            if (pkg != null) {
7434                cleanPackageDataStructuresLILPw(pkg, chatty);
7435            }
7436        }
7437    }
7438
7439    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7440        if (DEBUG_INSTALL) {
7441            if (chatty)
7442                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7443        }
7444
7445        // writer
7446        synchronized (mPackages) {
7447            mPackages.remove(pkg.applicationInfo.packageName);
7448            cleanPackageDataStructuresLILPw(pkg, chatty);
7449        }
7450    }
7451
7452    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7453        int N = pkg.providers.size();
7454        StringBuilder r = null;
7455        int i;
7456        for (i=0; i<N; i++) {
7457            PackageParser.Provider p = pkg.providers.get(i);
7458            mProviders.removeProvider(p);
7459            if (p.info.authority == null) {
7460
7461                /* There was another ContentProvider with this authority when
7462                 * this app was installed so this authority is null,
7463                 * Ignore it as we don't have to unregister the provider.
7464                 */
7465                continue;
7466            }
7467            String names[] = p.info.authority.split(";");
7468            for (int j = 0; j < names.length; j++) {
7469                if (mProvidersByAuthority.get(names[j]) == p) {
7470                    mProvidersByAuthority.remove(names[j]);
7471                    if (DEBUG_REMOVE) {
7472                        if (chatty)
7473                            Log.d(TAG, "Unregistered content provider: " + names[j]
7474                                    + ", className = " + p.info.name + ", isSyncable = "
7475                                    + p.info.isSyncable);
7476                    }
7477                }
7478            }
7479            if (DEBUG_REMOVE && chatty) {
7480                if (r == null) {
7481                    r = new StringBuilder(256);
7482                } else {
7483                    r.append(' ');
7484                }
7485                r.append(p.info.name);
7486            }
7487        }
7488        if (r != null) {
7489            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7490        }
7491
7492        N = pkg.services.size();
7493        r = null;
7494        for (i=0; i<N; i++) {
7495            PackageParser.Service s = pkg.services.get(i);
7496            mServices.removeService(s);
7497            if (chatty) {
7498                if (r == null) {
7499                    r = new StringBuilder(256);
7500                } else {
7501                    r.append(' ');
7502                }
7503                r.append(s.info.name);
7504            }
7505        }
7506        if (r != null) {
7507            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7508        }
7509
7510        N = pkg.receivers.size();
7511        r = null;
7512        for (i=0; i<N; i++) {
7513            PackageParser.Activity a = pkg.receivers.get(i);
7514            mReceivers.removeActivity(a, "receiver");
7515            if (DEBUG_REMOVE && chatty) {
7516                if (r == null) {
7517                    r = new StringBuilder(256);
7518                } else {
7519                    r.append(' ');
7520                }
7521                r.append(a.info.name);
7522            }
7523        }
7524        if (r != null) {
7525            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7526        }
7527
7528        N = pkg.activities.size();
7529        r = null;
7530        for (i=0; i<N; i++) {
7531            PackageParser.Activity a = pkg.activities.get(i);
7532            mActivities.removeActivity(a, "activity");
7533            if (DEBUG_REMOVE && chatty) {
7534                if (r == null) {
7535                    r = new StringBuilder(256);
7536                } else {
7537                    r.append(' ');
7538                }
7539                r.append(a.info.name);
7540            }
7541        }
7542        if (r != null) {
7543            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7544        }
7545
7546        N = pkg.permissions.size();
7547        r = null;
7548        for (i=0; i<N; i++) {
7549            PackageParser.Permission p = pkg.permissions.get(i);
7550            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7551            if (bp == null) {
7552                bp = mSettings.mPermissionTrees.get(p.info.name);
7553            }
7554            if (bp != null && bp.perm == p) {
7555                bp.perm = null;
7556                if (DEBUG_REMOVE && chatty) {
7557                    if (r == null) {
7558                        r = new StringBuilder(256);
7559                    } else {
7560                        r.append(' ');
7561                    }
7562                    r.append(p.info.name);
7563                }
7564            }
7565            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7566                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7567                if (appOpPerms != null) {
7568                    appOpPerms.remove(pkg.packageName);
7569                }
7570            }
7571        }
7572        if (r != null) {
7573            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7574        }
7575
7576        N = pkg.requestedPermissions.size();
7577        r = null;
7578        for (i=0; i<N; i++) {
7579            String perm = pkg.requestedPermissions.get(i);
7580            BasePermission bp = mSettings.mPermissions.get(perm);
7581            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7582                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7583                if (appOpPerms != null) {
7584                    appOpPerms.remove(pkg.packageName);
7585                    if (appOpPerms.isEmpty()) {
7586                        mAppOpPermissionPackages.remove(perm);
7587                    }
7588                }
7589            }
7590        }
7591        if (r != null) {
7592            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7593        }
7594
7595        N = pkg.instrumentation.size();
7596        r = null;
7597        for (i=0; i<N; i++) {
7598            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7599            mInstrumentation.remove(a.getComponentName());
7600            if (DEBUG_REMOVE && chatty) {
7601                if (r == null) {
7602                    r = new StringBuilder(256);
7603                } else {
7604                    r.append(' ');
7605                }
7606                r.append(a.info.name);
7607            }
7608        }
7609        if (r != null) {
7610            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7611        }
7612
7613        r = null;
7614        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7615            // Only system apps can hold shared libraries.
7616            if (pkg.libraryNames != null) {
7617                for (i=0; i<pkg.libraryNames.size(); i++) {
7618                    String name = pkg.libraryNames.get(i);
7619                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7620                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7621                        mSharedLibraries.remove(name);
7622                        if (DEBUG_REMOVE && chatty) {
7623                            if (r == null) {
7624                                r = new StringBuilder(256);
7625                            } else {
7626                                r.append(' ');
7627                            }
7628                            r.append(name);
7629                        }
7630                    }
7631                }
7632            }
7633        }
7634        if (r != null) {
7635            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7636        }
7637    }
7638
7639    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7640        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7641            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7642                return true;
7643            }
7644        }
7645        return false;
7646    }
7647
7648    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7649    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7650    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7651
7652    private void updatePermissionsLPw(String changingPkg,
7653            PackageParser.Package pkgInfo, int flags) {
7654        // Make sure there are no dangling permission trees.
7655        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7656        while (it.hasNext()) {
7657            final BasePermission bp = it.next();
7658            if (bp.packageSetting == null) {
7659                // We may not yet have parsed the package, so just see if
7660                // we still know about its settings.
7661                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7662            }
7663            if (bp.packageSetting == null) {
7664                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7665                        + " from package " + bp.sourcePackage);
7666                it.remove();
7667            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7668                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7669                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7670                            + " from package " + bp.sourcePackage);
7671                    flags |= UPDATE_PERMISSIONS_ALL;
7672                    it.remove();
7673                }
7674            }
7675        }
7676
7677        // Make sure all dynamic permissions have been assigned to a package,
7678        // and make sure there are no dangling permissions.
7679        it = mSettings.mPermissions.values().iterator();
7680        while (it.hasNext()) {
7681            final BasePermission bp = it.next();
7682            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7683                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7684                        + bp.name + " pkg=" + bp.sourcePackage
7685                        + " info=" + bp.pendingInfo);
7686                if (bp.packageSetting == null && bp.pendingInfo != null) {
7687                    final BasePermission tree = findPermissionTreeLP(bp.name);
7688                    if (tree != null && tree.perm != null) {
7689                        bp.packageSetting = tree.packageSetting;
7690                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7691                                new PermissionInfo(bp.pendingInfo));
7692                        bp.perm.info.packageName = tree.perm.info.packageName;
7693                        bp.perm.info.name = bp.name;
7694                        bp.uid = tree.uid;
7695                    }
7696                }
7697            }
7698            if (bp.packageSetting == null) {
7699                // We may not yet have parsed the package, so just see if
7700                // we still know about its settings.
7701                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7702            }
7703            if (bp.packageSetting == null) {
7704                Slog.w(TAG, "Removing dangling permission: " + bp.name
7705                        + " from package " + bp.sourcePackage);
7706                it.remove();
7707            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7708                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7709                    Slog.i(TAG, "Removing old permission: " + bp.name
7710                            + " from package " + bp.sourcePackage);
7711                    flags |= UPDATE_PERMISSIONS_ALL;
7712                    it.remove();
7713                }
7714            }
7715        }
7716
7717        // Now update the permissions for all packages, in particular
7718        // replace the granted permissions of the system packages.
7719        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7720            for (PackageParser.Package pkg : mPackages.values()) {
7721                if (pkg != pkgInfo) {
7722                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7723                            changingPkg);
7724                }
7725            }
7726        }
7727
7728        if (pkgInfo != null) {
7729            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7730        }
7731    }
7732
7733    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7734            String packageOfInterest) {
7735        // IMPORTANT: There are two types of permissions: install and runtime.
7736        // Install time permissions are granted when the app is installed to
7737        // all device users and users added in the future. Runtime permissions
7738        // are granted at runtime explicitly to specific users. Normal and signature
7739        // protected permissions are install time permissions. Dangerous permissions
7740        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7741        // otherwise they are runtime permissions. This function does not manage
7742        // runtime permissions except for the case an app targeting Lollipop MR1
7743        // being upgraded to target a newer SDK, in which case dangerous permissions
7744        // are transformed from install time to runtime ones.
7745
7746        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7747        if (ps == null) {
7748            return;
7749        }
7750
7751        PermissionsState permissionsState = ps.getPermissionsState();
7752        PermissionsState origPermissions = permissionsState;
7753
7754        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7755
7756        int[] upgradeUserIds = EMPTY_INT_ARRAY;
7757        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7758
7759        boolean changedInstallPermission = false;
7760
7761        if (replace) {
7762            ps.installPermissionsFixed = false;
7763            if (!ps.isSharedUser()) {
7764                origPermissions = new PermissionsState(permissionsState);
7765                permissionsState.reset();
7766            }
7767        }
7768
7769        permissionsState.setGlobalGids(mGlobalGids);
7770
7771        final int N = pkg.requestedPermissions.size();
7772        for (int i=0; i<N; i++) {
7773            final String name = pkg.requestedPermissions.get(i);
7774            final BasePermission bp = mSettings.mPermissions.get(name);
7775
7776            if (DEBUG_INSTALL) {
7777                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7778            }
7779
7780            if (bp == null || bp.packageSetting == null) {
7781                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7782                    Slog.w(TAG, "Unknown permission " + name
7783                            + " in package " + pkg.packageName);
7784                }
7785                continue;
7786            }
7787
7788            final String perm = bp.name;
7789            boolean allowedSig = false;
7790            int grant = GRANT_DENIED;
7791
7792            // Keep track of app op permissions.
7793            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7794                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7795                if (pkgs == null) {
7796                    pkgs = new ArraySet<>();
7797                    mAppOpPermissionPackages.put(bp.name, pkgs);
7798                }
7799                pkgs.add(pkg.packageName);
7800            }
7801
7802            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7803            switch (level) {
7804                case PermissionInfo.PROTECTION_NORMAL: {
7805                    // For all apps normal permissions are install time ones.
7806                    grant = GRANT_INSTALL;
7807                } break;
7808
7809                case PermissionInfo.PROTECTION_DANGEROUS: {
7810                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7811                        // For legacy apps dangerous permissions are install time ones.
7812                        grant = GRANT_INSTALL_LEGACY;
7813                    } else if (ps.isSystem()) {
7814                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7815                        if (origPermissions.hasInstallPermission(bp.name)) {
7816                            // If a system app had an install permission, then the app was
7817                            // upgraded and we grant the permissions as runtime to all users.
7818                            grant = GRANT_UPGRADE;
7819                            upgradeUserIds = currentUserIds;
7820                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7821                            // If users changed since the last permissions update for a
7822                            // system app, we grant the permission as runtime to the new users.
7823                            grant = GRANT_UPGRADE;
7824                            upgradeUserIds = currentUserIds;
7825                            for (int userId : updatedUserIds) {
7826                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7827                            }
7828                        } else {
7829                            // Otherwise, we grant the permission as runtime if the app
7830                            // already had it, i.e. we preserve runtime permissions.
7831                            grant = GRANT_RUNTIME;
7832                        }
7833                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7834                        // For legacy apps that became modern, install becomes runtime.
7835                        grant = GRANT_UPGRADE;
7836                        upgradeUserIds = currentUserIds;
7837                    } else if (replace) {
7838                        // For upgraded modern apps keep runtime permissions unchanged.
7839                        grant = GRANT_RUNTIME;
7840                    }
7841                } break;
7842
7843                case PermissionInfo.PROTECTION_SIGNATURE: {
7844                    // For all apps signature permissions are install time ones.
7845                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7846                    if (allowedSig) {
7847                        grant = GRANT_INSTALL;
7848                    }
7849                } break;
7850            }
7851
7852            if (DEBUG_INSTALL) {
7853                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7854            }
7855
7856            if (grant != GRANT_DENIED) {
7857                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7858                    // If this is an existing, non-system package, then
7859                    // we can't add any new permissions to it.
7860                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7861                        // Except...  if this is a permission that was added
7862                        // to the platform (note: need to only do this when
7863                        // updating the platform).
7864                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7865                            grant = GRANT_DENIED;
7866                        }
7867                    }
7868                }
7869
7870                switch (grant) {
7871                    case GRANT_INSTALL: {
7872                        // Revoke this as runtime permission to handle the case of
7873                        // a runtime permssion being downgraded to an install one.
7874                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7875                            if (origPermissions.getRuntimePermissionState(
7876                                    bp.name, userId) != null) {
7877                                // Revoke the runtime permission and clear the flags.
7878                                origPermissions.revokeRuntimePermission(bp, userId);
7879                                origPermissions.updatePermissionFlags(bp, userId,
7880                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
7881                                // If we revoked a permission permission, we have to write.
7882                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7883                                        changedRuntimePermissionUserIds, userId);
7884                            }
7885                        }
7886                        // Grant an install permission.
7887                        if (permissionsState.grantInstallPermission(bp) !=
7888                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7889                            changedInstallPermission = true;
7890                        }
7891                    } break;
7892
7893                    case GRANT_INSTALL_LEGACY: {
7894                        // Grant an install permission.
7895                        if (permissionsState.grantInstallPermission(bp) !=
7896                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7897                            changedInstallPermission = true;
7898                        }
7899                    } break;
7900
7901                    case GRANT_RUNTIME: {
7902                        // Grant previously granted runtime permissions.
7903                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7904                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7905                                PermissionState permissionState = origPermissions
7906                                        .getRuntimePermissionState(bp.name, userId);
7907                                final int flags = permissionState.getFlags();
7908                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7909                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7910                                    // If we cannot put the permission as it was, we have to write.
7911                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7912                                            changedRuntimePermissionUserIds, userId);
7913                                } else {
7914                                    // System components not only get the permissions but
7915                                    // they are also fixed, so nothing can change that.
7916                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7917                                            ? flags
7918                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7919                                    // Propagate the permission flags.
7920                                    permissionsState.updatePermissionFlags(bp, userId,
7921                                            newFlags, newFlags);
7922                                }
7923                            }
7924                        }
7925                    } break;
7926
7927                    case GRANT_UPGRADE: {
7928                        // Grant runtime permissions for a previously held install permission.
7929                        PermissionState permissionState = origPermissions
7930                                .getInstallPermissionState(bp.name);
7931                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
7932
7933                        origPermissions.revokeInstallPermission(bp);
7934                        // We will be transferring the permission flags, so clear them.
7935                        origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
7936                                PackageManager.MASK_PERMISSION_FLAGS, 0);
7937
7938                        // If the permission is not to be promoted to runtime we ignore it and
7939                        // also its other flags as they are not applicable to install permissions.
7940                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
7941                            for (int userId : upgradeUserIds) {
7942                                if (permissionsState.grantRuntimePermission(bp, userId) !=
7943                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7944                                    // System components not only get the permissions but
7945                                    // they are also fixed so nothing can change that.
7946                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7947                                            ? flags
7948                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7949                                    // Transfer the permission flags.
7950                                    permissionsState.updatePermissionFlags(bp, userId,
7951                                            newFlags, newFlags);
7952                                    // If we granted the permission, we have to write.
7953                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7954                                            changedRuntimePermissionUserIds, userId);
7955                                }
7956                            }
7957                        }
7958                    } break;
7959
7960                    default: {
7961                        if (packageOfInterest == null
7962                                || packageOfInterest.equals(pkg.packageName)) {
7963                            Slog.w(TAG, "Not granting permission " + perm
7964                                    + " to package " + pkg.packageName
7965                                    + " because it was previously installed without");
7966                        }
7967                    } break;
7968                }
7969            } else {
7970                if (permissionsState.revokeInstallPermission(bp) !=
7971                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7972                    // Also drop the permission flags.
7973                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
7974                            PackageManager.MASK_PERMISSION_FLAGS, 0);
7975                    changedInstallPermission = true;
7976                    Slog.i(TAG, "Un-granting permission " + perm
7977                            + " from package " + pkg.packageName
7978                            + " (protectionLevel=" + bp.protectionLevel
7979                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7980                            + ")");
7981                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7982                    // Don't print warning for app op permissions, since it is fine for them
7983                    // not to be granted, there is a UI for the user to decide.
7984                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7985                        Slog.w(TAG, "Not granting permission " + perm
7986                                + " to package " + pkg.packageName
7987                                + " (protectionLevel=" + bp.protectionLevel
7988                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7989                                + ")");
7990                    }
7991                }
7992            }
7993        }
7994
7995        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7996                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7997            // This is the first that we have heard about this package, so the
7998            // permissions we have now selected are fixed until explicitly
7999            // changed.
8000            ps.installPermissionsFixed = true;
8001        }
8002
8003        ps.setPermissionsUpdatedForUserIds(currentUserIds);
8004
8005        // Persist the runtime permissions state for users with changes.
8006        for (int userId : changedRuntimePermissionUserIds) {
8007            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8008        }
8009    }
8010
8011    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8012        boolean allowed = false;
8013        final int NP = PackageParser.NEW_PERMISSIONS.length;
8014        for (int ip=0; ip<NP; ip++) {
8015            final PackageParser.NewPermissionInfo npi
8016                    = PackageParser.NEW_PERMISSIONS[ip];
8017            if (npi.name.equals(perm)
8018                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8019                allowed = true;
8020                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8021                        + pkg.packageName);
8022                break;
8023            }
8024        }
8025        return allowed;
8026    }
8027
8028    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8029            BasePermission bp, PermissionsState origPermissions) {
8030        boolean allowed;
8031        allowed = (compareSignatures(
8032                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8033                        == PackageManager.SIGNATURE_MATCH)
8034                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8035                        == PackageManager.SIGNATURE_MATCH);
8036        if (!allowed && (bp.protectionLevel
8037                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8038            if (isSystemApp(pkg)) {
8039                // For updated system applications, a system permission
8040                // is granted only if it had been defined by the original application.
8041                if (pkg.isUpdatedSystemApp()) {
8042                    final PackageSetting sysPs = mSettings
8043                            .getDisabledSystemPkgLPr(pkg.packageName);
8044                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8045                        // If the original was granted this permission, we take
8046                        // that grant decision as read and propagate it to the
8047                        // update.
8048                        if (sysPs.isPrivileged()) {
8049                            allowed = true;
8050                        }
8051                    } else {
8052                        // The system apk may have been updated with an older
8053                        // version of the one on the data partition, but which
8054                        // granted a new system permission that it didn't have
8055                        // before.  In this case we do want to allow the app to
8056                        // now get the new permission if the ancestral apk is
8057                        // privileged to get it.
8058                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8059                            for (int j=0;
8060                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8061                                if (perm.equals(
8062                                        sysPs.pkg.requestedPermissions.get(j))) {
8063                                    allowed = true;
8064                                    break;
8065                                }
8066                            }
8067                        }
8068                    }
8069                } else {
8070                    allowed = isPrivilegedApp(pkg);
8071                }
8072            }
8073        }
8074        if (!allowed && (bp.protectionLevel
8075                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8076            // For development permissions, a development permission
8077            // is granted only if it was already granted.
8078            allowed = origPermissions.hasInstallPermission(perm);
8079        }
8080        return allowed;
8081    }
8082
8083    final class ActivityIntentResolver
8084            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8085        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8086                boolean defaultOnly, int userId) {
8087            if (!sUserManager.exists(userId)) return null;
8088            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8089            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8090        }
8091
8092        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8093                int userId) {
8094            if (!sUserManager.exists(userId)) return null;
8095            mFlags = flags;
8096            return super.queryIntent(intent, resolvedType,
8097                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8098        }
8099
8100        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8101                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8102            if (!sUserManager.exists(userId)) return null;
8103            if (packageActivities == null) {
8104                return null;
8105            }
8106            mFlags = flags;
8107            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8108            final int N = packageActivities.size();
8109            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8110                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8111
8112            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8113            for (int i = 0; i < N; ++i) {
8114                intentFilters = packageActivities.get(i).intents;
8115                if (intentFilters != null && intentFilters.size() > 0) {
8116                    PackageParser.ActivityIntentInfo[] array =
8117                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8118                    intentFilters.toArray(array);
8119                    listCut.add(array);
8120                }
8121            }
8122            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8123        }
8124
8125        public final void addActivity(PackageParser.Activity a, String type) {
8126            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8127            mActivities.put(a.getComponentName(), a);
8128            if (DEBUG_SHOW_INFO)
8129                Log.v(
8130                TAG, "  " + type + " " +
8131                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8132            if (DEBUG_SHOW_INFO)
8133                Log.v(TAG, "    Class=" + a.info.name);
8134            final int NI = a.intents.size();
8135            for (int j=0; j<NI; j++) {
8136                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8137                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8138                    intent.setPriority(0);
8139                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8140                            + a.className + " with priority > 0, forcing to 0");
8141                }
8142                if (DEBUG_SHOW_INFO) {
8143                    Log.v(TAG, "    IntentFilter:");
8144                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8145                }
8146                if (!intent.debugCheck()) {
8147                    Log.w(TAG, "==> For Activity " + a.info.name);
8148                }
8149                addFilter(intent);
8150            }
8151        }
8152
8153        public final void removeActivity(PackageParser.Activity a, String type) {
8154            mActivities.remove(a.getComponentName());
8155            if (DEBUG_SHOW_INFO) {
8156                Log.v(TAG, "  " + type + " "
8157                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8158                                : a.info.name) + ":");
8159                Log.v(TAG, "    Class=" + a.info.name);
8160            }
8161            final int NI = a.intents.size();
8162            for (int j=0; j<NI; j++) {
8163                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8164                if (DEBUG_SHOW_INFO) {
8165                    Log.v(TAG, "    IntentFilter:");
8166                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8167                }
8168                removeFilter(intent);
8169            }
8170        }
8171
8172        @Override
8173        protected boolean allowFilterResult(
8174                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8175            ActivityInfo filterAi = filter.activity.info;
8176            for (int i=dest.size()-1; i>=0; i--) {
8177                ActivityInfo destAi = dest.get(i).activityInfo;
8178                if (destAi.name == filterAi.name
8179                        && destAi.packageName == filterAi.packageName) {
8180                    return false;
8181                }
8182            }
8183            return true;
8184        }
8185
8186        @Override
8187        protected ActivityIntentInfo[] newArray(int size) {
8188            return new ActivityIntentInfo[size];
8189        }
8190
8191        @Override
8192        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8193            if (!sUserManager.exists(userId)) return true;
8194            PackageParser.Package p = filter.activity.owner;
8195            if (p != null) {
8196                PackageSetting ps = (PackageSetting)p.mExtras;
8197                if (ps != null) {
8198                    // System apps are never considered stopped for purposes of
8199                    // filtering, because there may be no way for the user to
8200                    // actually re-launch them.
8201                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8202                            && ps.getStopped(userId);
8203                }
8204            }
8205            return false;
8206        }
8207
8208        @Override
8209        protected boolean isPackageForFilter(String packageName,
8210                PackageParser.ActivityIntentInfo info) {
8211            return packageName.equals(info.activity.owner.packageName);
8212        }
8213
8214        @Override
8215        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8216                int match, int userId) {
8217            if (!sUserManager.exists(userId)) return null;
8218            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8219                return null;
8220            }
8221            final PackageParser.Activity activity = info.activity;
8222            if (mSafeMode && (activity.info.applicationInfo.flags
8223                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8224                return null;
8225            }
8226            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8227            if (ps == null) {
8228                return null;
8229            }
8230            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8231                    ps.readUserState(userId), userId);
8232            if (ai == null) {
8233                return null;
8234            }
8235            final ResolveInfo res = new ResolveInfo();
8236            res.activityInfo = ai;
8237            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8238                res.filter = info;
8239            }
8240            if (info != null) {
8241                res.handleAllWebDataURI = info.handleAllWebDataURI();
8242            }
8243            res.priority = info.getPriority();
8244            res.preferredOrder = activity.owner.mPreferredOrder;
8245            //System.out.println("Result: " + res.activityInfo.className +
8246            //                   " = " + res.priority);
8247            res.match = match;
8248            res.isDefault = info.hasDefault;
8249            res.labelRes = info.labelRes;
8250            res.nonLocalizedLabel = info.nonLocalizedLabel;
8251            if (userNeedsBadging(userId)) {
8252                res.noResourceId = true;
8253            } else {
8254                res.icon = info.icon;
8255            }
8256            res.iconResourceId = info.icon;
8257            res.system = res.activityInfo.applicationInfo.isSystemApp();
8258            return res;
8259        }
8260
8261        @Override
8262        protected void sortResults(List<ResolveInfo> results) {
8263            Collections.sort(results, mResolvePrioritySorter);
8264        }
8265
8266        @Override
8267        protected void dumpFilter(PrintWriter out, String prefix,
8268                PackageParser.ActivityIntentInfo filter) {
8269            out.print(prefix); out.print(
8270                    Integer.toHexString(System.identityHashCode(filter.activity)));
8271                    out.print(' ');
8272                    filter.activity.printComponentShortName(out);
8273                    out.print(" filter ");
8274                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8275        }
8276
8277        @Override
8278        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8279            return filter.activity;
8280        }
8281
8282        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8283            PackageParser.Activity activity = (PackageParser.Activity)label;
8284            out.print(prefix); out.print(
8285                    Integer.toHexString(System.identityHashCode(activity)));
8286                    out.print(' ');
8287                    activity.printComponentShortName(out);
8288            if (count > 1) {
8289                out.print(" ("); out.print(count); out.print(" filters)");
8290            }
8291            out.println();
8292        }
8293
8294//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8295//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8296//            final List<ResolveInfo> retList = Lists.newArrayList();
8297//            while (i.hasNext()) {
8298//                final ResolveInfo resolveInfo = i.next();
8299//                if (isEnabledLP(resolveInfo.activityInfo)) {
8300//                    retList.add(resolveInfo);
8301//                }
8302//            }
8303//            return retList;
8304//        }
8305
8306        // Keys are String (activity class name), values are Activity.
8307        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8308                = new ArrayMap<ComponentName, PackageParser.Activity>();
8309        private int mFlags;
8310    }
8311
8312    private final class ServiceIntentResolver
8313            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8314        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8315                boolean defaultOnly, int userId) {
8316            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8317            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8318        }
8319
8320        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8321                int userId) {
8322            if (!sUserManager.exists(userId)) return null;
8323            mFlags = flags;
8324            return super.queryIntent(intent, resolvedType,
8325                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8326        }
8327
8328        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8329                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8330            if (!sUserManager.exists(userId)) return null;
8331            if (packageServices == null) {
8332                return null;
8333            }
8334            mFlags = flags;
8335            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8336            final int N = packageServices.size();
8337            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8338                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8339
8340            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8341            for (int i = 0; i < N; ++i) {
8342                intentFilters = packageServices.get(i).intents;
8343                if (intentFilters != null && intentFilters.size() > 0) {
8344                    PackageParser.ServiceIntentInfo[] array =
8345                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8346                    intentFilters.toArray(array);
8347                    listCut.add(array);
8348                }
8349            }
8350            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8351        }
8352
8353        public final void addService(PackageParser.Service s) {
8354            mServices.put(s.getComponentName(), s);
8355            if (DEBUG_SHOW_INFO) {
8356                Log.v(TAG, "  "
8357                        + (s.info.nonLocalizedLabel != null
8358                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8359                Log.v(TAG, "    Class=" + s.info.name);
8360            }
8361            final int NI = s.intents.size();
8362            int j;
8363            for (j=0; j<NI; j++) {
8364                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8365                if (DEBUG_SHOW_INFO) {
8366                    Log.v(TAG, "    IntentFilter:");
8367                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8368                }
8369                if (!intent.debugCheck()) {
8370                    Log.w(TAG, "==> For Service " + s.info.name);
8371                }
8372                addFilter(intent);
8373            }
8374        }
8375
8376        public final void removeService(PackageParser.Service s) {
8377            mServices.remove(s.getComponentName());
8378            if (DEBUG_SHOW_INFO) {
8379                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8380                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8381                Log.v(TAG, "    Class=" + s.info.name);
8382            }
8383            final int NI = s.intents.size();
8384            int j;
8385            for (j=0; j<NI; j++) {
8386                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8387                if (DEBUG_SHOW_INFO) {
8388                    Log.v(TAG, "    IntentFilter:");
8389                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8390                }
8391                removeFilter(intent);
8392            }
8393        }
8394
8395        @Override
8396        protected boolean allowFilterResult(
8397                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8398            ServiceInfo filterSi = filter.service.info;
8399            for (int i=dest.size()-1; i>=0; i--) {
8400                ServiceInfo destAi = dest.get(i).serviceInfo;
8401                if (destAi.name == filterSi.name
8402                        && destAi.packageName == filterSi.packageName) {
8403                    return false;
8404                }
8405            }
8406            return true;
8407        }
8408
8409        @Override
8410        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8411            return new PackageParser.ServiceIntentInfo[size];
8412        }
8413
8414        @Override
8415        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8416            if (!sUserManager.exists(userId)) return true;
8417            PackageParser.Package p = filter.service.owner;
8418            if (p != null) {
8419                PackageSetting ps = (PackageSetting)p.mExtras;
8420                if (ps != null) {
8421                    // System apps are never considered stopped for purposes of
8422                    // filtering, because there may be no way for the user to
8423                    // actually re-launch them.
8424                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8425                            && ps.getStopped(userId);
8426                }
8427            }
8428            return false;
8429        }
8430
8431        @Override
8432        protected boolean isPackageForFilter(String packageName,
8433                PackageParser.ServiceIntentInfo info) {
8434            return packageName.equals(info.service.owner.packageName);
8435        }
8436
8437        @Override
8438        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8439                int match, int userId) {
8440            if (!sUserManager.exists(userId)) return null;
8441            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8442            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8443                return null;
8444            }
8445            final PackageParser.Service service = info.service;
8446            if (mSafeMode && (service.info.applicationInfo.flags
8447                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8448                return null;
8449            }
8450            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8451            if (ps == null) {
8452                return null;
8453            }
8454            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8455                    ps.readUserState(userId), userId);
8456            if (si == null) {
8457                return null;
8458            }
8459            final ResolveInfo res = new ResolveInfo();
8460            res.serviceInfo = si;
8461            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8462                res.filter = filter;
8463            }
8464            res.priority = info.getPriority();
8465            res.preferredOrder = service.owner.mPreferredOrder;
8466            res.match = match;
8467            res.isDefault = info.hasDefault;
8468            res.labelRes = info.labelRes;
8469            res.nonLocalizedLabel = info.nonLocalizedLabel;
8470            res.icon = info.icon;
8471            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8472            return res;
8473        }
8474
8475        @Override
8476        protected void sortResults(List<ResolveInfo> results) {
8477            Collections.sort(results, mResolvePrioritySorter);
8478        }
8479
8480        @Override
8481        protected void dumpFilter(PrintWriter out, String prefix,
8482                PackageParser.ServiceIntentInfo filter) {
8483            out.print(prefix); out.print(
8484                    Integer.toHexString(System.identityHashCode(filter.service)));
8485                    out.print(' ');
8486                    filter.service.printComponentShortName(out);
8487                    out.print(" filter ");
8488                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8489        }
8490
8491        @Override
8492        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8493            return filter.service;
8494        }
8495
8496        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8497            PackageParser.Service service = (PackageParser.Service)label;
8498            out.print(prefix); out.print(
8499                    Integer.toHexString(System.identityHashCode(service)));
8500                    out.print(' ');
8501                    service.printComponentShortName(out);
8502            if (count > 1) {
8503                out.print(" ("); out.print(count); out.print(" filters)");
8504            }
8505            out.println();
8506        }
8507
8508//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8509//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8510//            final List<ResolveInfo> retList = Lists.newArrayList();
8511//            while (i.hasNext()) {
8512//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8513//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8514//                    retList.add(resolveInfo);
8515//                }
8516//            }
8517//            return retList;
8518//        }
8519
8520        // Keys are String (activity class name), values are Activity.
8521        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8522                = new ArrayMap<ComponentName, PackageParser.Service>();
8523        private int mFlags;
8524    };
8525
8526    private final class ProviderIntentResolver
8527            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8528        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8529                boolean defaultOnly, int userId) {
8530            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8531            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8532        }
8533
8534        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8535                int userId) {
8536            if (!sUserManager.exists(userId))
8537                return null;
8538            mFlags = flags;
8539            return super.queryIntent(intent, resolvedType,
8540                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8541        }
8542
8543        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8544                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8545            if (!sUserManager.exists(userId))
8546                return null;
8547            if (packageProviders == null) {
8548                return null;
8549            }
8550            mFlags = flags;
8551            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8552            final int N = packageProviders.size();
8553            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8554                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8555
8556            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8557            for (int i = 0; i < N; ++i) {
8558                intentFilters = packageProviders.get(i).intents;
8559                if (intentFilters != null && intentFilters.size() > 0) {
8560                    PackageParser.ProviderIntentInfo[] array =
8561                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8562                    intentFilters.toArray(array);
8563                    listCut.add(array);
8564                }
8565            }
8566            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8567        }
8568
8569        public final void addProvider(PackageParser.Provider p) {
8570            if (mProviders.containsKey(p.getComponentName())) {
8571                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8572                return;
8573            }
8574
8575            mProviders.put(p.getComponentName(), p);
8576            if (DEBUG_SHOW_INFO) {
8577                Log.v(TAG, "  "
8578                        + (p.info.nonLocalizedLabel != null
8579                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8580                Log.v(TAG, "    Class=" + p.info.name);
8581            }
8582            final int NI = p.intents.size();
8583            int j;
8584            for (j = 0; j < NI; j++) {
8585                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8586                if (DEBUG_SHOW_INFO) {
8587                    Log.v(TAG, "    IntentFilter:");
8588                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8589                }
8590                if (!intent.debugCheck()) {
8591                    Log.w(TAG, "==> For Provider " + p.info.name);
8592                }
8593                addFilter(intent);
8594            }
8595        }
8596
8597        public final void removeProvider(PackageParser.Provider p) {
8598            mProviders.remove(p.getComponentName());
8599            if (DEBUG_SHOW_INFO) {
8600                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8601                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8602                Log.v(TAG, "    Class=" + p.info.name);
8603            }
8604            final int NI = p.intents.size();
8605            int j;
8606            for (j = 0; j < NI; j++) {
8607                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8608                if (DEBUG_SHOW_INFO) {
8609                    Log.v(TAG, "    IntentFilter:");
8610                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8611                }
8612                removeFilter(intent);
8613            }
8614        }
8615
8616        @Override
8617        protected boolean allowFilterResult(
8618                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8619            ProviderInfo filterPi = filter.provider.info;
8620            for (int i = dest.size() - 1; i >= 0; i--) {
8621                ProviderInfo destPi = dest.get(i).providerInfo;
8622                if (destPi.name == filterPi.name
8623                        && destPi.packageName == filterPi.packageName) {
8624                    return false;
8625                }
8626            }
8627            return true;
8628        }
8629
8630        @Override
8631        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8632            return new PackageParser.ProviderIntentInfo[size];
8633        }
8634
8635        @Override
8636        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8637            if (!sUserManager.exists(userId))
8638                return true;
8639            PackageParser.Package p = filter.provider.owner;
8640            if (p != null) {
8641                PackageSetting ps = (PackageSetting) p.mExtras;
8642                if (ps != null) {
8643                    // System apps are never considered stopped for purposes of
8644                    // filtering, because there may be no way for the user to
8645                    // actually re-launch them.
8646                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8647                            && ps.getStopped(userId);
8648                }
8649            }
8650            return false;
8651        }
8652
8653        @Override
8654        protected boolean isPackageForFilter(String packageName,
8655                PackageParser.ProviderIntentInfo info) {
8656            return packageName.equals(info.provider.owner.packageName);
8657        }
8658
8659        @Override
8660        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8661                int match, int userId) {
8662            if (!sUserManager.exists(userId))
8663                return null;
8664            final PackageParser.ProviderIntentInfo info = filter;
8665            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8666                return null;
8667            }
8668            final PackageParser.Provider provider = info.provider;
8669            if (mSafeMode && (provider.info.applicationInfo.flags
8670                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8671                return null;
8672            }
8673            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8674            if (ps == null) {
8675                return null;
8676            }
8677            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8678                    ps.readUserState(userId), userId);
8679            if (pi == null) {
8680                return null;
8681            }
8682            final ResolveInfo res = new ResolveInfo();
8683            res.providerInfo = pi;
8684            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8685                res.filter = filter;
8686            }
8687            res.priority = info.getPriority();
8688            res.preferredOrder = provider.owner.mPreferredOrder;
8689            res.match = match;
8690            res.isDefault = info.hasDefault;
8691            res.labelRes = info.labelRes;
8692            res.nonLocalizedLabel = info.nonLocalizedLabel;
8693            res.icon = info.icon;
8694            res.system = res.providerInfo.applicationInfo.isSystemApp();
8695            return res;
8696        }
8697
8698        @Override
8699        protected void sortResults(List<ResolveInfo> results) {
8700            Collections.sort(results, mResolvePrioritySorter);
8701        }
8702
8703        @Override
8704        protected void dumpFilter(PrintWriter out, String prefix,
8705                PackageParser.ProviderIntentInfo filter) {
8706            out.print(prefix);
8707            out.print(
8708                    Integer.toHexString(System.identityHashCode(filter.provider)));
8709            out.print(' ');
8710            filter.provider.printComponentShortName(out);
8711            out.print(" filter ");
8712            out.println(Integer.toHexString(System.identityHashCode(filter)));
8713        }
8714
8715        @Override
8716        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8717            return filter.provider;
8718        }
8719
8720        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8721            PackageParser.Provider provider = (PackageParser.Provider)label;
8722            out.print(prefix); out.print(
8723                    Integer.toHexString(System.identityHashCode(provider)));
8724                    out.print(' ');
8725                    provider.printComponentShortName(out);
8726            if (count > 1) {
8727                out.print(" ("); out.print(count); out.print(" filters)");
8728            }
8729            out.println();
8730        }
8731
8732        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8733                = new ArrayMap<ComponentName, PackageParser.Provider>();
8734        private int mFlags;
8735    };
8736
8737    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8738            new Comparator<ResolveInfo>() {
8739        public int compare(ResolveInfo r1, ResolveInfo r2) {
8740            int v1 = r1.priority;
8741            int v2 = r2.priority;
8742            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8743            if (v1 != v2) {
8744                return (v1 > v2) ? -1 : 1;
8745            }
8746            v1 = r1.preferredOrder;
8747            v2 = r2.preferredOrder;
8748            if (v1 != v2) {
8749                return (v1 > v2) ? -1 : 1;
8750            }
8751            if (r1.isDefault != r2.isDefault) {
8752                return r1.isDefault ? -1 : 1;
8753            }
8754            v1 = r1.match;
8755            v2 = r2.match;
8756            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8757            if (v1 != v2) {
8758                return (v1 > v2) ? -1 : 1;
8759            }
8760            if (r1.system != r2.system) {
8761                return r1.system ? -1 : 1;
8762            }
8763            return 0;
8764        }
8765    };
8766
8767    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8768            new Comparator<ProviderInfo>() {
8769        public int compare(ProviderInfo p1, ProviderInfo p2) {
8770            final int v1 = p1.initOrder;
8771            final int v2 = p2.initOrder;
8772            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8773        }
8774    };
8775
8776    final void sendPackageBroadcast(final String action, final String pkg,
8777            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8778            final int[] userIds) {
8779        mHandler.post(new Runnable() {
8780            @Override
8781            public void run() {
8782                try {
8783                    final IActivityManager am = ActivityManagerNative.getDefault();
8784                    if (am == null) return;
8785                    final int[] resolvedUserIds;
8786                    if (userIds == null) {
8787                        resolvedUserIds = am.getRunningUserIds();
8788                    } else {
8789                        resolvedUserIds = userIds;
8790                    }
8791                    for (int id : resolvedUserIds) {
8792                        final Intent intent = new Intent(action,
8793                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8794                        if (extras != null) {
8795                            intent.putExtras(extras);
8796                        }
8797                        if (targetPkg != null) {
8798                            intent.setPackage(targetPkg);
8799                        }
8800                        // Modify the UID when posting to other users
8801                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8802                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8803                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8804                            intent.putExtra(Intent.EXTRA_UID, uid);
8805                        }
8806                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8807                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8808                        if (DEBUG_BROADCASTS) {
8809                            RuntimeException here = new RuntimeException("here");
8810                            here.fillInStackTrace();
8811                            Slog.d(TAG, "Sending to user " + id + ": "
8812                                    + intent.toShortString(false, true, false, false)
8813                                    + " " + intent.getExtras(), here);
8814                        }
8815                        am.broadcastIntent(null, intent, null, finishedReceiver,
8816                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8817                                null, finishedReceiver != null, false, id);
8818                    }
8819                } catch (RemoteException ex) {
8820                }
8821            }
8822        });
8823    }
8824
8825    /**
8826     * Check if the external storage media is available. This is true if there
8827     * is a mounted external storage medium or if the external storage is
8828     * emulated.
8829     */
8830    private boolean isExternalMediaAvailable() {
8831        return mMediaMounted || Environment.isExternalStorageEmulated();
8832    }
8833
8834    @Override
8835    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8836        // writer
8837        synchronized (mPackages) {
8838            if (!isExternalMediaAvailable()) {
8839                // If the external storage is no longer mounted at this point,
8840                // the caller may not have been able to delete all of this
8841                // packages files and can not delete any more.  Bail.
8842                return null;
8843            }
8844            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8845            if (lastPackage != null) {
8846                pkgs.remove(lastPackage);
8847            }
8848            if (pkgs.size() > 0) {
8849                return pkgs.get(0);
8850            }
8851        }
8852        return null;
8853    }
8854
8855    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8856        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8857                userId, andCode ? 1 : 0, packageName);
8858        if (mSystemReady) {
8859            msg.sendToTarget();
8860        } else {
8861            if (mPostSystemReadyMessages == null) {
8862                mPostSystemReadyMessages = new ArrayList<>();
8863            }
8864            mPostSystemReadyMessages.add(msg);
8865        }
8866    }
8867
8868    void startCleaningPackages() {
8869        // reader
8870        synchronized (mPackages) {
8871            if (!isExternalMediaAvailable()) {
8872                return;
8873            }
8874            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8875                return;
8876            }
8877        }
8878        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8879        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8880        IActivityManager am = ActivityManagerNative.getDefault();
8881        if (am != null) {
8882            try {
8883                am.startService(null, intent, null, UserHandle.USER_OWNER);
8884            } catch (RemoteException e) {
8885            }
8886        }
8887    }
8888
8889    @Override
8890    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8891            int installFlags, String installerPackageName, VerificationParams verificationParams,
8892            String packageAbiOverride) {
8893        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8894                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8895    }
8896
8897    @Override
8898    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8899            int installFlags, String installerPackageName, VerificationParams verificationParams,
8900            String packageAbiOverride, int userId) {
8901        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8902
8903        final int callingUid = Binder.getCallingUid();
8904        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8905
8906        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8907            try {
8908                if (observer != null) {
8909                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8910                }
8911            } catch (RemoteException re) {
8912            }
8913            return;
8914        }
8915
8916        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8917            installFlags |= PackageManager.INSTALL_FROM_ADB;
8918
8919        } else {
8920            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8921            // about installerPackageName.
8922
8923            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8924            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8925        }
8926
8927        UserHandle user;
8928        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8929            user = UserHandle.ALL;
8930        } else {
8931            user = new UserHandle(userId);
8932        }
8933
8934        // Only system components can circumvent runtime permissions when installing.
8935        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
8936                && mContext.checkCallingOrSelfPermission(Manifest.permission
8937                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
8938            throw new SecurityException("You need the "
8939                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
8940                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
8941        }
8942
8943        verificationParams.setInstallerUid(callingUid);
8944
8945        final File originFile = new File(originPath);
8946        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8947
8948        final Message msg = mHandler.obtainMessage(INIT_COPY);
8949        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
8950                null, verificationParams, user, packageAbiOverride);
8951        mHandler.sendMessage(msg);
8952    }
8953
8954    void installStage(String packageName, File stagedDir, String stagedCid,
8955            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8956            String installerPackageName, int installerUid, UserHandle user) {
8957        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8958                params.referrerUri, installerUid, null);
8959
8960        final OriginInfo origin;
8961        if (stagedDir != null) {
8962            origin = OriginInfo.fromStagedFile(stagedDir);
8963        } else {
8964            origin = OriginInfo.fromStagedContainer(stagedCid);
8965        }
8966
8967        final Message msg = mHandler.obtainMessage(INIT_COPY);
8968        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
8969                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8970        mHandler.sendMessage(msg);
8971    }
8972
8973    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8974        Bundle extras = new Bundle(1);
8975        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8976
8977        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8978                packageName, extras, null, null, new int[] {userId});
8979        try {
8980            IActivityManager am = ActivityManagerNative.getDefault();
8981            final boolean isSystem =
8982                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8983            if (isSystem && am.isUserRunning(userId, false)) {
8984                // The just-installed/enabled app is bundled on the system, so presumed
8985                // to be able to run automatically without needing an explicit launch.
8986                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8987                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8988                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8989                        .setPackage(packageName);
8990                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8991                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
8992            }
8993        } catch (RemoteException e) {
8994            // shouldn't happen
8995            Slog.w(TAG, "Unable to bootstrap installed package", e);
8996        }
8997    }
8998
8999    @Override
9000    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9001            int userId) {
9002        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9003        PackageSetting pkgSetting;
9004        final int uid = Binder.getCallingUid();
9005        enforceCrossUserPermission(uid, userId, true, true,
9006                "setApplicationHiddenSetting for user " + userId);
9007
9008        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9009            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9010            return false;
9011        }
9012
9013        long callingId = Binder.clearCallingIdentity();
9014        try {
9015            boolean sendAdded = false;
9016            boolean sendRemoved = false;
9017            // writer
9018            synchronized (mPackages) {
9019                pkgSetting = mSettings.mPackages.get(packageName);
9020                if (pkgSetting == null) {
9021                    return false;
9022                }
9023                if (pkgSetting.getHidden(userId) != hidden) {
9024                    pkgSetting.setHidden(hidden, userId);
9025                    mSettings.writePackageRestrictionsLPr(userId);
9026                    if (hidden) {
9027                        sendRemoved = true;
9028                    } else {
9029                        sendAdded = true;
9030                    }
9031                }
9032            }
9033            if (sendAdded) {
9034                sendPackageAddedForUser(packageName, pkgSetting, userId);
9035                return true;
9036            }
9037            if (sendRemoved) {
9038                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9039                        "hiding pkg");
9040                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9041            }
9042        } finally {
9043            Binder.restoreCallingIdentity(callingId);
9044        }
9045        return false;
9046    }
9047
9048    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9049            int userId) {
9050        final PackageRemovedInfo info = new PackageRemovedInfo();
9051        info.removedPackage = packageName;
9052        info.removedUsers = new int[] {userId};
9053        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9054        info.sendBroadcast(false, false, false);
9055    }
9056
9057    /**
9058     * Returns true if application is not found or there was an error. Otherwise it returns
9059     * the hidden state of the package for the given user.
9060     */
9061    @Override
9062    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9063        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9064        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9065                false, "getApplicationHidden for user " + userId);
9066        PackageSetting pkgSetting;
9067        long callingId = Binder.clearCallingIdentity();
9068        try {
9069            // writer
9070            synchronized (mPackages) {
9071                pkgSetting = mSettings.mPackages.get(packageName);
9072                if (pkgSetting == null) {
9073                    return true;
9074                }
9075                return pkgSetting.getHidden(userId);
9076            }
9077        } finally {
9078            Binder.restoreCallingIdentity(callingId);
9079        }
9080    }
9081
9082    /**
9083     * @hide
9084     */
9085    @Override
9086    public int installExistingPackageAsUser(String packageName, int userId) {
9087        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9088                null);
9089        PackageSetting pkgSetting;
9090        final int uid = Binder.getCallingUid();
9091        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9092                + userId);
9093        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9094            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9095        }
9096
9097        long callingId = Binder.clearCallingIdentity();
9098        try {
9099            boolean sendAdded = false;
9100
9101            // writer
9102            synchronized (mPackages) {
9103                pkgSetting = mSettings.mPackages.get(packageName);
9104                if (pkgSetting == null) {
9105                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9106                }
9107                if (!pkgSetting.getInstalled(userId)) {
9108                    pkgSetting.setInstalled(true, userId);
9109                    pkgSetting.setHidden(false, userId);
9110                    mSettings.writePackageRestrictionsLPr(userId);
9111                    sendAdded = true;
9112                }
9113            }
9114
9115            if (sendAdded) {
9116                sendPackageAddedForUser(packageName, pkgSetting, userId);
9117            }
9118        } finally {
9119            Binder.restoreCallingIdentity(callingId);
9120        }
9121
9122        return PackageManager.INSTALL_SUCCEEDED;
9123    }
9124
9125    boolean isUserRestricted(int userId, String restrictionKey) {
9126        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9127        if (restrictions.getBoolean(restrictionKey, false)) {
9128            Log.w(TAG, "User is restricted: " + restrictionKey);
9129            return true;
9130        }
9131        return false;
9132    }
9133
9134    @Override
9135    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9136        mContext.enforceCallingOrSelfPermission(
9137                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9138                "Only package verification agents can verify applications");
9139
9140        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9141        final PackageVerificationResponse response = new PackageVerificationResponse(
9142                verificationCode, Binder.getCallingUid());
9143        msg.arg1 = id;
9144        msg.obj = response;
9145        mHandler.sendMessage(msg);
9146    }
9147
9148    @Override
9149    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9150            long millisecondsToDelay) {
9151        mContext.enforceCallingOrSelfPermission(
9152                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9153                "Only package verification agents can extend verification timeouts");
9154
9155        final PackageVerificationState state = mPendingVerification.get(id);
9156        final PackageVerificationResponse response = new PackageVerificationResponse(
9157                verificationCodeAtTimeout, Binder.getCallingUid());
9158
9159        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9160            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9161        }
9162        if (millisecondsToDelay < 0) {
9163            millisecondsToDelay = 0;
9164        }
9165        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9166                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9167            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9168        }
9169
9170        if ((state != null) && !state.timeoutExtended()) {
9171            state.extendTimeout();
9172
9173            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9174            msg.arg1 = id;
9175            msg.obj = response;
9176            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9177        }
9178    }
9179
9180    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9181            int verificationCode, UserHandle user) {
9182        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9183        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9184        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9185        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9186        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9187
9188        mContext.sendBroadcastAsUser(intent, user,
9189                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9190    }
9191
9192    private ComponentName matchComponentForVerifier(String packageName,
9193            List<ResolveInfo> receivers) {
9194        ActivityInfo targetReceiver = null;
9195
9196        final int NR = receivers.size();
9197        for (int i = 0; i < NR; i++) {
9198            final ResolveInfo info = receivers.get(i);
9199            if (info.activityInfo == null) {
9200                continue;
9201            }
9202
9203            if (packageName.equals(info.activityInfo.packageName)) {
9204                targetReceiver = info.activityInfo;
9205                break;
9206            }
9207        }
9208
9209        if (targetReceiver == null) {
9210            return null;
9211        }
9212
9213        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9214    }
9215
9216    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9217            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9218        if (pkgInfo.verifiers.length == 0) {
9219            return null;
9220        }
9221
9222        final int N = pkgInfo.verifiers.length;
9223        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9224        for (int i = 0; i < N; i++) {
9225            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9226
9227            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9228                    receivers);
9229            if (comp == null) {
9230                continue;
9231            }
9232
9233            final int verifierUid = getUidForVerifier(verifierInfo);
9234            if (verifierUid == -1) {
9235                continue;
9236            }
9237
9238            if (DEBUG_VERIFY) {
9239                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9240                        + " with the correct signature");
9241            }
9242            sufficientVerifiers.add(comp);
9243            verificationState.addSufficientVerifier(verifierUid);
9244        }
9245
9246        return sufficientVerifiers;
9247    }
9248
9249    private int getUidForVerifier(VerifierInfo verifierInfo) {
9250        synchronized (mPackages) {
9251            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9252            if (pkg == null) {
9253                return -1;
9254            } else if (pkg.mSignatures.length != 1) {
9255                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9256                        + " has more than one signature; ignoring");
9257                return -1;
9258            }
9259
9260            /*
9261             * If the public key of the package's signature does not match
9262             * our expected public key, then this is a different package and
9263             * we should skip.
9264             */
9265
9266            final byte[] expectedPublicKey;
9267            try {
9268                final Signature verifierSig = pkg.mSignatures[0];
9269                final PublicKey publicKey = verifierSig.getPublicKey();
9270                expectedPublicKey = publicKey.getEncoded();
9271            } catch (CertificateException e) {
9272                return -1;
9273            }
9274
9275            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9276
9277            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9278                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9279                        + " does not have the expected public key; ignoring");
9280                return -1;
9281            }
9282
9283            return pkg.applicationInfo.uid;
9284        }
9285    }
9286
9287    @Override
9288    public void finishPackageInstall(int token) {
9289        enforceSystemOrRoot("Only the system is allowed to finish installs");
9290
9291        if (DEBUG_INSTALL) {
9292            Slog.v(TAG, "BM finishing package install for " + token);
9293        }
9294
9295        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9296        mHandler.sendMessage(msg);
9297    }
9298
9299    /**
9300     * Get the verification agent timeout.
9301     *
9302     * @return verification timeout in milliseconds
9303     */
9304    private long getVerificationTimeout() {
9305        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9306                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9307                DEFAULT_VERIFICATION_TIMEOUT);
9308    }
9309
9310    /**
9311     * Get the default verification agent response code.
9312     *
9313     * @return default verification response code
9314     */
9315    private int getDefaultVerificationResponse() {
9316        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9317                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9318                DEFAULT_VERIFICATION_RESPONSE);
9319    }
9320
9321    /**
9322     * Check whether or not package verification has been enabled.
9323     *
9324     * @return true if verification should be performed
9325     */
9326    private boolean isVerificationEnabled(int userId, int installFlags) {
9327        if (!DEFAULT_VERIFY_ENABLE) {
9328            return false;
9329        }
9330
9331        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9332
9333        // Check if installing from ADB
9334        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9335            // Do not run verification in a test harness environment
9336            if (ActivityManager.isRunningInTestHarness()) {
9337                return false;
9338            }
9339            if (ensureVerifyAppsEnabled) {
9340                return true;
9341            }
9342            // Check if the developer does not want package verification for ADB installs
9343            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9344                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9345                return false;
9346            }
9347        }
9348
9349        if (ensureVerifyAppsEnabled) {
9350            return true;
9351        }
9352
9353        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9354                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9355    }
9356
9357    @Override
9358    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9359            throws RemoteException {
9360        mContext.enforceCallingOrSelfPermission(
9361                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9362                "Only intentfilter verification agents can verify applications");
9363
9364        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9365        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9366                Binder.getCallingUid(), verificationCode, failedDomains);
9367        msg.arg1 = id;
9368        msg.obj = response;
9369        mHandler.sendMessage(msg);
9370    }
9371
9372    @Override
9373    public int getIntentVerificationStatus(String packageName, int userId) {
9374        synchronized (mPackages) {
9375            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9376        }
9377    }
9378
9379    @Override
9380    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9381        boolean result = false;
9382        synchronized (mPackages) {
9383            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9384        }
9385        if (result) {
9386            scheduleWritePackageRestrictionsLocked(userId);
9387        }
9388        return result;
9389    }
9390
9391    @Override
9392    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9393        synchronized (mPackages) {
9394            return mSettings.getIntentFilterVerificationsLPr(packageName);
9395        }
9396    }
9397
9398    @Override
9399    public List<IntentFilter> getAllIntentFilters(String packageName) {
9400        if (TextUtils.isEmpty(packageName)) {
9401            return Collections.<IntentFilter>emptyList();
9402        }
9403        synchronized (mPackages) {
9404            PackageParser.Package pkg = mPackages.get(packageName);
9405            if (pkg == null || pkg.activities == null) {
9406                return Collections.<IntentFilter>emptyList();
9407            }
9408            final int count = pkg.activities.size();
9409            ArrayList<IntentFilter> result = new ArrayList<>();
9410            for (int n=0; n<count; n++) {
9411                PackageParser.Activity activity = pkg.activities.get(n);
9412                if (activity.intents != null || activity.intents.size() > 0) {
9413                    result.addAll(activity.intents);
9414                }
9415            }
9416            return result;
9417        }
9418    }
9419
9420    @Override
9421    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9422        synchronized (mPackages) {
9423            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9424            if (packageName != null) {
9425                result |= updateIntentVerificationStatus(packageName,
9426                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9427                        UserHandle.myUserId());
9428            }
9429            return result;
9430        }
9431    }
9432
9433    @Override
9434    public String getDefaultBrowserPackageName(int userId) {
9435        synchronized (mPackages) {
9436            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9437        }
9438    }
9439
9440    /**
9441     * Get the "allow unknown sources" setting.
9442     *
9443     * @return the current "allow unknown sources" setting
9444     */
9445    private int getUnknownSourcesSettings() {
9446        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9447                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9448                -1);
9449    }
9450
9451    @Override
9452    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9453        final int uid = Binder.getCallingUid();
9454        // writer
9455        synchronized (mPackages) {
9456            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9457            if (targetPackageSetting == null) {
9458                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9459            }
9460
9461            PackageSetting installerPackageSetting;
9462            if (installerPackageName != null) {
9463                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9464                if (installerPackageSetting == null) {
9465                    throw new IllegalArgumentException("Unknown installer package: "
9466                            + installerPackageName);
9467                }
9468            } else {
9469                installerPackageSetting = null;
9470            }
9471
9472            Signature[] callerSignature;
9473            Object obj = mSettings.getUserIdLPr(uid);
9474            if (obj != null) {
9475                if (obj instanceof SharedUserSetting) {
9476                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9477                } else if (obj instanceof PackageSetting) {
9478                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9479                } else {
9480                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9481                }
9482            } else {
9483                throw new SecurityException("Unknown calling uid " + uid);
9484            }
9485
9486            // Verify: can't set installerPackageName to a package that is
9487            // not signed with the same cert as the caller.
9488            if (installerPackageSetting != null) {
9489                if (compareSignatures(callerSignature,
9490                        installerPackageSetting.signatures.mSignatures)
9491                        != PackageManager.SIGNATURE_MATCH) {
9492                    throw new SecurityException(
9493                            "Caller does not have same cert as new installer package "
9494                            + installerPackageName);
9495                }
9496            }
9497
9498            // Verify: if target already has an installer package, it must
9499            // be signed with the same cert as the caller.
9500            if (targetPackageSetting.installerPackageName != null) {
9501                PackageSetting setting = mSettings.mPackages.get(
9502                        targetPackageSetting.installerPackageName);
9503                // If the currently set package isn't valid, then it's always
9504                // okay to change it.
9505                if (setting != null) {
9506                    if (compareSignatures(callerSignature,
9507                            setting.signatures.mSignatures)
9508                            != PackageManager.SIGNATURE_MATCH) {
9509                        throw new SecurityException(
9510                                "Caller does not have same cert as old installer package "
9511                                + targetPackageSetting.installerPackageName);
9512                    }
9513                }
9514            }
9515
9516            // Okay!
9517            targetPackageSetting.installerPackageName = installerPackageName;
9518            scheduleWriteSettingsLocked();
9519        }
9520    }
9521
9522    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9523        // Queue up an async operation since the package installation may take a little while.
9524        mHandler.post(new Runnable() {
9525            public void run() {
9526                mHandler.removeCallbacks(this);
9527                 // Result object to be returned
9528                PackageInstalledInfo res = new PackageInstalledInfo();
9529                res.returnCode = currentStatus;
9530                res.uid = -1;
9531                res.pkg = null;
9532                res.removedInfo = new PackageRemovedInfo();
9533                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9534                    args.doPreInstall(res.returnCode);
9535                    synchronized (mInstallLock) {
9536                        installPackageLI(args, res);
9537                    }
9538                    args.doPostInstall(res.returnCode, res.uid);
9539                }
9540
9541                // A restore should be performed at this point if (a) the install
9542                // succeeded, (b) the operation is not an update, and (c) the new
9543                // package has not opted out of backup participation.
9544                final boolean update = res.removedInfo.removedPackage != null;
9545                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9546                boolean doRestore = !update
9547                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9548
9549                // Set up the post-install work request bookkeeping.  This will be used
9550                // and cleaned up by the post-install event handling regardless of whether
9551                // there's a restore pass performed.  Token values are >= 1.
9552                int token;
9553                if (mNextInstallToken < 0) mNextInstallToken = 1;
9554                token = mNextInstallToken++;
9555
9556                PostInstallData data = new PostInstallData(args, res);
9557                mRunningInstalls.put(token, data);
9558                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9559
9560                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9561                    // Pass responsibility to the Backup Manager.  It will perform a
9562                    // restore if appropriate, then pass responsibility back to the
9563                    // Package Manager to run the post-install observer callbacks
9564                    // and broadcasts.
9565                    IBackupManager bm = IBackupManager.Stub.asInterface(
9566                            ServiceManager.getService(Context.BACKUP_SERVICE));
9567                    if (bm != null) {
9568                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9569                                + " to BM for possible restore");
9570                        try {
9571                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9572                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9573                            } else {
9574                                doRestore = false;
9575                            }
9576                        } catch (RemoteException e) {
9577                            // can't happen; the backup manager is local
9578                        } catch (Exception e) {
9579                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9580                            doRestore = false;
9581                        }
9582                    } else {
9583                        Slog.e(TAG, "Backup Manager not found!");
9584                        doRestore = false;
9585                    }
9586                }
9587
9588                if (!doRestore) {
9589                    // No restore possible, or the Backup Manager was mysteriously not
9590                    // available -- just fire the post-install work request directly.
9591                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9592                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9593                    mHandler.sendMessage(msg);
9594                }
9595            }
9596        });
9597    }
9598
9599    private abstract class HandlerParams {
9600        private static final int MAX_RETRIES = 4;
9601
9602        /**
9603         * Number of times startCopy() has been attempted and had a non-fatal
9604         * error.
9605         */
9606        private int mRetries = 0;
9607
9608        /** User handle for the user requesting the information or installation. */
9609        private final UserHandle mUser;
9610
9611        HandlerParams(UserHandle user) {
9612            mUser = user;
9613        }
9614
9615        UserHandle getUser() {
9616            return mUser;
9617        }
9618
9619        final boolean startCopy() {
9620            boolean res;
9621            try {
9622                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9623
9624                if (++mRetries > MAX_RETRIES) {
9625                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9626                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9627                    handleServiceError();
9628                    return false;
9629                } else {
9630                    handleStartCopy();
9631                    res = true;
9632                }
9633            } catch (RemoteException e) {
9634                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9635                mHandler.sendEmptyMessage(MCS_RECONNECT);
9636                res = false;
9637            }
9638            handleReturnCode();
9639            return res;
9640        }
9641
9642        final void serviceError() {
9643            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9644            handleServiceError();
9645            handleReturnCode();
9646        }
9647
9648        abstract void handleStartCopy() throws RemoteException;
9649        abstract void handleServiceError();
9650        abstract void handleReturnCode();
9651    }
9652
9653    class MeasureParams extends HandlerParams {
9654        private final PackageStats mStats;
9655        private boolean mSuccess;
9656
9657        private final IPackageStatsObserver mObserver;
9658
9659        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9660            super(new UserHandle(stats.userHandle));
9661            mObserver = observer;
9662            mStats = stats;
9663        }
9664
9665        @Override
9666        public String toString() {
9667            return "MeasureParams{"
9668                + Integer.toHexString(System.identityHashCode(this))
9669                + " " + mStats.packageName + "}";
9670        }
9671
9672        @Override
9673        void handleStartCopy() throws RemoteException {
9674            synchronized (mInstallLock) {
9675                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9676            }
9677
9678            if (mSuccess) {
9679                final boolean mounted;
9680                if (Environment.isExternalStorageEmulated()) {
9681                    mounted = true;
9682                } else {
9683                    final String status = Environment.getExternalStorageState();
9684                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9685                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9686                }
9687
9688                if (mounted) {
9689                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9690
9691                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9692                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9693
9694                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9695                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9696
9697                    // Always subtract cache size, since it's a subdirectory
9698                    mStats.externalDataSize -= mStats.externalCacheSize;
9699
9700                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9701                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9702
9703                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9704                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9705                }
9706            }
9707        }
9708
9709        @Override
9710        void handleReturnCode() {
9711            if (mObserver != null) {
9712                try {
9713                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9714                } catch (RemoteException e) {
9715                    Slog.i(TAG, "Observer no longer exists.");
9716                }
9717            }
9718        }
9719
9720        @Override
9721        void handleServiceError() {
9722            Slog.e(TAG, "Could not measure application " + mStats.packageName
9723                            + " external storage");
9724        }
9725    }
9726
9727    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9728            throws RemoteException {
9729        long result = 0;
9730        for (File path : paths) {
9731            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9732        }
9733        return result;
9734    }
9735
9736    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9737        for (File path : paths) {
9738            try {
9739                mcs.clearDirectory(path.getAbsolutePath());
9740            } catch (RemoteException e) {
9741            }
9742        }
9743    }
9744
9745    static class OriginInfo {
9746        /**
9747         * Location where install is coming from, before it has been
9748         * copied/renamed into place. This could be a single monolithic APK
9749         * file, or a cluster directory. This location may be untrusted.
9750         */
9751        final File file;
9752        final String cid;
9753
9754        /**
9755         * Flag indicating that {@link #file} or {@link #cid} has already been
9756         * staged, meaning downstream users don't need to defensively copy the
9757         * contents.
9758         */
9759        final boolean staged;
9760
9761        /**
9762         * Flag indicating that {@link #file} or {@link #cid} is an already
9763         * installed app that is being moved.
9764         */
9765        final boolean existing;
9766
9767        final String resolvedPath;
9768        final File resolvedFile;
9769
9770        static OriginInfo fromNothing() {
9771            return new OriginInfo(null, null, false, false);
9772        }
9773
9774        static OriginInfo fromUntrustedFile(File file) {
9775            return new OriginInfo(file, null, false, false);
9776        }
9777
9778        static OriginInfo fromExistingFile(File file) {
9779            return new OriginInfo(file, null, false, true);
9780        }
9781
9782        static OriginInfo fromStagedFile(File file) {
9783            return new OriginInfo(file, null, true, false);
9784        }
9785
9786        static OriginInfo fromStagedContainer(String cid) {
9787            return new OriginInfo(null, cid, true, false);
9788        }
9789
9790        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9791            this.file = file;
9792            this.cid = cid;
9793            this.staged = staged;
9794            this.existing = existing;
9795
9796            if (cid != null) {
9797                resolvedPath = PackageHelper.getSdDir(cid);
9798                resolvedFile = new File(resolvedPath);
9799            } else if (file != null) {
9800                resolvedPath = file.getAbsolutePath();
9801                resolvedFile = file;
9802            } else {
9803                resolvedPath = null;
9804                resolvedFile = null;
9805            }
9806        }
9807    }
9808
9809    class MoveInfo {
9810        final int moveId;
9811        final String fromUuid;
9812        final String toUuid;
9813        final String packageName;
9814        final String dataAppName;
9815        final int appId;
9816        final String seinfo;
9817
9818        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9819                String dataAppName, int appId, String seinfo) {
9820            this.moveId = moveId;
9821            this.fromUuid = fromUuid;
9822            this.toUuid = toUuid;
9823            this.packageName = packageName;
9824            this.dataAppName = dataAppName;
9825            this.appId = appId;
9826            this.seinfo = seinfo;
9827        }
9828    }
9829
9830    class InstallParams extends HandlerParams {
9831        final OriginInfo origin;
9832        final MoveInfo move;
9833        final IPackageInstallObserver2 observer;
9834        int installFlags;
9835        final String installerPackageName;
9836        final String volumeUuid;
9837        final VerificationParams verificationParams;
9838        private InstallArgs mArgs;
9839        private int mRet;
9840        final String packageAbiOverride;
9841
9842        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
9843                int installFlags, String installerPackageName, String volumeUuid,
9844                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9845            super(user);
9846            this.origin = origin;
9847            this.move = move;
9848            this.observer = observer;
9849            this.installFlags = installFlags;
9850            this.installerPackageName = installerPackageName;
9851            this.volumeUuid = volumeUuid;
9852            this.verificationParams = verificationParams;
9853            this.packageAbiOverride = packageAbiOverride;
9854        }
9855
9856        @Override
9857        public String toString() {
9858            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9859                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9860        }
9861
9862        public ManifestDigest getManifestDigest() {
9863            if (verificationParams == null) {
9864                return null;
9865            }
9866            return verificationParams.getManifestDigest();
9867        }
9868
9869        private int installLocationPolicy(PackageInfoLite pkgLite) {
9870            String packageName = pkgLite.packageName;
9871            int installLocation = pkgLite.installLocation;
9872            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9873            // reader
9874            synchronized (mPackages) {
9875                PackageParser.Package pkg = mPackages.get(packageName);
9876                if (pkg != null) {
9877                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9878                        // Check for downgrading.
9879                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9880                            try {
9881                                checkDowngrade(pkg, pkgLite);
9882                            } catch (PackageManagerException e) {
9883                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9884                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9885                            }
9886                        }
9887                        // Check for updated system application.
9888                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9889                            if (onSd) {
9890                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9891                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9892                            }
9893                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9894                        } else {
9895                            if (onSd) {
9896                                // Install flag overrides everything.
9897                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9898                            }
9899                            // If current upgrade specifies particular preference
9900                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9901                                // Application explicitly specified internal.
9902                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9903                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9904                                // App explictly prefers external. Let policy decide
9905                            } else {
9906                                // Prefer previous location
9907                                if (isExternal(pkg)) {
9908                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9909                                }
9910                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9911                            }
9912                        }
9913                    } else {
9914                        // Invalid install. Return error code
9915                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9916                    }
9917                }
9918            }
9919            // All the special cases have been taken care of.
9920            // Return result based on recommended install location.
9921            if (onSd) {
9922                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9923            }
9924            return pkgLite.recommendedInstallLocation;
9925        }
9926
9927        /*
9928         * Invoke remote method to get package information and install
9929         * location values. Override install location based on default
9930         * policy if needed and then create install arguments based
9931         * on the install location.
9932         */
9933        public void handleStartCopy() throws RemoteException {
9934            int ret = PackageManager.INSTALL_SUCCEEDED;
9935
9936            // If we're already staged, we've firmly committed to an install location
9937            if (origin.staged) {
9938                if (origin.file != null) {
9939                    installFlags |= PackageManager.INSTALL_INTERNAL;
9940                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9941                } else if (origin.cid != null) {
9942                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9943                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9944                } else {
9945                    throw new IllegalStateException("Invalid stage location");
9946                }
9947            }
9948
9949            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9950            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9951
9952            PackageInfoLite pkgLite = null;
9953
9954            if (onInt && onSd) {
9955                // Check if both bits are set.
9956                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9957                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9958            } else {
9959                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9960                        packageAbiOverride);
9961
9962                /*
9963                 * If we have too little free space, try to free cache
9964                 * before giving up.
9965                 */
9966                if (!origin.staged && pkgLite.recommendedInstallLocation
9967                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9968                    // TODO: focus freeing disk space on the target device
9969                    final StorageManager storage = StorageManager.from(mContext);
9970                    final long lowThreshold = storage.getStorageLowBytes(
9971                            Environment.getDataDirectory());
9972
9973                    final long sizeBytes = mContainerService.calculateInstalledSize(
9974                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9975
9976                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
9977                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9978                                installFlags, packageAbiOverride);
9979                    }
9980
9981                    /*
9982                     * The cache free must have deleted the file we
9983                     * downloaded to install.
9984                     *
9985                     * TODO: fix the "freeCache" call to not delete
9986                     *       the file we care about.
9987                     */
9988                    if (pkgLite.recommendedInstallLocation
9989                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9990                        pkgLite.recommendedInstallLocation
9991                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9992                    }
9993                }
9994            }
9995
9996            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9997                int loc = pkgLite.recommendedInstallLocation;
9998                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9999                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10000                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10001                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10002                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10003                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10004                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10005                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10006                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10007                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10008                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10009                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10010                } else {
10011                    // Override with defaults if needed.
10012                    loc = installLocationPolicy(pkgLite);
10013                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10014                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10015                    } else if (!onSd && !onInt) {
10016                        // Override install location with flags
10017                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10018                            // Set the flag to install on external media.
10019                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10020                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10021                        } else {
10022                            // Make sure the flag for installing on external
10023                            // media is unset
10024                            installFlags |= PackageManager.INSTALL_INTERNAL;
10025                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10026                        }
10027                    }
10028                }
10029            }
10030
10031            final InstallArgs args = createInstallArgs(this);
10032            mArgs = args;
10033
10034            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10035                 /*
10036                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10037                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10038                 */
10039                int userIdentifier = getUser().getIdentifier();
10040                if (userIdentifier == UserHandle.USER_ALL
10041                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10042                    userIdentifier = UserHandle.USER_OWNER;
10043                }
10044
10045                /*
10046                 * Determine if we have any installed package verifiers. If we
10047                 * do, then we'll defer to them to verify the packages.
10048                 */
10049                final int requiredUid = mRequiredVerifierPackage == null ? -1
10050                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10051                if (!origin.existing && requiredUid != -1
10052                        && isVerificationEnabled(userIdentifier, installFlags)) {
10053                    final Intent verification = new Intent(
10054                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10055                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10056                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10057                            PACKAGE_MIME_TYPE);
10058                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10059
10060                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10061                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10062                            0 /* TODO: Which userId? */);
10063
10064                    if (DEBUG_VERIFY) {
10065                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10066                                + verification.toString() + " with " + pkgLite.verifiers.length
10067                                + " optional verifiers");
10068                    }
10069
10070                    final int verificationId = mPendingVerificationToken++;
10071
10072                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10073
10074                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10075                            installerPackageName);
10076
10077                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10078                            installFlags);
10079
10080                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10081                            pkgLite.packageName);
10082
10083                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10084                            pkgLite.versionCode);
10085
10086                    if (verificationParams != null) {
10087                        if (verificationParams.getVerificationURI() != null) {
10088                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10089                                 verificationParams.getVerificationURI());
10090                        }
10091                        if (verificationParams.getOriginatingURI() != null) {
10092                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10093                                  verificationParams.getOriginatingURI());
10094                        }
10095                        if (verificationParams.getReferrer() != null) {
10096                            verification.putExtra(Intent.EXTRA_REFERRER,
10097                                  verificationParams.getReferrer());
10098                        }
10099                        if (verificationParams.getOriginatingUid() >= 0) {
10100                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10101                                  verificationParams.getOriginatingUid());
10102                        }
10103                        if (verificationParams.getInstallerUid() >= 0) {
10104                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10105                                  verificationParams.getInstallerUid());
10106                        }
10107                    }
10108
10109                    final PackageVerificationState verificationState = new PackageVerificationState(
10110                            requiredUid, args);
10111
10112                    mPendingVerification.append(verificationId, verificationState);
10113
10114                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10115                            receivers, verificationState);
10116
10117                    /*
10118                     * If any sufficient verifiers were listed in the package
10119                     * manifest, attempt to ask them.
10120                     */
10121                    if (sufficientVerifiers != null) {
10122                        final int N = sufficientVerifiers.size();
10123                        if (N == 0) {
10124                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10125                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10126                        } else {
10127                            for (int i = 0; i < N; i++) {
10128                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10129
10130                                final Intent sufficientIntent = new Intent(verification);
10131                                sufficientIntent.setComponent(verifierComponent);
10132
10133                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10134                            }
10135                        }
10136                    }
10137
10138                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10139                            mRequiredVerifierPackage, receivers);
10140                    if (ret == PackageManager.INSTALL_SUCCEEDED
10141                            && mRequiredVerifierPackage != null) {
10142                        /*
10143                         * Send the intent to the required verification agent,
10144                         * but only start the verification timeout after the
10145                         * target BroadcastReceivers have run.
10146                         */
10147                        verification.setComponent(requiredVerifierComponent);
10148                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10149                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10150                                new BroadcastReceiver() {
10151                                    @Override
10152                                    public void onReceive(Context context, Intent intent) {
10153                                        final Message msg = mHandler
10154                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10155                                        msg.arg1 = verificationId;
10156                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10157                                    }
10158                                }, null, 0, null, null);
10159
10160                        /*
10161                         * We don't want the copy to proceed until verification
10162                         * succeeds, so null out this field.
10163                         */
10164                        mArgs = null;
10165                    }
10166                } else {
10167                    /*
10168                     * No package verification is enabled, so immediately start
10169                     * the remote call to initiate copy using temporary file.
10170                     */
10171                    ret = args.copyApk(mContainerService, true);
10172                }
10173            }
10174
10175            mRet = ret;
10176        }
10177
10178        @Override
10179        void handleReturnCode() {
10180            // If mArgs is null, then MCS couldn't be reached. When it
10181            // reconnects, it will try again to install. At that point, this
10182            // will succeed.
10183            if (mArgs != null) {
10184                processPendingInstall(mArgs, mRet);
10185            }
10186        }
10187
10188        @Override
10189        void handleServiceError() {
10190            mArgs = createInstallArgs(this);
10191            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10192        }
10193
10194        public boolean isForwardLocked() {
10195            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10196        }
10197    }
10198
10199    /**
10200     * Used during creation of InstallArgs
10201     *
10202     * @param installFlags package installation flags
10203     * @return true if should be installed on external storage
10204     */
10205    private static boolean installOnExternalAsec(int installFlags) {
10206        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10207            return false;
10208        }
10209        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10210            return true;
10211        }
10212        return false;
10213    }
10214
10215    /**
10216     * Used during creation of InstallArgs
10217     *
10218     * @param installFlags package installation flags
10219     * @return true if should be installed as forward locked
10220     */
10221    private static boolean installForwardLocked(int installFlags) {
10222        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10223    }
10224
10225    private InstallArgs createInstallArgs(InstallParams params) {
10226        if (params.move != null) {
10227            return new MoveInstallArgs(params);
10228        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10229            return new AsecInstallArgs(params);
10230        } else {
10231            return new FileInstallArgs(params);
10232        }
10233    }
10234
10235    /**
10236     * Create args that describe an existing installed package. Typically used
10237     * when cleaning up old installs, or used as a move source.
10238     */
10239    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10240            String resourcePath, String[] instructionSets) {
10241        final boolean isInAsec;
10242        if (installOnExternalAsec(installFlags)) {
10243            /* Apps on SD card are always in ASEC containers. */
10244            isInAsec = true;
10245        } else if (installForwardLocked(installFlags)
10246                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10247            /*
10248             * Forward-locked apps are only in ASEC containers if they're the
10249             * new style
10250             */
10251            isInAsec = true;
10252        } else {
10253            isInAsec = false;
10254        }
10255
10256        if (isInAsec) {
10257            return new AsecInstallArgs(codePath, instructionSets,
10258                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10259        } else {
10260            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10261        }
10262    }
10263
10264    static abstract class InstallArgs {
10265        /** @see InstallParams#origin */
10266        final OriginInfo origin;
10267        /** @see InstallParams#move */
10268        final MoveInfo move;
10269
10270        final IPackageInstallObserver2 observer;
10271        // Always refers to PackageManager flags only
10272        final int installFlags;
10273        final String installerPackageName;
10274        final String volumeUuid;
10275        final ManifestDigest manifestDigest;
10276        final UserHandle user;
10277        final String abiOverride;
10278
10279        // The list of instruction sets supported by this app. This is currently
10280        // only used during the rmdex() phase to clean up resources. We can get rid of this
10281        // if we move dex files under the common app path.
10282        /* nullable */ String[] instructionSets;
10283
10284        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10285                int installFlags, String installerPackageName, String volumeUuid,
10286                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10287                String abiOverride) {
10288            this.origin = origin;
10289            this.move = move;
10290            this.installFlags = installFlags;
10291            this.observer = observer;
10292            this.installerPackageName = installerPackageName;
10293            this.volumeUuid = volumeUuid;
10294            this.manifestDigest = manifestDigest;
10295            this.user = user;
10296            this.instructionSets = instructionSets;
10297            this.abiOverride = abiOverride;
10298        }
10299
10300        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10301        abstract int doPreInstall(int status);
10302
10303        /**
10304         * Rename package into final resting place. All paths on the given
10305         * scanned package should be updated to reflect the rename.
10306         */
10307        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10308        abstract int doPostInstall(int status, int uid);
10309
10310        /** @see PackageSettingBase#codePathString */
10311        abstract String getCodePath();
10312        /** @see PackageSettingBase#resourcePathString */
10313        abstract String getResourcePath();
10314
10315        // Need installer lock especially for dex file removal.
10316        abstract void cleanUpResourcesLI();
10317        abstract boolean doPostDeleteLI(boolean delete);
10318
10319        /**
10320         * Called before the source arguments are copied. This is used mostly
10321         * for MoveParams when it needs to read the source file to put it in the
10322         * destination.
10323         */
10324        int doPreCopy() {
10325            return PackageManager.INSTALL_SUCCEEDED;
10326        }
10327
10328        /**
10329         * Called after the source arguments are copied. This is used mostly for
10330         * MoveParams when it needs to read the source file to put it in the
10331         * destination.
10332         *
10333         * @return
10334         */
10335        int doPostCopy(int uid) {
10336            return PackageManager.INSTALL_SUCCEEDED;
10337        }
10338
10339        protected boolean isFwdLocked() {
10340            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10341        }
10342
10343        protected boolean isExternalAsec() {
10344            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10345        }
10346
10347        UserHandle getUser() {
10348            return user;
10349        }
10350    }
10351
10352    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10353        if (!allCodePaths.isEmpty()) {
10354            if (instructionSets == null) {
10355                throw new IllegalStateException("instructionSet == null");
10356            }
10357            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10358            for (String codePath : allCodePaths) {
10359                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10360                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10361                    if (retCode < 0) {
10362                        Slog.w(TAG, "Couldn't remove dex file for package: "
10363                                + " at location " + codePath + ", retcode=" + retCode);
10364                        // we don't consider this to be a failure of the core package deletion
10365                    }
10366                }
10367            }
10368        }
10369    }
10370
10371    /**
10372     * Logic to handle installation of non-ASEC applications, including copying
10373     * and renaming logic.
10374     */
10375    class FileInstallArgs extends InstallArgs {
10376        private File codeFile;
10377        private File resourceFile;
10378
10379        // Example topology:
10380        // /data/app/com.example/base.apk
10381        // /data/app/com.example/split_foo.apk
10382        // /data/app/com.example/lib/arm/libfoo.so
10383        // /data/app/com.example/lib/arm64/libfoo.so
10384        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10385
10386        /** New install */
10387        FileInstallArgs(InstallParams params) {
10388            super(params.origin, params.move, params.observer, params.installFlags,
10389                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10390                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10391            if (isFwdLocked()) {
10392                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10393            }
10394        }
10395
10396        /** Existing install */
10397        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10398            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10399                    null);
10400            this.codeFile = (codePath != null) ? new File(codePath) : null;
10401            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10402        }
10403
10404        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10405            if (origin.staged) {
10406                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10407                codeFile = origin.file;
10408                resourceFile = origin.file;
10409                return PackageManager.INSTALL_SUCCEEDED;
10410            }
10411
10412            try {
10413                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10414                codeFile = tempDir;
10415                resourceFile = tempDir;
10416            } catch (IOException e) {
10417                Slog.w(TAG, "Failed to create copy file: " + e);
10418                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10419            }
10420
10421            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10422                @Override
10423                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10424                    if (!FileUtils.isValidExtFilename(name)) {
10425                        throw new IllegalArgumentException("Invalid filename: " + name);
10426                    }
10427                    try {
10428                        final File file = new File(codeFile, name);
10429                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10430                                O_RDWR | O_CREAT, 0644);
10431                        Os.chmod(file.getAbsolutePath(), 0644);
10432                        return new ParcelFileDescriptor(fd);
10433                    } catch (ErrnoException e) {
10434                        throw new RemoteException("Failed to open: " + e.getMessage());
10435                    }
10436                }
10437            };
10438
10439            int ret = PackageManager.INSTALL_SUCCEEDED;
10440            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10441            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10442                Slog.e(TAG, "Failed to copy package");
10443                return ret;
10444            }
10445
10446            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10447            NativeLibraryHelper.Handle handle = null;
10448            try {
10449                handle = NativeLibraryHelper.Handle.create(codeFile);
10450                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10451                        abiOverride);
10452            } catch (IOException e) {
10453                Slog.e(TAG, "Copying native libraries failed", e);
10454                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10455            } finally {
10456                IoUtils.closeQuietly(handle);
10457            }
10458
10459            return ret;
10460        }
10461
10462        int doPreInstall(int status) {
10463            if (status != PackageManager.INSTALL_SUCCEEDED) {
10464                cleanUp();
10465            }
10466            return status;
10467        }
10468
10469        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10470            if (status != PackageManager.INSTALL_SUCCEEDED) {
10471                cleanUp();
10472                return false;
10473            }
10474
10475            final File targetDir = codeFile.getParentFile();
10476            final File beforeCodeFile = codeFile;
10477            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10478
10479            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10480            try {
10481                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10482            } catch (ErrnoException e) {
10483                Slog.w(TAG, "Failed to rename", e);
10484                return false;
10485            }
10486
10487            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10488                Slog.w(TAG, "Failed to restorecon");
10489                return false;
10490            }
10491
10492            // Reflect the rename internally
10493            codeFile = afterCodeFile;
10494            resourceFile = afterCodeFile;
10495
10496            // Reflect the rename in scanned details
10497            pkg.codePath = afterCodeFile.getAbsolutePath();
10498            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10499                    pkg.baseCodePath);
10500            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10501                    pkg.splitCodePaths);
10502
10503            // Reflect the rename in app info
10504            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10505            pkg.applicationInfo.setCodePath(pkg.codePath);
10506            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10507            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10508            pkg.applicationInfo.setResourcePath(pkg.codePath);
10509            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10510            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10511
10512            return true;
10513        }
10514
10515        int doPostInstall(int status, int uid) {
10516            if (status != PackageManager.INSTALL_SUCCEEDED) {
10517                cleanUp();
10518            }
10519            return status;
10520        }
10521
10522        @Override
10523        String getCodePath() {
10524            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10525        }
10526
10527        @Override
10528        String getResourcePath() {
10529            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10530        }
10531
10532        private boolean cleanUp() {
10533            if (codeFile == null || !codeFile.exists()) {
10534                return false;
10535            }
10536
10537            if (codeFile.isDirectory()) {
10538                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10539            } else {
10540                codeFile.delete();
10541            }
10542
10543            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10544                resourceFile.delete();
10545            }
10546
10547            return true;
10548        }
10549
10550        void cleanUpResourcesLI() {
10551            // Try enumerating all code paths before deleting
10552            List<String> allCodePaths = Collections.EMPTY_LIST;
10553            if (codeFile != null && codeFile.exists()) {
10554                try {
10555                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10556                    allCodePaths = pkg.getAllCodePaths();
10557                } catch (PackageParserException e) {
10558                    // Ignored; we tried our best
10559                }
10560            }
10561
10562            cleanUp();
10563            removeDexFiles(allCodePaths, instructionSets);
10564        }
10565
10566        boolean doPostDeleteLI(boolean delete) {
10567            // XXX err, shouldn't we respect the delete flag?
10568            cleanUpResourcesLI();
10569            return true;
10570        }
10571    }
10572
10573    private boolean isAsecExternal(String cid) {
10574        final String asecPath = PackageHelper.getSdFilesystem(cid);
10575        return !asecPath.startsWith(mAsecInternalPath);
10576    }
10577
10578    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10579            PackageManagerException {
10580        if (copyRet < 0) {
10581            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10582                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10583                throw new PackageManagerException(copyRet, message);
10584            }
10585        }
10586    }
10587
10588    /**
10589     * Extract the MountService "container ID" from the full code path of an
10590     * .apk.
10591     */
10592    static String cidFromCodePath(String fullCodePath) {
10593        int eidx = fullCodePath.lastIndexOf("/");
10594        String subStr1 = fullCodePath.substring(0, eidx);
10595        int sidx = subStr1.lastIndexOf("/");
10596        return subStr1.substring(sidx+1, eidx);
10597    }
10598
10599    /**
10600     * Logic to handle installation of ASEC applications, including copying and
10601     * renaming logic.
10602     */
10603    class AsecInstallArgs extends InstallArgs {
10604        static final String RES_FILE_NAME = "pkg.apk";
10605        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10606
10607        String cid;
10608        String packagePath;
10609        String resourcePath;
10610
10611        /** New install */
10612        AsecInstallArgs(InstallParams params) {
10613            super(params.origin, params.move, params.observer, params.installFlags,
10614                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10615                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10616        }
10617
10618        /** Existing install */
10619        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10620                        boolean isExternal, boolean isForwardLocked) {
10621            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10622                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10623                    instructionSets, null);
10624            // Hackily pretend we're still looking at a full code path
10625            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10626                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10627            }
10628
10629            // Extract cid from fullCodePath
10630            int eidx = fullCodePath.lastIndexOf("/");
10631            String subStr1 = fullCodePath.substring(0, eidx);
10632            int sidx = subStr1.lastIndexOf("/");
10633            cid = subStr1.substring(sidx+1, eidx);
10634            setMountPath(subStr1);
10635        }
10636
10637        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10638            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10639                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10640                    instructionSets, null);
10641            this.cid = cid;
10642            setMountPath(PackageHelper.getSdDir(cid));
10643        }
10644
10645        void createCopyFile() {
10646            cid = mInstallerService.allocateExternalStageCidLegacy();
10647        }
10648
10649        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10650            if (origin.staged) {
10651                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
10652                cid = origin.cid;
10653                setMountPath(PackageHelper.getSdDir(cid));
10654                return PackageManager.INSTALL_SUCCEEDED;
10655            }
10656
10657            if (temp) {
10658                createCopyFile();
10659            } else {
10660                /*
10661                 * Pre-emptively destroy the container since it's destroyed if
10662                 * copying fails due to it existing anyway.
10663                 */
10664                PackageHelper.destroySdDir(cid);
10665            }
10666
10667            final String newMountPath = imcs.copyPackageToContainer(
10668                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10669                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10670
10671            if (newMountPath != null) {
10672                setMountPath(newMountPath);
10673                return PackageManager.INSTALL_SUCCEEDED;
10674            } else {
10675                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10676            }
10677        }
10678
10679        @Override
10680        String getCodePath() {
10681            return packagePath;
10682        }
10683
10684        @Override
10685        String getResourcePath() {
10686            return resourcePath;
10687        }
10688
10689        int doPreInstall(int status) {
10690            if (status != PackageManager.INSTALL_SUCCEEDED) {
10691                // Destroy container
10692                PackageHelper.destroySdDir(cid);
10693            } else {
10694                boolean mounted = PackageHelper.isContainerMounted(cid);
10695                if (!mounted) {
10696                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10697                            Process.SYSTEM_UID);
10698                    if (newMountPath != null) {
10699                        setMountPath(newMountPath);
10700                    } else {
10701                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10702                    }
10703                }
10704            }
10705            return status;
10706        }
10707
10708        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10709            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10710            String newMountPath = null;
10711            if (PackageHelper.isContainerMounted(cid)) {
10712                // Unmount the container
10713                if (!PackageHelper.unMountSdDir(cid)) {
10714                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10715                    return false;
10716                }
10717            }
10718            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10719                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10720                        " which might be stale. Will try to clean up.");
10721                // Clean up the stale container and proceed to recreate.
10722                if (!PackageHelper.destroySdDir(newCacheId)) {
10723                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10724                    return false;
10725                }
10726                // Successfully cleaned up stale container. Try to rename again.
10727                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10728                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10729                            + " inspite of cleaning it up.");
10730                    return false;
10731                }
10732            }
10733            if (!PackageHelper.isContainerMounted(newCacheId)) {
10734                Slog.w(TAG, "Mounting container " + newCacheId);
10735                newMountPath = PackageHelper.mountSdDir(newCacheId,
10736                        getEncryptKey(), Process.SYSTEM_UID);
10737            } else {
10738                newMountPath = PackageHelper.getSdDir(newCacheId);
10739            }
10740            if (newMountPath == null) {
10741                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10742                return false;
10743            }
10744            Log.i(TAG, "Succesfully renamed " + cid +
10745                    " to " + newCacheId +
10746                    " at new path: " + newMountPath);
10747            cid = newCacheId;
10748
10749            final File beforeCodeFile = new File(packagePath);
10750            setMountPath(newMountPath);
10751            final File afterCodeFile = new File(packagePath);
10752
10753            // Reflect the rename in scanned details
10754            pkg.codePath = afterCodeFile.getAbsolutePath();
10755            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10756                    pkg.baseCodePath);
10757            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10758                    pkg.splitCodePaths);
10759
10760            // Reflect the rename in app info
10761            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10762            pkg.applicationInfo.setCodePath(pkg.codePath);
10763            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10764            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10765            pkg.applicationInfo.setResourcePath(pkg.codePath);
10766            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10767            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10768
10769            return true;
10770        }
10771
10772        private void setMountPath(String mountPath) {
10773            final File mountFile = new File(mountPath);
10774
10775            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10776            if (monolithicFile.exists()) {
10777                packagePath = monolithicFile.getAbsolutePath();
10778                if (isFwdLocked()) {
10779                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10780                } else {
10781                    resourcePath = packagePath;
10782                }
10783            } else {
10784                packagePath = mountFile.getAbsolutePath();
10785                resourcePath = packagePath;
10786            }
10787        }
10788
10789        int doPostInstall(int status, int uid) {
10790            if (status != PackageManager.INSTALL_SUCCEEDED) {
10791                cleanUp();
10792            } else {
10793                final int groupOwner;
10794                final String protectedFile;
10795                if (isFwdLocked()) {
10796                    groupOwner = UserHandle.getSharedAppGid(uid);
10797                    protectedFile = RES_FILE_NAME;
10798                } else {
10799                    groupOwner = -1;
10800                    protectedFile = null;
10801                }
10802
10803                if (uid < Process.FIRST_APPLICATION_UID
10804                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10805                    Slog.e(TAG, "Failed to finalize " + cid);
10806                    PackageHelper.destroySdDir(cid);
10807                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10808                }
10809
10810                boolean mounted = PackageHelper.isContainerMounted(cid);
10811                if (!mounted) {
10812                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10813                }
10814            }
10815            return status;
10816        }
10817
10818        private void cleanUp() {
10819            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10820
10821            // Destroy secure container
10822            PackageHelper.destroySdDir(cid);
10823        }
10824
10825        private List<String> getAllCodePaths() {
10826            final File codeFile = new File(getCodePath());
10827            if (codeFile != null && codeFile.exists()) {
10828                try {
10829                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10830                    return pkg.getAllCodePaths();
10831                } catch (PackageParserException e) {
10832                    // Ignored; we tried our best
10833                }
10834            }
10835            return Collections.EMPTY_LIST;
10836        }
10837
10838        void cleanUpResourcesLI() {
10839            // Enumerate all code paths before deleting
10840            cleanUpResourcesLI(getAllCodePaths());
10841        }
10842
10843        private void cleanUpResourcesLI(List<String> allCodePaths) {
10844            cleanUp();
10845            removeDexFiles(allCodePaths, instructionSets);
10846        }
10847
10848        String getPackageName() {
10849            return getAsecPackageName(cid);
10850        }
10851
10852        boolean doPostDeleteLI(boolean delete) {
10853            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10854            final List<String> allCodePaths = getAllCodePaths();
10855            boolean mounted = PackageHelper.isContainerMounted(cid);
10856            if (mounted) {
10857                // Unmount first
10858                if (PackageHelper.unMountSdDir(cid)) {
10859                    mounted = false;
10860                }
10861            }
10862            if (!mounted && delete) {
10863                cleanUpResourcesLI(allCodePaths);
10864            }
10865            return !mounted;
10866        }
10867
10868        @Override
10869        int doPreCopy() {
10870            if (isFwdLocked()) {
10871                if (!PackageHelper.fixSdPermissions(cid,
10872                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10873                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10874                }
10875            }
10876
10877            return PackageManager.INSTALL_SUCCEEDED;
10878        }
10879
10880        @Override
10881        int doPostCopy(int uid) {
10882            if (isFwdLocked()) {
10883                if (uid < Process.FIRST_APPLICATION_UID
10884                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10885                                RES_FILE_NAME)) {
10886                    Slog.e(TAG, "Failed to finalize " + cid);
10887                    PackageHelper.destroySdDir(cid);
10888                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10889                }
10890            }
10891
10892            return PackageManager.INSTALL_SUCCEEDED;
10893        }
10894    }
10895
10896    /**
10897     * Logic to handle movement of existing installed applications.
10898     */
10899    class MoveInstallArgs extends InstallArgs {
10900        private File codeFile;
10901        private File resourceFile;
10902
10903        /** New install */
10904        MoveInstallArgs(InstallParams params) {
10905            super(params.origin, params.move, params.observer, params.installFlags,
10906                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10907                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10908        }
10909
10910        int copyApk(IMediaContainerService imcs, boolean temp) {
10911            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
10912                    + move.fromUuid + " to " + move.toUuid);
10913            synchronized (mInstaller) {
10914                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
10915                        move.dataAppName, move.appId, move.seinfo) != 0) {
10916                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10917                }
10918            }
10919
10920            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
10921            resourceFile = codeFile;
10922            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
10923
10924            return PackageManager.INSTALL_SUCCEEDED;
10925        }
10926
10927        int doPreInstall(int status) {
10928            if (status != PackageManager.INSTALL_SUCCEEDED) {
10929                cleanUp();
10930            }
10931            return status;
10932        }
10933
10934        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10935            if (status != PackageManager.INSTALL_SUCCEEDED) {
10936                cleanUp();
10937                return false;
10938            }
10939
10940            // Reflect the move in app info
10941            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10942            pkg.applicationInfo.setCodePath(pkg.codePath);
10943            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10944            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10945            pkg.applicationInfo.setResourcePath(pkg.codePath);
10946            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10947            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10948
10949            return true;
10950        }
10951
10952        int doPostInstall(int status, int uid) {
10953            if (status != PackageManager.INSTALL_SUCCEEDED) {
10954                cleanUp();
10955            }
10956            return status;
10957        }
10958
10959        @Override
10960        String getCodePath() {
10961            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10962        }
10963
10964        @Override
10965        String getResourcePath() {
10966            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10967        }
10968
10969        private boolean cleanUp() {
10970            if (codeFile == null || !codeFile.exists()) {
10971                return false;
10972            }
10973
10974            if (codeFile.isDirectory()) {
10975                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10976            } else {
10977                codeFile.delete();
10978            }
10979
10980            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10981                resourceFile.delete();
10982            }
10983
10984            return true;
10985        }
10986
10987        void cleanUpResourcesLI() {
10988            cleanUp();
10989        }
10990
10991        boolean doPostDeleteLI(boolean delete) {
10992            // XXX err, shouldn't we respect the delete flag?
10993            cleanUpResourcesLI();
10994            return true;
10995        }
10996    }
10997
10998    static String getAsecPackageName(String packageCid) {
10999        int idx = packageCid.lastIndexOf("-");
11000        if (idx == -1) {
11001            return packageCid;
11002        }
11003        return packageCid.substring(0, idx);
11004    }
11005
11006    // Utility method used to create code paths based on package name and available index.
11007    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11008        String idxStr = "";
11009        int idx = 1;
11010        // Fall back to default value of idx=1 if prefix is not
11011        // part of oldCodePath
11012        if (oldCodePath != null) {
11013            String subStr = oldCodePath;
11014            // Drop the suffix right away
11015            if (suffix != null && subStr.endsWith(suffix)) {
11016                subStr = subStr.substring(0, subStr.length() - suffix.length());
11017            }
11018            // If oldCodePath already contains prefix find out the
11019            // ending index to either increment or decrement.
11020            int sidx = subStr.lastIndexOf(prefix);
11021            if (sidx != -1) {
11022                subStr = subStr.substring(sidx + prefix.length());
11023                if (subStr != null) {
11024                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11025                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11026                    }
11027                    try {
11028                        idx = Integer.parseInt(subStr);
11029                        if (idx <= 1) {
11030                            idx++;
11031                        } else {
11032                            idx--;
11033                        }
11034                    } catch(NumberFormatException e) {
11035                    }
11036                }
11037            }
11038        }
11039        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11040        return prefix + idxStr;
11041    }
11042
11043    private File getNextCodePath(File targetDir, String packageName) {
11044        int suffix = 1;
11045        File result;
11046        do {
11047            result = new File(targetDir, packageName + "-" + suffix);
11048            suffix++;
11049        } while (result.exists());
11050        return result;
11051    }
11052
11053    // Utility method that returns the relative package path with respect
11054    // to the installation directory. Like say for /data/data/com.test-1.apk
11055    // string com.test-1 is returned.
11056    static String deriveCodePathName(String codePath) {
11057        if (codePath == null) {
11058            return null;
11059        }
11060        final File codeFile = new File(codePath);
11061        final String name = codeFile.getName();
11062        if (codeFile.isDirectory()) {
11063            return name;
11064        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11065            final int lastDot = name.lastIndexOf('.');
11066            return name.substring(0, lastDot);
11067        } else {
11068            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11069            return null;
11070        }
11071    }
11072
11073    class PackageInstalledInfo {
11074        String name;
11075        int uid;
11076        // The set of users that originally had this package installed.
11077        int[] origUsers;
11078        // The set of users that now have this package installed.
11079        int[] newUsers;
11080        PackageParser.Package pkg;
11081        int returnCode;
11082        String returnMsg;
11083        PackageRemovedInfo removedInfo;
11084
11085        public void setError(int code, String msg) {
11086            returnCode = code;
11087            returnMsg = msg;
11088            Slog.w(TAG, msg);
11089        }
11090
11091        public void setError(String msg, PackageParserException e) {
11092            returnCode = e.error;
11093            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11094            Slog.w(TAG, msg, e);
11095        }
11096
11097        public void setError(String msg, PackageManagerException e) {
11098            returnCode = e.error;
11099            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11100            Slog.w(TAG, msg, e);
11101        }
11102
11103        // In some error cases we want to convey more info back to the observer
11104        String origPackage;
11105        String origPermission;
11106    }
11107
11108    /*
11109     * Install a non-existing package.
11110     */
11111    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11112            UserHandle user, String installerPackageName, String volumeUuid,
11113            PackageInstalledInfo res) {
11114        // Remember this for later, in case we need to rollback this install
11115        String pkgName = pkg.packageName;
11116
11117        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11118        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11119                UserHandle.USER_OWNER).exists();
11120        synchronized(mPackages) {
11121            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11122                // A package with the same name is already installed, though
11123                // it has been renamed to an older name.  The package we
11124                // are trying to install should be installed as an update to
11125                // the existing one, but that has not been requested, so bail.
11126                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11127                        + " without first uninstalling package running as "
11128                        + mSettings.mRenamedPackages.get(pkgName));
11129                return;
11130            }
11131            if (mPackages.containsKey(pkgName)) {
11132                // Don't allow installation over an existing package with the same name.
11133                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11134                        + " without first uninstalling.");
11135                return;
11136            }
11137        }
11138
11139        try {
11140            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11141                    System.currentTimeMillis(), user);
11142
11143            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11144            // delete the partially installed application. the data directory will have to be
11145            // restored if it was already existing
11146            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11147                // remove package from internal structures.  Note that we want deletePackageX to
11148                // delete the package data and cache directories that it created in
11149                // scanPackageLocked, unless those directories existed before we even tried to
11150                // install.
11151                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11152                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11153                                res.removedInfo, true);
11154            }
11155
11156        } catch (PackageManagerException e) {
11157            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11158        }
11159    }
11160
11161    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11162        // Can't rotate keys during boot or if sharedUser.
11163        if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null
11164                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11165            return false;
11166        }
11167        // app is using upgradeKeySets; make sure all are valid
11168        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11169        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11170        for (int i = 0; i < upgradeKeySets.length; i++) {
11171            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11172                Slog.wtf(TAG, "Package "
11173                         + (oldPs.name != null ? oldPs.name : "<null>")
11174                         + " contains upgrade-key-set reference to unknown key-set: "
11175                         + upgradeKeySets[i]
11176                         + " reverting to signatures check.");
11177                return false;
11178            }
11179        }
11180        return true;
11181    }
11182
11183    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11184        // Upgrade keysets are being used.  Determine if new package has a superset of the
11185        // required keys.
11186        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11187        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11188        for (int i = 0; i < upgradeKeySets.length; i++) {
11189            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11190            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11191                return true;
11192            }
11193        }
11194        return false;
11195    }
11196
11197    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11198            UserHandle user, String installerPackageName, String volumeUuid,
11199            PackageInstalledInfo res) {
11200        final PackageParser.Package oldPackage;
11201        final String pkgName = pkg.packageName;
11202        final int[] allUsers;
11203        final boolean[] perUserInstalled;
11204        final boolean weFroze;
11205
11206        // First find the old package info and check signatures
11207        synchronized(mPackages) {
11208            oldPackage = mPackages.get(pkgName);
11209            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11210            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11211            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11212                if(!checkUpgradeKeySetLP(ps, pkg)) {
11213                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11214                            "New package not signed by keys specified by upgrade-keysets: "
11215                            + pkgName);
11216                    return;
11217                }
11218            } else {
11219                // default to original signature matching
11220                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11221                    != PackageManager.SIGNATURE_MATCH) {
11222                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11223                            "New package has a different signature: " + pkgName);
11224                    return;
11225                }
11226            }
11227
11228            // In case of rollback, remember per-user/profile install state
11229            allUsers = sUserManager.getUserIds();
11230            perUserInstalled = new boolean[allUsers.length];
11231            for (int i = 0; i < allUsers.length; i++) {
11232                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11233            }
11234
11235            // Mark the app as frozen to prevent launching during the upgrade
11236            // process, and then kill all running instances
11237            if (!ps.frozen) {
11238                ps.frozen = true;
11239                weFroze = true;
11240            } else {
11241                weFroze = false;
11242            }
11243        }
11244
11245        // Now that we're guarded by frozen state, kill app during upgrade
11246        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11247
11248        try {
11249            boolean sysPkg = (isSystemApp(oldPackage));
11250            if (sysPkg) {
11251                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11252                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11253            } else {
11254                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11255                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11256            }
11257        } finally {
11258            // Regardless of success or failure of upgrade steps above, always
11259            // unfreeze the package if we froze it
11260            if (weFroze) {
11261                unfreezePackage(pkgName);
11262            }
11263        }
11264    }
11265
11266    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11267            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11268            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11269            String volumeUuid, PackageInstalledInfo res) {
11270        String pkgName = deletedPackage.packageName;
11271        boolean deletedPkg = true;
11272        boolean updatedSettings = false;
11273
11274        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11275                + deletedPackage);
11276        long origUpdateTime;
11277        if (pkg.mExtras != null) {
11278            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11279        } else {
11280            origUpdateTime = 0;
11281        }
11282
11283        // First delete the existing package while retaining the data directory
11284        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11285                res.removedInfo, true)) {
11286            // If the existing package wasn't successfully deleted
11287            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11288            deletedPkg = false;
11289        } else {
11290            // Successfully deleted the old package; proceed with replace.
11291
11292            // If deleted package lived in a container, give users a chance to
11293            // relinquish resources before killing.
11294            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11295                if (DEBUG_INSTALL) {
11296                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11297                }
11298                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11299                final ArrayList<String> pkgList = new ArrayList<String>(1);
11300                pkgList.add(deletedPackage.applicationInfo.packageName);
11301                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11302            }
11303
11304            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11305            try {
11306                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11307                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11308                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11309                        perUserInstalled, res, user);
11310                updatedSettings = true;
11311            } catch (PackageManagerException e) {
11312                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11313            }
11314        }
11315
11316        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11317            // remove package from internal structures.  Note that we want deletePackageX to
11318            // delete the package data and cache directories that it created in
11319            // scanPackageLocked, unless those directories existed before we even tried to
11320            // install.
11321            if(updatedSettings) {
11322                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11323                deletePackageLI(
11324                        pkgName, null, true, allUsers, perUserInstalled,
11325                        PackageManager.DELETE_KEEP_DATA,
11326                                res.removedInfo, true);
11327            }
11328            // Since we failed to install the new package we need to restore the old
11329            // package that we deleted.
11330            if (deletedPkg) {
11331                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11332                File restoreFile = new File(deletedPackage.codePath);
11333                // Parse old package
11334                boolean oldExternal = isExternal(deletedPackage);
11335                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11336                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11337                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11338                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11339                try {
11340                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11341                } catch (PackageManagerException e) {
11342                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11343                            + e.getMessage());
11344                    return;
11345                }
11346                // Restore of old package succeeded. Update permissions.
11347                // writer
11348                synchronized (mPackages) {
11349                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11350                            UPDATE_PERMISSIONS_ALL);
11351                    // can downgrade to reader
11352                    mSettings.writeLPr();
11353                }
11354                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11355            }
11356        }
11357    }
11358
11359    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11360            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11361            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11362            String volumeUuid, PackageInstalledInfo res) {
11363        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11364                + ", old=" + deletedPackage);
11365        boolean disabledSystem = false;
11366        boolean updatedSettings = false;
11367        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11368        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11369                != 0) {
11370            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11371        }
11372        String packageName = deletedPackage.packageName;
11373        if (packageName == null) {
11374            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11375                    "Attempt to delete null packageName.");
11376            return;
11377        }
11378        PackageParser.Package oldPkg;
11379        PackageSetting oldPkgSetting;
11380        // reader
11381        synchronized (mPackages) {
11382            oldPkg = mPackages.get(packageName);
11383            oldPkgSetting = mSettings.mPackages.get(packageName);
11384            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11385                    (oldPkgSetting == null)) {
11386                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11387                        "Couldn't find package:" + packageName + " information");
11388                return;
11389            }
11390        }
11391
11392        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11393        res.removedInfo.removedPackage = packageName;
11394        // Remove existing system package
11395        removePackageLI(oldPkgSetting, true);
11396        // writer
11397        synchronized (mPackages) {
11398            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11399            if (!disabledSystem && deletedPackage != null) {
11400                // We didn't need to disable the .apk as a current system package,
11401                // which means we are replacing another update that is already
11402                // installed.  We need to make sure to delete the older one's .apk.
11403                res.removedInfo.args = createInstallArgsForExisting(0,
11404                        deletedPackage.applicationInfo.getCodePath(),
11405                        deletedPackage.applicationInfo.getResourcePath(),
11406                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11407            } else {
11408                res.removedInfo.args = null;
11409            }
11410        }
11411
11412        // Successfully disabled the old package. Now proceed with re-installation
11413        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11414
11415        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11416        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11417
11418        PackageParser.Package newPackage = null;
11419        try {
11420            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11421            if (newPackage.mExtras != null) {
11422                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11423                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11424                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11425
11426                // is the update attempting to change shared user? that isn't going to work...
11427                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11428                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11429                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11430                            + " to " + newPkgSetting.sharedUser);
11431                    updatedSettings = true;
11432                }
11433            }
11434
11435            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11436                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11437                        perUserInstalled, res, user);
11438                updatedSettings = true;
11439            }
11440
11441        } catch (PackageManagerException e) {
11442            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11443        }
11444
11445        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11446            // Re installation failed. Restore old information
11447            // Remove new pkg information
11448            if (newPackage != null) {
11449                removeInstalledPackageLI(newPackage, true);
11450            }
11451            // Add back the old system package
11452            try {
11453                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11454            } catch (PackageManagerException e) {
11455                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11456            }
11457            // Restore the old system information in Settings
11458            synchronized (mPackages) {
11459                if (disabledSystem) {
11460                    mSettings.enableSystemPackageLPw(packageName);
11461                }
11462                if (updatedSettings) {
11463                    mSettings.setInstallerPackageName(packageName,
11464                            oldPkgSetting.installerPackageName);
11465                }
11466                mSettings.writeLPr();
11467            }
11468        }
11469    }
11470
11471    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11472            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11473            UserHandle user) {
11474        String pkgName = newPackage.packageName;
11475        synchronized (mPackages) {
11476            //write settings. the installStatus will be incomplete at this stage.
11477            //note that the new package setting would have already been
11478            //added to mPackages. It hasn't been persisted yet.
11479            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11480            mSettings.writeLPr();
11481        }
11482
11483        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11484
11485        synchronized (mPackages) {
11486            updatePermissionsLPw(newPackage.packageName, newPackage,
11487                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11488                            ? UPDATE_PERMISSIONS_ALL : 0));
11489            // For system-bundled packages, we assume that installing an upgraded version
11490            // of the package implies that the user actually wants to run that new code,
11491            // so we enable the package.
11492            PackageSetting ps = mSettings.mPackages.get(pkgName);
11493            if (ps != null) {
11494                if (isSystemApp(newPackage)) {
11495                    // NB: implicit assumption that system package upgrades apply to all users
11496                    if (DEBUG_INSTALL) {
11497                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11498                    }
11499                    if (res.origUsers != null) {
11500                        for (int userHandle : res.origUsers) {
11501                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11502                                    userHandle, installerPackageName);
11503                        }
11504                    }
11505                    // Also convey the prior install/uninstall state
11506                    if (allUsers != null && perUserInstalled != null) {
11507                        for (int i = 0; i < allUsers.length; i++) {
11508                            if (DEBUG_INSTALL) {
11509                                Slog.d(TAG, "    user " + allUsers[i]
11510                                        + " => " + perUserInstalled[i]);
11511                            }
11512                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11513                        }
11514                        // these install state changes will be persisted in the
11515                        // upcoming call to mSettings.writeLPr().
11516                    }
11517                }
11518                // It's implied that when a user requests installation, they want the app to be
11519                // installed and enabled.
11520                int userId = user.getIdentifier();
11521                if (userId != UserHandle.USER_ALL) {
11522                    ps.setInstalled(true, userId);
11523                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11524                }
11525            }
11526            res.name = pkgName;
11527            res.uid = newPackage.applicationInfo.uid;
11528            res.pkg = newPackage;
11529            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11530            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11531            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11532            //to update install status
11533            mSettings.writeLPr();
11534        }
11535    }
11536
11537    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11538        final int installFlags = args.installFlags;
11539        final String installerPackageName = args.installerPackageName;
11540        final String volumeUuid = args.volumeUuid;
11541        final File tmpPackageFile = new File(args.getCodePath());
11542        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11543        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11544                || (args.volumeUuid != null));
11545        boolean replace = false;
11546        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11547        // Result object to be returned
11548        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11549
11550        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11551        // Retrieve PackageSettings and parse package
11552        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11553                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11554                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11555        PackageParser pp = new PackageParser();
11556        pp.setSeparateProcesses(mSeparateProcesses);
11557        pp.setDisplayMetrics(mMetrics);
11558
11559        final PackageParser.Package pkg;
11560        try {
11561            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11562        } catch (PackageParserException e) {
11563            res.setError("Failed parse during installPackageLI", e);
11564            return;
11565        }
11566
11567        // Mark that we have an install time CPU ABI override.
11568        pkg.cpuAbiOverride = args.abiOverride;
11569
11570        String pkgName = res.name = pkg.packageName;
11571        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11572            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11573                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11574                return;
11575            }
11576        }
11577
11578        try {
11579            pp.collectCertificates(pkg, parseFlags);
11580            pp.collectManifestDigest(pkg);
11581        } catch (PackageParserException e) {
11582            res.setError("Failed collect during installPackageLI", e);
11583            return;
11584        }
11585
11586        /* If the installer passed in a manifest digest, compare it now. */
11587        if (args.manifestDigest != null) {
11588            if (DEBUG_INSTALL) {
11589                final String parsedManifest = pkg.manifestDigest == null ? "null"
11590                        : pkg.manifestDigest.toString();
11591                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11592                        + parsedManifest);
11593            }
11594
11595            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11596                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11597                return;
11598            }
11599        } else if (DEBUG_INSTALL) {
11600            final String parsedManifest = pkg.manifestDigest == null
11601                    ? "null" : pkg.manifestDigest.toString();
11602            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11603        }
11604
11605        // Get rid of all references to package scan path via parser.
11606        pp = null;
11607        String oldCodePath = null;
11608        boolean systemApp = false;
11609        synchronized (mPackages) {
11610            // Check if installing already existing package
11611            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11612                String oldName = mSettings.mRenamedPackages.get(pkgName);
11613                if (pkg.mOriginalPackages != null
11614                        && pkg.mOriginalPackages.contains(oldName)
11615                        && mPackages.containsKey(oldName)) {
11616                    // This package is derived from an original package,
11617                    // and this device has been updating from that original
11618                    // name.  We must continue using the original name, so
11619                    // rename the new package here.
11620                    pkg.setPackageName(oldName);
11621                    pkgName = pkg.packageName;
11622                    replace = true;
11623                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11624                            + oldName + " pkgName=" + pkgName);
11625                } else if (mPackages.containsKey(pkgName)) {
11626                    // This package, under its official name, already exists
11627                    // on the device; we should replace it.
11628                    replace = true;
11629                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11630                }
11631
11632                // Prevent apps opting out from runtime permissions
11633                if (replace) {
11634                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11635                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11636                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11637                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11638                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11639                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11640                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11641                                        + " doesn't support runtime permissions but the old"
11642                                        + " target SDK " + oldTargetSdk + " does.");
11643                        return;
11644                    }
11645                }
11646            }
11647
11648            PackageSetting ps = mSettings.mPackages.get(pkgName);
11649            if (ps != null) {
11650                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11651
11652                // Quick sanity check that we're signed correctly if updating;
11653                // we'll check this again later when scanning, but we want to
11654                // bail early here before tripping over redefined permissions.
11655                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11656                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11657                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11658                                + pkg.packageName + " upgrade keys do not match the "
11659                                + "previously installed version");
11660                        return;
11661                    }
11662                } else {
11663                    try {
11664                        verifySignaturesLP(ps, pkg);
11665                    } catch (PackageManagerException e) {
11666                        res.setError(e.error, e.getMessage());
11667                        return;
11668                    }
11669                }
11670
11671                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11672                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11673                    systemApp = (ps.pkg.applicationInfo.flags &
11674                            ApplicationInfo.FLAG_SYSTEM) != 0;
11675                }
11676                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11677            }
11678
11679            // Check whether the newly-scanned package wants to define an already-defined perm
11680            int N = pkg.permissions.size();
11681            for (int i = N-1; i >= 0; i--) {
11682                PackageParser.Permission perm = pkg.permissions.get(i);
11683                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11684                if (bp != null) {
11685                    // If the defining package is signed with our cert, it's okay.  This
11686                    // also includes the "updating the same package" case, of course.
11687                    // "updating same package" could also involve key-rotation.
11688                    final boolean sigsOk;
11689                    if (bp.sourcePackage.equals(pkg.packageName)
11690                            && (bp.packageSetting instanceof PackageSetting)
11691                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
11692                                    scanFlags))) {
11693                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11694                    } else {
11695                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11696                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11697                    }
11698                    if (!sigsOk) {
11699                        // If the owning package is the system itself, we log but allow
11700                        // install to proceed; we fail the install on all other permission
11701                        // redefinitions.
11702                        if (!bp.sourcePackage.equals("android")) {
11703                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11704                                    + pkg.packageName + " attempting to redeclare permission "
11705                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11706                            res.origPermission = perm.info.name;
11707                            res.origPackage = bp.sourcePackage;
11708                            return;
11709                        } else {
11710                            Slog.w(TAG, "Package " + pkg.packageName
11711                                    + " attempting to redeclare system permission "
11712                                    + perm.info.name + "; ignoring new declaration");
11713                            pkg.permissions.remove(i);
11714                        }
11715                    }
11716                }
11717            }
11718
11719        }
11720
11721        if (systemApp && onExternal) {
11722            // Disable updates to system apps on sdcard
11723            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11724                    "Cannot install updates to system apps on sdcard");
11725            return;
11726        }
11727
11728        if (args.move != null) {
11729            // We did an in-place move, so dex is ready to roll
11730            scanFlags |= SCAN_NO_DEX;
11731            scanFlags |= SCAN_MOVE;
11732        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11733            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11734            scanFlags |= SCAN_NO_DEX;
11735
11736            try {
11737                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
11738                        true /* extract libs */);
11739            } catch (PackageManagerException pme) {
11740                Slog.e(TAG, "Error deriving application ABI", pme);
11741                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
11742                return;
11743            }
11744
11745            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11746            int result = mPackageDexOptimizer
11747                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
11748                            false /* defer */, false /* inclDependencies */);
11749            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11750                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11751                return;
11752            }
11753        }
11754
11755        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11756            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11757            return;
11758        }
11759
11760        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11761
11762        if (replace) {
11763            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11764                    installerPackageName, volumeUuid, res);
11765        } else {
11766            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11767                    args.user, installerPackageName, volumeUuid, res);
11768        }
11769        synchronized (mPackages) {
11770            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11771            if (ps != null) {
11772                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11773            }
11774        }
11775    }
11776
11777    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11778        if (mIntentFilterVerifierComponent == null) {
11779            Slog.w(TAG, "No IntentFilter verification will not be done as "
11780                    + "there is no IntentFilterVerifier available!");
11781            return;
11782        }
11783
11784        final int verifierUid = getPackageUid(
11785                mIntentFilterVerifierComponent.getPackageName(),
11786                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11787
11788        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11789        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11790        msg.obj = pkg;
11791        msg.arg1 = userId;
11792        msg.arg2 = verifierUid;
11793
11794        mHandler.sendMessage(msg);
11795    }
11796
11797    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11798            PackageParser.Package pkg) {
11799        int size = pkg.activities.size();
11800        if (size == 0) {
11801            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11802                    "No activity, so no need to verify any IntentFilter!");
11803            return;
11804        }
11805
11806        final boolean hasDomainURLs = hasDomainURLs(pkg);
11807        if (!hasDomainURLs) {
11808            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11809                    "No domain URLs, so no need to verify any IntentFilter!");
11810            return;
11811        }
11812
11813        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
11814                + " if any IntentFilter from the " + size
11815                + " Activities needs verification ...");
11816
11817        final int verificationId = mIntentFilterVerificationToken++;
11818        int count = 0;
11819        final String packageName = pkg.packageName;
11820        boolean needToVerify = false;
11821
11822        synchronized (mPackages) {
11823            // If any filters need to be verified, then all need to be.
11824            for (PackageParser.Activity a : pkg.activities) {
11825                for (ActivityIntentInfo filter : a.intents) {
11826                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
11827                        if (DEBUG_DOMAIN_VERIFICATION) {
11828                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
11829                        }
11830                        needToVerify = true;
11831                        break;
11832                    }
11833                }
11834            }
11835            if (needToVerify) {
11836                for (PackageParser.Activity a : pkg.activities) {
11837                    for (ActivityIntentInfo filter : a.intents) {
11838                        boolean needsFilterVerification = filter.hasWebDataURI();
11839                        if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11840                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11841                                    "Verification needed for IntentFilter:" + filter.toString());
11842                            mIntentFilterVerifier.addOneIntentFilterVerification(
11843                                    verifierUid, userId, verificationId, filter, packageName);
11844                            count++;
11845                        }
11846                    }
11847                }
11848            }
11849        }
11850
11851        if (count > 0) {
11852            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
11853                    + " IntentFilter verification" + (count > 1 ? "s" : "")
11854                    +  " for userId:" + userId);
11855            mIntentFilterVerifier.startVerifications(userId);
11856        } else {
11857            if (DEBUG_DOMAIN_VERIFICATION) {
11858                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
11859            }
11860        }
11861    }
11862
11863    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11864        final ComponentName cn  = filter.activity.getComponentName();
11865        final String packageName = cn.getPackageName();
11866
11867        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11868                packageName);
11869        if (ivi == null) {
11870            return true;
11871        }
11872        int status = ivi.getStatus();
11873        switch (status) {
11874            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11875            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11876                return true;
11877
11878            default:
11879                // Nothing to do
11880                return false;
11881        }
11882    }
11883
11884    private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) {
11885        return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID
11886                || ((pkg.applicationInfo.privateFlags
11887                        & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0
11888                && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0);
11889    }
11890
11891    private static boolean isMultiArch(PackageSetting ps) {
11892        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11893    }
11894
11895    private static boolean isMultiArch(ApplicationInfo info) {
11896        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11897    }
11898
11899    private static boolean isExternal(PackageParser.Package pkg) {
11900        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11901    }
11902
11903    private static boolean isExternal(PackageSetting ps) {
11904        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11905    }
11906
11907    private static boolean isExternal(ApplicationInfo info) {
11908        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11909    }
11910
11911    private static boolean isSystemApp(PackageParser.Package pkg) {
11912        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11913    }
11914
11915    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11916        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11917    }
11918
11919    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11920        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11921    }
11922
11923    private static boolean isSystemApp(PackageSetting ps) {
11924        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11925    }
11926
11927    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11928        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11929    }
11930
11931    private int packageFlagsToInstallFlags(PackageSetting ps) {
11932        int installFlags = 0;
11933        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11934            // This existing package was an external ASEC install when we have
11935            // the external flag without a UUID
11936            installFlags |= PackageManager.INSTALL_EXTERNAL;
11937        }
11938        if (ps.isForwardLocked()) {
11939            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11940        }
11941        return installFlags;
11942    }
11943
11944    private void deleteTempPackageFiles() {
11945        final FilenameFilter filter = new FilenameFilter() {
11946            public boolean accept(File dir, String name) {
11947                return name.startsWith("vmdl") && name.endsWith(".tmp");
11948            }
11949        };
11950        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11951            file.delete();
11952        }
11953    }
11954
11955    @Override
11956    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11957            int flags) {
11958        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11959                flags);
11960    }
11961
11962    @Override
11963    public void deletePackage(final String packageName,
11964            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11965        mContext.enforceCallingOrSelfPermission(
11966                android.Manifest.permission.DELETE_PACKAGES, null);
11967        final int uid = Binder.getCallingUid();
11968        if (UserHandle.getUserId(uid) != userId) {
11969            mContext.enforceCallingPermission(
11970                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11971                    "deletePackage for user " + userId);
11972        }
11973        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11974            try {
11975                observer.onPackageDeleted(packageName,
11976                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11977            } catch (RemoteException re) {
11978            }
11979            return;
11980        }
11981
11982        boolean uninstallBlocked = false;
11983        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11984            int[] users = sUserManager.getUserIds();
11985            for (int i = 0; i < users.length; ++i) {
11986                if (getBlockUninstallForUser(packageName, users[i])) {
11987                    uninstallBlocked = true;
11988                    break;
11989                }
11990            }
11991        } else {
11992            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11993        }
11994        if (uninstallBlocked) {
11995            try {
11996                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11997                        null);
11998            } catch (RemoteException re) {
11999            }
12000            return;
12001        }
12002
12003        if (DEBUG_REMOVE) {
12004            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12005        }
12006        // Queue up an async operation since the package deletion may take a little while.
12007        mHandler.post(new Runnable() {
12008            public void run() {
12009                mHandler.removeCallbacks(this);
12010                final int returnCode = deletePackageX(packageName, userId, flags);
12011                if (observer != null) {
12012                    try {
12013                        observer.onPackageDeleted(packageName, returnCode, null);
12014                    } catch (RemoteException e) {
12015                        Log.i(TAG, "Observer no longer exists.");
12016                    } //end catch
12017                } //end if
12018            } //end run
12019        });
12020    }
12021
12022    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12023        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12024                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12025        try {
12026            if (dpm != null) {
12027                if (dpm.isDeviceOwner(packageName)) {
12028                    return true;
12029                }
12030                int[] users;
12031                if (userId == UserHandle.USER_ALL) {
12032                    users = sUserManager.getUserIds();
12033                } else {
12034                    users = new int[]{userId};
12035                }
12036                for (int i = 0; i < users.length; ++i) {
12037                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12038                        return true;
12039                    }
12040                }
12041            }
12042        } catch (RemoteException e) {
12043        }
12044        return false;
12045    }
12046
12047    /**
12048     *  This method is an internal method that could be get invoked either
12049     *  to delete an installed package or to clean up a failed installation.
12050     *  After deleting an installed package, a broadcast is sent to notify any
12051     *  listeners that the package has been installed. For cleaning up a failed
12052     *  installation, the broadcast is not necessary since the package's
12053     *  installation wouldn't have sent the initial broadcast either
12054     *  The key steps in deleting a package are
12055     *  deleting the package information in internal structures like mPackages,
12056     *  deleting the packages base directories through installd
12057     *  updating mSettings to reflect current status
12058     *  persisting settings for later use
12059     *  sending a broadcast if necessary
12060     */
12061    private int deletePackageX(String packageName, int userId, int flags) {
12062        final PackageRemovedInfo info = new PackageRemovedInfo();
12063        final boolean res;
12064
12065        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12066                ? UserHandle.ALL : new UserHandle(userId);
12067
12068        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12069            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12070            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12071        }
12072
12073        boolean removedForAllUsers = false;
12074        boolean systemUpdate = false;
12075
12076        // for the uninstall-updates case and restricted profiles, remember the per-
12077        // userhandle installed state
12078        int[] allUsers;
12079        boolean[] perUserInstalled;
12080        synchronized (mPackages) {
12081            PackageSetting ps = mSettings.mPackages.get(packageName);
12082            allUsers = sUserManager.getUserIds();
12083            perUserInstalled = new boolean[allUsers.length];
12084            for (int i = 0; i < allUsers.length; i++) {
12085                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12086            }
12087        }
12088
12089        synchronized (mInstallLock) {
12090            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12091            res = deletePackageLI(packageName, removeForUser,
12092                    true, allUsers, perUserInstalled,
12093                    flags | REMOVE_CHATTY, info, true);
12094            systemUpdate = info.isRemovedPackageSystemUpdate;
12095            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12096                removedForAllUsers = true;
12097            }
12098            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12099                    + " removedForAllUsers=" + removedForAllUsers);
12100        }
12101
12102        if (res) {
12103            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12104
12105            // If the removed package was a system update, the old system package
12106            // was re-enabled; we need to broadcast this information
12107            if (systemUpdate) {
12108                Bundle extras = new Bundle(1);
12109                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12110                        ? info.removedAppId : info.uid);
12111                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12112
12113                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12114                        extras, null, null, null);
12115                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12116                        extras, null, null, null);
12117                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12118                        null, packageName, null, null);
12119            }
12120        }
12121        // Force a gc here.
12122        Runtime.getRuntime().gc();
12123        // Delete the resources here after sending the broadcast to let
12124        // other processes clean up before deleting resources.
12125        if (info.args != null) {
12126            synchronized (mInstallLock) {
12127                info.args.doPostDeleteLI(true);
12128            }
12129        }
12130
12131        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12132    }
12133
12134    class PackageRemovedInfo {
12135        String removedPackage;
12136        int uid = -1;
12137        int removedAppId = -1;
12138        int[] removedUsers = null;
12139        boolean isRemovedPackageSystemUpdate = false;
12140        // Clean up resources deleted packages.
12141        InstallArgs args = null;
12142
12143        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12144            Bundle extras = new Bundle(1);
12145            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12146            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12147            if (replacing) {
12148                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12149            }
12150            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12151            if (removedPackage != null) {
12152                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12153                        extras, null, null, removedUsers);
12154                if (fullRemove && !replacing) {
12155                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12156                            extras, null, null, removedUsers);
12157                }
12158            }
12159            if (removedAppId >= 0) {
12160                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12161                        removedUsers);
12162            }
12163        }
12164    }
12165
12166    /*
12167     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12168     * flag is not set, the data directory is removed as well.
12169     * make sure this flag is set for partially installed apps. If not its meaningless to
12170     * delete a partially installed application.
12171     */
12172    private void removePackageDataLI(PackageSetting ps,
12173            int[] allUserHandles, boolean[] perUserInstalled,
12174            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12175        String packageName = ps.name;
12176        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12177        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12178        // Retrieve object to delete permissions for shared user later on
12179        final PackageSetting deletedPs;
12180        // reader
12181        synchronized (mPackages) {
12182            deletedPs = mSettings.mPackages.get(packageName);
12183            if (outInfo != null) {
12184                outInfo.removedPackage = packageName;
12185                outInfo.removedUsers = deletedPs != null
12186                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12187                        : null;
12188            }
12189        }
12190        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12191            removeDataDirsLI(ps.volumeUuid, packageName);
12192            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12193        }
12194        // writer
12195        synchronized (mPackages) {
12196            if (deletedPs != null) {
12197                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12198                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12199                    clearDefaultBrowserIfNeeded(packageName);
12200                    if (outInfo != null) {
12201                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12202                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12203                    }
12204                    updatePermissionsLPw(deletedPs.name, null, 0);
12205                    if (deletedPs.sharedUser != null) {
12206                        // Remove permissions associated with package. Since runtime
12207                        // permissions are per user we have to kill the removed package
12208                        // or packages running under the shared user of the removed
12209                        // package if revoking the permissions requested only by the removed
12210                        // package is successful and this causes a change in gids.
12211                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12212                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12213                                    userId);
12214                            if (userIdToKill == UserHandle.USER_ALL
12215                                    || userIdToKill >= UserHandle.USER_OWNER) {
12216                                // If gids changed for this user, kill all affected packages.
12217                                mHandler.post(new Runnable() {
12218                                    @Override
12219                                    public void run() {
12220                                        // This has to happen with no lock held.
12221                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12222                                                KILL_APP_REASON_GIDS_CHANGED);
12223                                    }
12224                                });
12225                            break;
12226                            }
12227                        }
12228                    }
12229                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12230                }
12231                // make sure to preserve per-user disabled state if this removal was just
12232                // a downgrade of a system app to the factory package
12233                if (allUserHandles != null && perUserInstalled != null) {
12234                    if (DEBUG_REMOVE) {
12235                        Slog.d(TAG, "Propagating install state across downgrade");
12236                    }
12237                    for (int i = 0; i < allUserHandles.length; i++) {
12238                        if (DEBUG_REMOVE) {
12239                            Slog.d(TAG, "    user " + allUserHandles[i]
12240                                    + " => " + perUserInstalled[i]);
12241                        }
12242                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12243                    }
12244                }
12245            }
12246            // can downgrade to reader
12247            if (writeSettings) {
12248                // Save settings now
12249                mSettings.writeLPr();
12250            }
12251        }
12252        if (outInfo != null) {
12253            // A user ID was deleted here. Go through all users and remove it
12254            // from KeyStore.
12255            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12256        }
12257    }
12258
12259    static boolean locationIsPrivileged(File path) {
12260        try {
12261            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12262                    .getCanonicalPath();
12263            return path.getCanonicalPath().startsWith(privilegedAppDir);
12264        } catch (IOException e) {
12265            Slog.e(TAG, "Unable to access code path " + path);
12266        }
12267        return false;
12268    }
12269
12270    /*
12271     * Tries to delete system package.
12272     */
12273    private boolean deleteSystemPackageLI(PackageSetting newPs,
12274            int[] allUserHandles, boolean[] perUserInstalled,
12275            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12276        final boolean applyUserRestrictions
12277                = (allUserHandles != null) && (perUserInstalled != null);
12278        PackageSetting disabledPs = null;
12279        // Confirm if the system package has been updated
12280        // An updated system app can be deleted. This will also have to restore
12281        // the system pkg from system partition
12282        // reader
12283        synchronized (mPackages) {
12284            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12285        }
12286        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12287                + " disabledPs=" + disabledPs);
12288        if (disabledPs == null) {
12289            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12290            return false;
12291        } else if (DEBUG_REMOVE) {
12292            Slog.d(TAG, "Deleting system pkg from data partition");
12293        }
12294        if (DEBUG_REMOVE) {
12295            if (applyUserRestrictions) {
12296                Slog.d(TAG, "Remembering install states:");
12297                for (int i = 0; i < allUserHandles.length; i++) {
12298                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12299                }
12300            }
12301        }
12302        // Delete the updated package
12303        outInfo.isRemovedPackageSystemUpdate = true;
12304        if (disabledPs.versionCode < newPs.versionCode) {
12305            // Delete data for downgrades
12306            flags &= ~PackageManager.DELETE_KEEP_DATA;
12307        } else {
12308            // Preserve data by setting flag
12309            flags |= PackageManager.DELETE_KEEP_DATA;
12310        }
12311        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12312                allUserHandles, perUserInstalled, outInfo, writeSettings);
12313        if (!ret) {
12314            return false;
12315        }
12316        // writer
12317        synchronized (mPackages) {
12318            // Reinstate the old system package
12319            mSettings.enableSystemPackageLPw(newPs.name);
12320            // Remove any native libraries from the upgraded package.
12321            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12322        }
12323        // Install the system package
12324        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12325        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12326        if (locationIsPrivileged(disabledPs.codePath)) {
12327            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12328        }
12329
12330        final PackageParser.Package newPkg;
12331        try {
12332            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12333        } catch (PackageManagerException e) {
12334            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12335            return false;
12336        }
12337
12338        // writer
12339        synchronized (mPackages) {
12340            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12341            updatePermissionsLPw(newPkg.packageName, newPkg,
12342                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12343            if (applyUserRestrictions) {
12344                if (DEBUG_REMOVE) {
12345                    Slog.d(TAG, "Propagating install state across reinstall");
12346                }
12347                for (int i = 0; i < allUserHandles.length; i++) {
12348                    if (DEBUG_REMOVE) {
12349                        Slog.d(TAG, "    user " + allUserHandles[i]
12350                                + " => " + perUserInstalled[i]);
12351                    }
12352                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12353                }
12354                // Regardless of writeSettings we need to ensure that this restriction
12355                // state propagation is persisted
12356                mSettings.writeAllUsersPackageRestrictionsLPr();
12357            }
12358            // can downgrade to reader here
12359            if (writeSettings) {
12360                mSettings.writeLPr();
12361            }
12362        }
12363        return true;
12364    }
12365
12366    private boolean deleteInstalledPackageLI(PackageSetting ps,
12367            boolean deleteCodeAndResources, int flags,
12368            int[] allUserHandles, boolean[] perUserInstalled,
12369            PackageRemovedInfo outInfo, boolean writeSettings) {
12370        if (outInfo != null) {
12371            outInfo.uid = ps.appId;
12372        }
12373
12374        // Delete package data from internal structures and also remove data if flag is set
12375        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12376
12377        // Delete application code and resources
12378        if (deleteCodeAndResources && (outInfo != null)) {
12379            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12380                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12381            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12382        }
12383        return true;
12384    }
12385
12386    @Override
12387    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12388            int userId) {
12389        mContext.enforceCallingOrSelfPermission(
12390                android.Manifest.permission.DELETE_PACKAGES, null);
12391        synchronized (mPackages) {
12392            PackageSetting ps = mSettings.mPackages.get(packageName);
12393            if (ps == null) {
12394                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12395                return false;
12396            }
12397            if (!ps.getInstalled(userId)) {
12398                // Can't block uninstall for an app that is not installed or enabled.
12399                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12400                return false;
12401            }
12402            ps.setBlockUninstall(blockUninstall, userId);
12403            mSettings.writePackageRestrictionsLPr(userId);
12404        }
12405        return true;
12406    }
12407
12408    @Override
12409    public boolean getBlockUninstallForUser(String packageName, int userId) {
12410        synchronized (mPackages) {
12411            PackageSetting ps = mSettings.mPackages.get(packageName);
12412            if (ps == null) {
12413                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12414                return false;
12415            }
12416            return ps.getBlockUninstall(userId);
12417        }
12418    }
12419
12420    /*
12421     * This method handles package deletion in general
12422     */
12423    private boolean deletePackageLI(String packageName, UserHandle user,
12424            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12425            int flags, PackageRemovedInfo outInfo,
12426            boolean writeSettings) {
12427        if (packageName == null) {
12428            Slog.w(TAG, "Attempt to delete null packageName.");
12429            return false;
12430        }
12431        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12432        PackageSetting ps;
12433        boolean dataOnly = false;
12434        int removeUser = -1;
12435        int appId = -1;
12436        synchronized (mPackages) {
12437            ps = mSettings.mPackages.get(packageName);
12438            if (ps == null) {
12439                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12440                return false;
12441            }
12442            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12443                    && user.getIdentifier() != UserHandle.USER_ALL) {
12444                // The caller is asking that the package only be deleted for a single
12445                // user.  To do this, we just mark its uninstalled state and delete
12446                // its data.  If this is a system app, we only allow this to happen if
12447                // they have set the special DELETE_SYSTEM_APP which requests different
12448                // semantics than normal for uninstalling system apps.
12449                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12450                ps.setUserState(user.getIdentifier(),
12451                        COMPONENT_ENABLED_STATE_DEFAULT,
12452                        false, //installed
12453                        true,  //stopped
12454                        true,  //notLaunched
12455                        false, //hidden
12456                        null, null, null,
12457                        false, // blockUninstall
12458                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12459                if (!isSystemApp(ps)) {
12460                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12461                        // Other user still have this package installed, so all
12462                        // we need to do is clear this user's data and save that
12463                        // it is uninstalled.
12464                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12465                        removeUser = user.getIdentifier();
12466                        appId = ps.appId;
12467                        scheduleWritePackageRestrictionsLocked(removeUser);
12468                    } else {
12469                        // We need to set it back to 'installed' so the uninstall
12470                        // broadcasts will be sent correctly.
12471                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12472                        ps.setInstalled(true, user.getIdentifier());
12473                    }
12474                } else {
12475                    // This is a system app, so we assume that the
12476                    // other users still have this package installed, so all
12477                    // we need to do is clear this user's data and save that
12478                    // it is uninstalled.
12479                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12480                    removeUser = user.getIdentifier();
12481                    appId = ps.appId;
12482                    scheduleWritePackageRestrictionsLocked(removeUser);
12483                }
12484            }
12485        }
12486
12487        if (removeUser >= 0) {
12488            // From above, we determined that we are deleting this only
12489            // for a single user.  Continue the work here.
12490            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12491            if (outInfo != null) {
12492                outInfo.removedPackage = packageName;
12493                outInfo.removedAppId = appId;
12494                outInfo.removedUsers = new int[] {removeUser};
12495            }
12496            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12497            removeKeystoreDataIfNeeded(removeUser, appId);
12498            schedulePackageCleaning(packageName, removeUser, false);
12499            synchronized (mPackages) {
12500                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12501                    scheduleWritePackageRestrictionsLocked(removeUser);
12502                }
12503            }
12504            return true;
12505        }
12506
12507        if (dataOnly) {
12508            // Delete application data first
12509            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12510            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12511            return true;
12512        }
12513
12514        boolean ret = false;
12515        if (isSystemApp(ps)) {
12516            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12517            // When an updated system application is deleted we delete the existing resources as well and
12518            // fall back to existing code in system partition
12519            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12520                    flags, outInfo, writeSettings);
12521        } else {
12522            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12523            // Kill application pre-emptively especially for apps on sd.
12524            killApplication(packageName, ps.appId, "uninstall pkg");
12525            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12526                    allUserHandles, perUserInstalled,
12527                    outInfo, writeSettings);
12528        }
12529
12530        return ret;
12531    }
12532
12533    private final class ClearStorageConnection implements ServiceConnection {
12534        IMediaContainerService mContainerService;
12535
12536        @Override
12537        public void onServiceConnected(ComponentName name, IBinder service) {
12538            synchronized (this) {
12539                mContainerService = IMediaContainerService.Stub.asInterface(service);
12540                notifyAll();
12541            }
12542        }
12543
12544        @Override
12545        public void onServiceDisconnected(ComponentName name) {
12546        }
12547    }
12548
12549    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12550        final boolean mounted;
12551        if (Environment.isExternalStorageEmulated()) {
12552            mounted = true;
12553        } else {
12554            final String status = Environment.getExternalStorageState();
12555
12556            mounted = status.equals(Environment.MEDIA_MOUNTED)
12557                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12558        }
12559
12560        if (!mounted) {
12561            return;
12562        }
12563
12564        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12565        int[] users;
12566        if (userId == UserHandle.USER_ALL) {
12567            users = sUserManager.getUserIds();
12568        } else {
12569            users = new int[] { userId };
12570        }
12571        final ClearStorageConnection conn = new ClearStorageConnection();
12572        if (mContext.bindServiceAsUser(
12573                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12574            try {
12575                for (int curUser : users) {
12576                    long timeout = SystemClock.uptimeMillis() + 5000;
12577                    synchronized (conn) {
12578                        long now = SystemClock.uptimeMillis();
12579                        while (conn.mContainerService == null && now < timeout) {
12580                            try {
12581                                conn.wait(timeout - now);
12582                            } catch (InterruptedException e) {
12583                            }
12584                        }
12585                    }
12586                    if (conn.mContainerService == null) {
12587                        return;
12588                    }
12589
12590                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12591                    clearDirectory(conn.mContainerService,
12592                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12593                    if (allData) {
12594                        clearDirectory(conn.mContainerService,
12595                                userEnv.buildExternalStorageAppDataDirs(packageName));
12596                        clearDirectory(conn.mContainerService,
12597                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12598                    }
12599                }
12600            } finally {
12601                mContext.unbindService(conn);
12602            }
12603        }
12604    }
12605
12606    @Override
12607    public void clearApplicationUserData(final String packageName,
12608            final IPackageDataObserver observer, final int userId) {
12609        mContext.enforceCallingOrSelfPermission(
12610                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12611        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12612        // Queue up an async operation since the package deletion may take a little while.
12613        mHandler.post(new Runnable() {
12614            public void run() {
12615                mHandler.removeCallbacks(this);
12616                final boolean succeeded;
12617                synchronized (mInstallLock) {
12618                    succeeded = clearApplicationUserDataLI(packageName, userId);
12619                }
12620                clearExternalStorageDataSync(packageName, userId, true);
12621                if (succeeded) {
12622                    // invoke DeviceStorageMonitor's update method to clear any notifications
12623                    DeviceStorageMonitorInternal
12624                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12625                    if (dsm != null) {
12626                        dsm.checkMemory();
12627                    }
12628                }
12629                if(observer != null) {
12630                    try {
12631                        observer.onRemoveCompleted(packageName, succeeded);
12632                    } catch (RemoteException e) {
12633                        Log.i(TAG, "Observer no longer exists.");
12634                    }
12635                } //end if observer
12636            } //end run
12637        });
12638    }
12639
12640    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12641        if (packageName == null) {
12642            Slog.w(TAG, "Attempt to delete null packageName.");
12643            return false;
12644        }
12645
12646        // Try finding details about the requested package
12647        PackageParser.Package pkg;
12648        synchronized (mPackages) {
12649            pkg = mPackages.get(packageName);
12650            if (pkg == null) {
12651                final PackageSetting ps = mSettings.mPackages.get(packageName);
12652                if (ps != null) {
12653                    pkg = ps.pkg;
12654                }
12655            }
12656
12657            if (pkg == null) {
12658                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12659                return false;
12660            }
12661
12662            PackageSetting ps = (PackageSetting) pkg.mExtras;
12663            PermissionsState permissionsState = ps.getPermissionsState();
12664            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
12665        }
12666
12667        // Always delete data directories for package, even if we found no other
12668        // record of app. This helps users recover from UID mismatches without
12669        // resorting to a full data wipe.
12670        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12671        if (retCode < 0) {
12672            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12673            return false;
12674        }
12675
12676        final int appId = pkg.applicationInfo.uid;
12677        removeKeystoreDataIfNeeded(userId, appId);
12678
12679        // Create a native library symlink only if we have native libraries
12680        // and if the native libraries are 32 bit libraries. We do not provide
12681        // this symlink for 64 bit libraries.
12682        if (pkg.applicationInfo.primaryCpuAbi != null &&
12683                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12684            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12685            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12686                    nativeLibPath, userId) < 0) {
12687                Slog.w(TAG, "Failed linking native library dir");
12688                return false;
12689            }
12690        }
12691
12692        return true;
12693    }
12694
12695
12696    /**
12697     * Revokes granted runtime permissions and clears resettable flags
12698     * which are flags that can be set by a user interaction.
12699     *
12700     * @param permissionsState The permission state to reset.
12701     * @param userId The device user for which to do a reset.
12702     */
12703    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
12704            PermissionsState permissionsState, int userId) {
12705        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
12706                | PackageManager.FLAG_PERMISSION_USER_FIXED
12707                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12708
12709        boolean needsWrite = false;
12710
12711        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
12712            BasePermission bp = mSettings.mPermissions.get(state.getName());
12713            if (bp != null) {
12714                permissionsState.revokeRuntimePermission(bp, userId);
12715                permissionsState.updatePermissionFlags(bp, userId, userSetFlags, 0);
12716                needsWrite = true;
12717            }
12718        }
12719
12720        if (needsWrite) {
12721            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
12722        }
12723    }
12724
12725    /**
12726     * Remove entries from the keystore daemon. Will only remove it if the
12727     * {@code appId} is valid.
12728     */
12729    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12730        if (appId < 0) {
12731            return;
12732        }
12733
12734        final KeyStore keyStore = KeyStore.getInstance();
12735        if (keyStore != null) {
12736            if (userId == UserHandle.USER_ALL) {
12737                for (final int individual : sUserManager.getUserIds()) {
12738                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12739                }
12740            } else {
12741                keyStore.clearUid(UserHandle.getUid(userId, appId));
12742            }
12743        } else {
12744            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12745        }
12746    }
12747
12748    @Override
12749    public void deleteApplicationCacheFiles(final String packageName,
12750            final IPackageDataObserver observer) {
12751        mContext.enforceCallingOrSelfPermission(
12752                android.Manifest.permission.DELETE_CACHE_FILES, null);
12753        // Queue up an async operation since the package deletion may take a little while.
12754        final int userId = UserHandle.getCallingUserId();
12755        mHandler.post(new Runnable() {
12756            public void run() {
12757                mHandler.removeCallbacks(this);
12758                final boolean succeded;
12759                synchronized (mInstallLock) {
12760                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12761                }
12762                clearExternalStorageDataSync(packageName, userId, false);
12763                if (observer != null) {
12764                    try {
12765                        observer.onRemoveCompleted(packageName, succeded);
12766                    } catch (RemoteException e) {
12767                        Log.i(TAG, "Observer no longer exists.");
12768                    }
12769                } //end if observer
12770            } //end run
12771        });
12772    }
12773
12774    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12775        if (packageName == null) {
12776            Slog.w(TAG, "Attempt to delete null packageName.");
12777            return false;
12778        }
12779        PackageParser.Package p;
12780        synchronized (mPackages) {
12781            p = mPackages.get(packageName);
12782        }
12783        if (p == null) {
12784            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12785            return false;
12786        }
12787        final ApplicationInfo applicationInfo = p.applicationInfo;
12788        if (applicationInfo == null) {
12789            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12790            return false;
12791        }
12792        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12793        if (retCode < 0) {
12794            Slog.w(TAG, "Couldn't remove cache files for package: "
12795                       + packageName + " u" + userId);
12796            return false;
12797        }
12798        return true;
12799    }
12800
12801    @Override
12802    public void getPackageSizeInfo(final String packageName, int userHandle,
12803            final IPackageStatsObserver observer) {
12804        mContext.enforceCallingOrSelfPermission(
12805                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12806        if (packageName == null) {
12807            throw new IllegalArgumentException("Attempt to get size of null packageName");
12808        }
12809
12810        PackageStats stats = new PackageStats(packageName, userHandle);
12811
12812        /*
12813         * Queue up an async operation since the package measurement may take a
12814         * little while.
12815         */
12816        Message msg = mHandler.obtainMessage(INIT_COPY);
12817        msg.obj = new MeasureParams(stats, observer);
12818        mHandler.sendMessage(msg);
12819    }
12820
12821    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12822            PackageStats pStats) {
12823        if (packageName == null) {
12824            Slog.w(TAG, "Attempt to get size of null packageName.");
12825            return false;
12826        }
12827        PackageParser.Package p;
12828        boolean dataOnly = false;
12829        String libDirRoot = null;
12830        String asecPath = null;
12831        PackageSetting ps = null;
12832        synchronized (mPackages) {
12833            p = mPackages.get(packageName);
12834            ps = mSettings.mPackages.get(packageName);
12835            if(p == null) {
12836                dataOnly = true;
12837                if((ps == null) || (ps.pkg == null)) {
12838                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12839                    return false;
12840                }
12841                p = ps.pkg;
12842            }
12843            if (ps != null) {
12844                libDirRoot = ps.legacyNativeLibraryPathString;
12845            }
12846            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12847                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12848                if (secureContainerId != null) {
12849                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12850                }
12851            }
12852        }
12853        String publicSrcDir = null;
12854        if(!dataOnly) {
12855            final ApplicationInfo applicationInfo = p.applicationInfo;
12856            if (applicationInfo == null) {
12857                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12858                return false;
12859            }
12860            if (p.isForwardLocked()) {
12861                publicSrcDir = applicationInfo.getBaseResourcePath();
12862            }
12863        }
12864        // TODO: extend to measure size of split APKs
12865        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12866        // not just the first level.
12867        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12868        // just the primary.
12869        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12870        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
12871                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12872        if (res < 0) {
12873            return false;
12874        }
12875
12876        // Fix-up for forward-locked applications in ASEC containers.
12877        if (!isExternal(p)) {
12878            pStats.codeSize += pStats.externalCodeSize;
12879            pStats.externalCodeSize = 0L;
12880        }
12881
12882        return true;
12883    }
12884
12885
12886    @Override
12887    public void addPackageToPreferred(String packageName) {
12888        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12889    }
12890
12891    @Override
12892    public void removePackageFromPreferred(String packageName) {
12893        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12894    }
12895
12896    @Override
12897    public List<PackageInfo> getPreferredPackages(int flags) {
12898        return new ArrayList<PackageInfo>();
12899    }
12900
12901    private int getUidTargetSdkVersionLockedLPr(int uid) {
12902        Object obj = mSettings.getUserIdLPr(uid);
12903        if (obj instanceof SharedUserSetting) {
12904            final SharedUserSetting sus = (SharedUserSetting) obj;
12905            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12906            final Iterator<PackageSetting> it = sus.packages.iterator();
12907            while (it.hasNext()) {
12908                final PackageSetting ps = it.next();
12909                if (ps.pkg != null) {
12910                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12911                    if (v < vers) vers = v;
12912                }
12913            }
12914            return vers;
12915        } else if (obj instanceof PackageSetting) {
12916            final PackageSetting ps = (PackageSetting) obj;
12917            if (ps.pkg != null) {
12918                return ps.pkg.applicationInfo.targetSdkVersion;
12919            }
12920        }
12921        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12922    }
12923
12924    @Override
12925    public void addPreferredActivity(IntentFilter filter, int match,
12926            ComponentName[] set, ComponentName activity, int userId) {
12927        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12928                "Adding preferred");
12929    }
12930
12931    private void addPreferredActivityInternal(IntentFilter filter, int match,
12932            ComponentName[] set, ComponentName activity, boolean always, int userId,
12933            String opname) {
12934        // writer
12935        int callingUid = Binder.getCallingUid();
12936        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12937        if (filter.countActions() == 0) {
12938            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12939            return;
12940        }
12941        synchronized (mPackages) {
12942            if (mContext.checkCallingOrSelfPermission(
12943                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12944                    != PackageManager.PERMISSION_GRANTED) {
12945                if (getUidTargetSdkVersionLockedLPr(callingUid)
12946                        < Build.VERSION_CODES.FROYO) {
12947                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12948                            + callingUid);
12949                    return;
12950                }
12951                mContext.enforceCallingOrSelfPermission(
12952                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12953            }
12954
12955            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12956            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12957                    + userId + ":");
12958            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12959            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12960            scheduleWritePackageRestrictionsLocked(userId);
12961        }
12962    }
12963
12964    @Override
12965    public void replacePreferredActivity(IntentFilter filter, int match,
12966            ComponentName[] set, ComponentName activity, int userId) {
12967        if (filter.countActions() != 1) {
12968            throw new IllegalArgumentException(
12969                    "replacePreferredActivity expects filter to have only 1 action.");
12970        }
12971        if (filter.countDataAuthorities() != 0
12972                || filter.countDataPaths() != 0
12973                || filter.countDataSchemes() > 1
12974                || filter.countDataTypes() != 0) {
12975            throw new IllegalArgumentException(
12976                    "replacePreferredActivity expects filter to have no data authorities, " +
12977                    "paths, or types; and at most one scheme.");
12978        }
12979
12980        final int callingUid = Binder.getCallingUid();
12981        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12982        synchronized (mPackages) {
12983            if (mContext.checkCallingOrSelfPermission(
12984                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12985                    != PackageManager.PERMISSION_GRANTED) {
12986                if (getUidTargetSdkVersionLockedLPr(callingUid)
12987                        < Build.VERSION_CODES.FROYO) {
12988                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12989                            + Binder.getCallingUid());
12990                    return;
12991                }
12992                mContext.enforceCallingOrSelfPermission(
12993                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12994            }
12995
12996            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12997            if (pir != null) {
12998                // Get all of the existing entries that exactly match this filter.
12999                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13000                if (existing != null && existing.size() == 1) {
13001                    PreferredActivity cur = existing.get(0);
13002                    if (DEBUG_PREFERRED) {
13003                        Slog.i(TAG, "Checking replace of preferred:");
13004                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13005                        if (!cur.mPref.mAlways) {
13006                            Slog.i(TAG, "  -- CUR; not mAlways!");
13007                        } else {
13008                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13009                            Slog.i(TAG, "  -- CUR: mSet="
13010                                    + Arrays.toString(cur.mPref.mSetComponents));
13011                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13012                            Slog.i(TAG, "  -- NEW: mMatch="
13013                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13014                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13015                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13016                        }
13017                    }
13018                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13019                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13020                            && cur.mPref.sameSet(set)) {
13021                        // Setting the preferred activity to what it happens to be already
13022                        if (DEBUG_PREFERRED) {
13023                            Slog.i(TAG, "Replacing with same preferred activity "
13024                                    + cur.mPref.mShortComponent + " for user "
13025                                    + userId + ":");
13026                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13027                        }
13028                        return;
13029                    }
13030                }
13031
13032                if (existing != null) {
13033                    if (DEBUG_PREFERRED) {
13034                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13035                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13036                    }
13037                    for (int i = 0; i < existing.size(); i++) {
13038                        PreferredActivity pa = existing.get(i);
13039                        if (DEBUG_PREFERRED) {
13040                            Slog.i(TAG, "Removing existing preferred activity "
13041                                    + pa.mPref.mComponent + ":");
13042                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13043                        }
13044                        pir.removeFilter(pa);
13045                    }
13046                }
13047            }
13048            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13049                    "Replacing preferred");
13050        }
13051    }
13052
13053    @Override
13054    public void clearPackagePreferredActivities(String packageName) {
13055        final int uid = Binder.getCallingUid();
13056        // writer
13057        synchronized (mPackages) {
13058            PackageParser.Package pkg = mPackages.get(packageName);
13059            if (pkg == null || pkg.applicationInfo.uid != uid) {
13060                if (mContext.checkCallingOrSelfPermission(
13061                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13062                        != PackageManager.PERMISSION_GRANTED) {
13063                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13064                            < Build.VERSION_CODES.FROYO) {
13065                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13066                                + Binder.getCallingUid());
13067                        return;
13068                    }
13069                    mContext.enforceCallingOrSelfPermission(
13070                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13071                }
13072            }
13073
13074            int user = UserHandle.getCallingUserId();
13075            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13076                scheduleWritePackageRestrictionsLocked(user);
13077            }
13078        }
13079    }
13080
13081    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13082    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13083        ArrayList<PreferredActivity> removed = null;
13084        boolean changed = false;
13085        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13086            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13087            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13088            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13089                continue;
13090            }
13091            Iterator<PreferredActivity> it = pir.filterIterator();
13092            while (it.hasNext()) {
13093                PreferredActivity pa = it.next();
13094                // Mark entry for removal only if it matches the package name
13095                // and the entry is of type "always".
13096                if (packageName == null ||
13097                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13098                                && pa.mPref.mAlways)) {
13099                    if (removed == null) {
13100                        removed = new ArrayList<PreferredActivity>();
13101                    }
13102                    removed.add(pa);
13103                }
13104            }
13105            if (removed != null) {
13106                for (int j=0; j<removed.size(); j++) {
13107                    PreferredActivity pa = removed.get(j);
13108                    pir.removeFilter(pa);
13109                }
13110                changed = true;
13111            }
13112        }
13113        return changed;
13114    }
13115
13116    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13117    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13118        if (userId == UserHandle.USER_ALL) {
13119            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13120                    sUserManager.getUserIds())) {
13121                for (int oneUserId : sUserManager.getUserIds()) {
13122                    scheduleWritePackageRestrictionsLocked(oneUserId);
13123                }
13124            }
13125        } else {
13126            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13127                scheduleWritePackageRestrictionsLocked(userId);
13128            }
13129        }
13130    }
13131
13132
13133    void clearDefaultBrowserIfNeeded(String packageName) {
13134        for (int oneUserId : sUserManager.getUserIds()) {
13135            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13136            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13137            if (packageName.equals(defaultBrowserPackageName)) {
13138                setDefaultBrowserPackageName(null, oneUserId);
13139            }
13140        }
13141    }
13142
13143    @Override
13144    public void resetPreferredActivities(int userId) {
13145        /* TODO: Actually use userId. Why is it being passed in? */
13146        mContext.enforceCallingOrSelfPermission(
13147                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13148        // writer
13149        synchronized (mPackages) {
13150            int user = UserHandle.getCallingUserId();
13151            clearPackagePreferredActivitiesLPw(null, user);
13152            mSettings.readDefaultPreferredAppsLPw(this, user);
13153            scheduleWritePackageRestrictionsLocked(user);
13154        }
13155    }
13156
13157    @Override
13158    public int getPreferredActivities(List<IntentFilter> outFilters,
13159            List<ComponentName> outActivities, String packageName) {
13160
13161        int num = 0;
13162        final int userId = UserHandle.getCallingUserId();
13163        // reader
13164        synchronized (mPackages) {
13165            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13166            if (pir != null) {
13167                final Iterator<PreferredActivity> it = pir.filterIterator();
13168                while (it.hasNext()) {
13169                    final PreferredActivity pa = it.next();
13170                    if (packageName == null
13171                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13172                                    && pa.mPref.mAlways)) {
13173                        if (outFilters != null) {
13174                            outFilters.add(new IntentFilter(pa));
13175                        }
13176                        if (outActivities != null) {
13177                            outActivities.add(pa.mPref.mComponent);
13178                        }
13179                    }
13180                }
13181            }
13182        }
13183
13184        return num;
13185    }
13186
13187    @Override
13188    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13189            int userId) {
13190        int callingUid = Binder.getCallingUid();
13191        if (callingUid != Process.SYSTEM_UID) {
13192            throw new SecurityException(
13193                    "addPersistentPreferredActivity can only be run by the system");
13194        }
13195        if (filter.countActions() == 0) {
13196            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13197            return;
13198        }
13199        synchronized (mPackages) {
13200            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13201                    " :");
13202            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13203            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13204                    new PersistentPreferredActivity(filter, activity));
13205            scheduleWritePackageRestrictionsLocked(userId);
13206        }
13207    }
13208
13209    @Override
13210    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13211        int callingUid = Binder.getCallingUid();
13212        if (callingUid != Process.SYSTEM_UID) {
13213            throw new SecurityException(
13214                    "clearPackagePersistentPreferredActivities can only be run by the system");
13215        }
13216        ArrayList<PersistentPreferredActivity> removed = null;
13217        boolean changed = false;
13218        synchronized (mPackages) {
13219            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13220                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13221                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13222                        .valueAt(i);
13223                if (userId != thisUserId) {
13224                    continue;
13225                }
13226                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13227                while (it.hasNext()) {
13228                    PersistentPreferredActivity ppa = it.next();
13229                    // Mark entry for removal only if it matches the package name.
13230                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13231                        if (removed == null) {
13232                            removed = new ArrayList<PersistentPreferredActivity>();
13233                        }
13234                        removed.add(ppa);
13235                    }
13236                }
13237                if (removed != null) {
13238                    for (int j=0; j<removed.size(); j++) {
13239                        PersistentPreferredActivity ppa = removed.get(j);
13240                        ppir.removeFilter(ppa);
13241                    }
13242                    changed = true;
13243                }
13244            }
13245
13246            if (changed) {
13247                scheduleWritePackageRestrictionsLocked(userId);
13248            }
13249        }
13250    }
13251
13252    /**
13253     * Non-Binder method, support for the backup/restore mechanism: write the
13254     * full set of preferred activities in its canonical XML format.  Returns true
13255     * on success; false otherwise.
13256     */
13257    @Override
13258    public byte[] getPreferredActivityBackup(int userId) {
13259        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13260            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13261        }
13262
13263        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13264        try {
13265            final XmlSerializer serializer = new FastXmlSerializer();
13266            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13267            serializer.startDocument(null, true);
13268            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13269
13270            synchronized (mPackages) {
13271                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13272            }
13273
13274            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13275            serializer.endDocument();
13276            serializer.flush();
13277        } catch (Exception e) {
13278            if (DEBUG_BACKUP) {
13279                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13280            }
13281            return null;
13282        }
13283
13284        return dataStream.toByteArray();
13285    }
13286
13287    @Override
13288    public void restorePreferredActivities(byte[] backup, int userId) {
13289        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13290            throw new SecurityException("Only the system may call restorePreferredActivities()");
13291        }
13292
13293        try {
13294            final XmlPullParser parser = Xml.newPullParser();
13295            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13296
13297            int type;
13298            while ((type = parser.next()) != XmlPullParser.START_TAG
13299                    && type != XmlPullParser.END_DOCUMENT) {
13300            }
13301            if (type != XmlPullParser.START_TAG) {
13302                // oops didn't find a start tag?!
13303                if (DEBUG_BACKUP) {
13304                    Slog.e(TAG, "Didn't find start tag during restore");
13305                }
13306                return;
13307            }
13308
13309            // this is supposed to be TAG_PREFERRED_BACKUP
13310            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
13311                if (DEBUG_BACKUP) {
13312                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
13313                }
13314                return;
13315            }
13316
13317            // skip interfering stuff, then we're aligned with the backing implementation
13318            while ((type = parser.next()) == XmlPullParser.TEXT) { }
13319            synchronized (mPackages) {
13320                mSettings.readPreferredActivitiesLPw(parser, userId);
13321            }
13322        } catch (Exception e) {
13323            if (DEBUG_BACKUP) {
13324                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13325            }
13326        }
13327    }
13328
13329    @Override
13330    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13331            int sourceUserId, int targetUserId, int flags) {
13332        mContext.enforceCallingOrSelfPermission(
13333                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13334        int callingUid = Binder.getCallingUid();
13335        enforceOwnerRights(ownerPackage, callingUid);
13336        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13337        if (intentFilter.countActions() == 0) {
13338            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13339            return;
13340        }
13341        synchronized (mPackages) {
13342            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13343                    ownerPackage, targetUserId, flags);
13344            CrossProfileIntentResolver resolver =
13345                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13346            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13347            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13348            if (existing != null) {
13349                int size = existing.size();
13350                for (int i = 0; i < size; i++) {
13351                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13352                        return;
13353                    }
13354                }
13355            }
13356            resolver.addFilter(newFilter);
13357            scheduleWritePackageRestrictionsLocked(sourceUserId);
13358        }
13359    }
13360
13361    @Override
13362    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13363        mContext.enforceCallingOrSelfPermission(
13364                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13365        int callingUid = Binder.getCallingUid();
13366        enforceOwnerRights(ownerPackage, callingUid);
13367        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13368        synchronized (mPackages) {
13369            CrossProfileIntentResolver resolver =
13370                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13371            ArraySet<CrossProfileIntentFilter> set =
13372                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13373            for (CrossProfileIntentFilter filter : set) {
13374                if (filter.getOwnerPackage().equals(ownerPackage)) {
13375                    resolver.removeFilter(filter);
13376                }
13377            }
13378            scheduleWritePackageRestrictionsLocked(sourceUserId);
13379        }
13380    }
13381
13382    // Enforcing that callingUid is owning pkg on userId
13383    private void enforceOwnerRights(String pkg, int callingUid) {
13384        // The system owns everything.
13385        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13386            return;
13387        }
13388        int callingUserId = UserHandle.getUserId(callingUid);
13389        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13390        if (pi == null) {
13391            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13392                    + callingUserId);
13393        }
13394        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13395            throw new SecurityException("Calling uid " + callingUid
13396                    + " does not own package " + pkg);
13397        }
13398    }
13399
13400    @Override
13401    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13402        Intent intent = new Intent(Intent.ACTION_MAIN);
13403        intent.addCategory(Intent.CATEGORY_HOME);
13404
13405        final int callingUserId = UserHandle.getCallingUserId();
13406        List<ResolveInfo> list = queryIntentActivities(intent, null,
13407                PackageManager.GET_META_DATA, callingUserId);
13408        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13409                true, false, false, callingUserId);
13410
13411        allHomeCandidates.clear();
13412        if (list != null) {
13413            for (ResolveInfo ri : list) {
13414                allHomeCandidates.add(ri);
13415            }
13416        }
13417        return (preferred == null || preferred.activityInfo == null)
13418                ? null
13419                : new ComponentName(preferred.activityInfo.packageName,
13420                        preferred.activityInfo.name);
13421    }
13422
13423    @Override
13424    public void setApplicationEnabledSetting(String appPackageName,
13425            int newState, int flags, int userId, String callingPackage) {
13426        if (!sUserManager.exists(userId)) return;
13427        if (callingPackage == null) {
13428            callingPackage = Integer.toString(Binder.getCallingUid());
13429        }
13430        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13431    }
13432
13433    @Override
13434    public void setComponentEnabledSetting(ComponentName componentName,
13435            int newState, int flags, int userId) {
13436        if (!sUserManager.exists(userId)) return;
13437        setEnabledSetting(componentName.getPackageName(),
13438                componentName.getClassName(), newState, flags, userId, null);
13439    }
13440
13441    private void setEnabledSetting(final String packageName, String className, int newState,
13442            final int flags, int userId, String callingPackage) {
13443        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13444              || newState == COMPONENT_ENABLED_STATE_ENABLED
13445              || newState == COMPONENT_ENABLED_STATE_DISABLED
13446              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13447              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13448            throw new IllegalArgumentException("Invalid new component state: "
13449                    + newState);
13450        }
13451        PackageSetting pkgSetting;
13452        final int uid = Binder.getCallingUid();
13453        final int permission = mContext.checkCallingOrSelfPermission(
13454                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13455        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13456        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13457        boolean sendNow = false;
13458        boolean isApp = (className == null);
13459        String componentName = isApp ? packageName : className;
13460        int packageUid = -1;
13461        ArrayList<String> components;
13462
13463        // writer
13464        synchronized (mPackages) {
13465            pkgSetting = mSettings.mPackages.get(packageName);
13466            if (pkgSetting == null) {
13467                if (className == null) {
13468                    throw new IllegalArgumentException(
13469                            "Unknown package: " + packageName);
13470                }
13471                throw new IllegalArgumentException(
13472                        "Unknown component: " + packageName
13473                        + "/" + className);
13474            }
13475            // Allow root and verify that userId is not being specified by a different user
13476            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13477                throw new SecurityException(
13478                        "Permission Denial: attempt to change component state from pid="
13479                        + Binder.getCallingPid()
13480                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13481            }
13482            if (className == null) {
13483                // We're dealing with an application/package level state change
13484                if (pkgSetting.getEnabled(userId) == newState) {
13485                    // Nothing to do
13486                    return;
13487                }
13488                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13489                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13490                    // Don't care about who enables an app.
13491                    callingPackage = null;
13492                }
13493                pkgSetting.setEnabled(newState, userId, callingPackage);
13494                // pkgSetting.pkg.mSetEnabled = newState;
13495            } else {
13496                // We're dealing with a component level state change
13497                // First, verify that this is a valid class name.
13498                PackageParser.Package pkg = pkgSetting.pkg;
13499                if (pkg == null || !pkg.hasComponentClassName(className)) {
13500                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13501                        throw new IllegalArgumentException("Component class " + className
13502                                + " does not exist in " + packageName);
13503                    } else {
13504                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13505                                + className + " does not exist in " + packageName);
13506                    }
13507                }
13508                switch (newState) {
13509                case COMPONENT_ENABLED_STATE_ENABLED:
13510                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13511                        return;
13512                    }
13513                    break;
13514                case COMPONENT_ENABLED_STATE_DISABLED:
13515                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13516                        return;
13517                    }
13518                    break;
13519                case COMPONENT_ENABLED_STATE_DEFAULT:
13520                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13521                        return;
13522                    }
13523                    break;
13524                default:
13525                    Slog.e(TAG, "Invalid new component state: " + newState);
13526                    return;
13527                }
13528            }
13529            scheduleWritePackageRestrictionsLocked(userId);
13530            components = mPendingBroadcasts.get(userId, packageName);
13531            final boolean newPackage = components == null;
13532            if (newPackage) {
13533                components = new ArrayList<String>();
13534            }
13535            if (!components.contains(componentName)) {
13536                components.add(componentName);
13537            }
13538            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13539                sendNow = true;
13540                // Purge entry from pending broadcast list if another one exists already
13541                // since we are sending one right away.
13542                mPendingBroadcasts.remove(userId, packageName);
13543            } else {
13544                if (newPackage) {
13545                    mPendingBroadcasts.put(userId, packageName, components);
13546                }
13547                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13548                    // Schedule a message
13549                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13550                }
13551            }
13552        }
13553
13554        long callingId = Binder.clearCallingIdentity();
13555        try {
13556            if (sendNow) {
13557                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13558                sendPackageChangedBroadcast(packageName,
13559                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13560            }
13561        } finally {
13562            Binder.restoreCallingIdentity(callingId);
13563        }
13564    }
13565
13566    private void sendPackageChangedBroadcast(String packageName,
13567            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13568        if (DEBUG_INSTALL)
13569            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13570                    + componentNames);
13571        Bundle extras = new Bundle(4);
13572        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13573        String nameList[] = new String[componentNames.size()];
13574        componentNames.toArray(nameList);
13575        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13576        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13577        extras.putInt(Intent.EXTRA_UID, packageUid);
13578        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13579                new int[] {UserHandle.getUserId(packageUid)});
13580    }
13581
13582    @Override
13583    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13584        if (!sUserManager.exists(userId)) return;
13585        final int uid = Binder.getCallingUid();
13586        final int permission = mContext.checkCallingOrSelfPermission(
13587                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13588        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13589        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13590        // writer
13591        synchronized (mPackages) {
13592            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13593                    allowedByPermission, uid, userId)) {
13594                scheduleWritePackageRestrictionsLocked(userId);
13595            }
13596        }
13597    }
13598
13599    @Override
13600    public String getInstallerPackageName(String packageName) {
13601        // reader
13602        synchronized (mPackages) {
13603            return mSettings.getInstallerPackageNameLPr(packageName);
13604        }
13605    }
13606
13607    @Override
13608    public int getApplicationEnabledSetting(String packageName, int userId) {
13609        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13610        int uid = Binder.getCallingUid();
13611        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13612        // reader
13613        synchronized (mPackages) {
13614            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13615        }
13616    }
13617
13618    @Override
13619    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13620        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13621        int uid = Binder.getCallingUid();
13622        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13623        // reader
13624        synchronized (mPackages) {
13625            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13626        }
13627    }
13628
13629    @Override
13630    public void enterSafeMode() {
13631        enforceSystemOrRoot("Only the system can request entering safe mode");
13632
13633        if (!mSystemReady) {
13634            mSafeMode = true;
13635        }
13636    }
13637
13638    @Override
13639    public void systemReady() {
13640        mSystemReady = true;
13641
13642        // Read the compatibilty setting when the system is ready.
13643        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13644                mContext.getContentResolver(),
13645                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13646        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13647        if (DEBUG_SETTINGS) {
13648            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13649        }
13650
13651        synchronized (mPackages) {
13652            // Verify that all of the preferred activity components actually
13653            // exist.  It is possible for applications to be updated and at
13654            // that point remove a previously declared activity component that
13655            // had been set as a preferred activity.  We try to clean this up
13656            // the next time we encounter that preferred activity, but it is
13657            // possible for the user flow to never be able to return to that
13658            // situation so here we do a sanity check to make sure we haven't
13659            // left any junk around.
13660            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13661            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13662                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13663                removed.clear();
13664                for (PreferredActivity pa : pir.filterSet()) {
13665                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13666                        removed.add(pa);
13667                    }
13668                }
13669                if (removed.size() > 0) {
13670                    for (int r=0; r<removed.size(); r++) {
13671                        PreferredActivity pa = removed.get(r);
13672                        Slog.w(TAG, "Removing dangling preferred activity: "
13673                                + pa.mPref.mComponent);
13674                        pir.removeFilter(pa);
13675                    }
13676                    mSettings.writePackageRestrictionsLPr(
13677                            mSettings.mPreferredActivities.keyAt(i));
13678                }
13679            }
13680        }
13681        sUserManager.systemReady();
13682
13683        // Kick off any messages waiting for system ready
13684        if (mPostSystemReadyMessages != null) {
13685            for (Message msg : mPostSystemReadyMessages) {
13686                msg.sendToTarget();
13687            }
13688            mPostSystemReadyMessages = null;
13689        }
13690
13691        // Watch for external volumes that come and go over time
13692        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13693        storage.registerListener(mStorageListener);
13694
13695        mInstallerService.systemReady();
13696        mPackageDexOptimizer.systemReady();
13697    }
13698
13699    @Override
13700    public boolean isSafeMode() {
13701        return mSafeMode;
13702    }
13703
13704    @Override
13705    public boolean hasSystemUidErrors() {
13706        return mHasSystemUidErrors;
13707    }
13708
13709    static String arrayToString(int[] array) {
13710        StringBuffer buf = new StringBuffer(128);
13711        buf.append('[');
13712        if (array != null) {
13713            for (int i=0; i<array.length; i++) {
13714                if (i > 0) buf.append(", ");
13715                buf.append(array[i]);
13716            }
13717        }
13718        buf.append(']');
13719        return buf.toString();
13720    }
13721
13722    static class DumpState {
13723        public static final int DUMP_LIBS = 1 << 0;
13724        public static final int DUMP_FEATURES = 1 << 1;
13725        public static final int DUMP_RESOLVERS = 1 << 2;
13726        public static final int DUMP_PERMISSIONS = 1 << 3;
13727        public static final int DUMP_PACKAGES = 1 << 4;
13728        public static final int DUMP_SHARED_USERS = 1 << 5;
13729        public static final int DUMP_MESSAGES = 1 << 6;
13730        public static final int DUMP_PROVIDERS = 1 << 7;
13731        public static final int DUMP_VERIFIERS = 1 << 8;
13732        public static final int DUMP_PREFERRED = 1 << 9;
13733        public static final int DUMP_PREFERRED_XML = 1 << 10;
13734        public static final int DUMP_KEYSETS = 1 << 11;
13735        public static final int DUMP_VERSION = 1 << 12;
13736        public static final int DUMP_INSTALLS = 1 << 13;
13737        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13738        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13739
13740        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13741
13742        private int mTypes;
13743
13744        private int mOptions;
13745
13746        private boolean mTitlePrinted;
13747
13748        private SharedUserSetting mSharedUser;
13749
13750        public boolean isDumping(int type) {
13751            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13752                return true;
13753            }
13754
13755            return (mTypes & type) != 0;
13756        }
13757
13758        public void setDump(int type) {
13759            mTypes |= type;
13760        }
13761
13762        public boolean isOptionEnabled(int option) {
13763            return (mOptions & option) != 0;
13764        }
13765
13766        public void setOptionEnabled(int option) {
13767            mOptions |= option;
13768        }
13769
13770        public boolean onTitlePrinted() {
13771            final boolean printed = mTitlePrinted;
13772            mTitlePrinted = true;
13773            return printed;
13774        }
13775
13776        public boolean getTitlePrinted() {
13777            return mTitlePrinted;
13778        }
13779
13780        public void setTitlePrinted(boolean enabled) {
13781            mTitlePrinted = enabled;
13782        }
13783
13784        public SharedUserSetting getSharedUser() {
13785            return mSharedUser;
13786        }
13787
13788        public void setSharedUser(SharedUserSetting user) {
13789            mSharedUser = user;
13790        }
13791    }
13792
13793    @Override
13794    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13795        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13796                != PackageManager.PERMISSION_GRANTED) {
13797            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13798                    + Binder.getCallingPid()
13799                    + ", uid=" + Binder.getCallingUid()
13800                    + " without permission "
13801                    + android.Manifest.permission.DUMP);
13802            return;
13803        }
13804
13805        DumpState dumpState = new DumpState();
13806        boolean fullPreferred = false;
13807        boolean checkin = false;
13808
13809        String packageName = null;
13810
13811        int opti = 0;
13812        while (opti < args.length) {
13813            String opt = args[opti];
13814            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13815                break;
13816            }
13817            opti++;
13818
13819            if ("-a".equals(opt)) {
13820                // Right now we only know how to print all.
13821            } else if ("-h".equals(opt)) {
13822                pw.println("Package manager dump options:");
13823                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13824                pw.println("    --checkin: dump for a checkin");
13825                pw.println("    -f: print details of intent filters");
13826                pw.println("    -h: print this help");
13827                pw.println("  cmd may be one of:");
13828                pw.println("    l[ibraries]: list known shared libraries");
13829                pw.println("    f[ibraries]: list device features");
13830                pw.println("    k[eysets]: print known keysets");
13831                pw.println("    r[esolvers]: dump intent resolvers");
13832                pw.println("    perm[issions]: dump permissions");
13833                pw.println("    pref[erred]: print preferred package settings");
13834                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13835                pw.println("    prov[iders]: dump content providers");
13836                pw.println("    p[ackages]: dump installed packages");
13837                pw.println("    s[hared-users]: dump shared user IDs");
13838                pw.println("    m[essages]: print collected runtime messages");
13839                pw.println("    v[erifiers]: print package verifier info");
13840                pw.println("    version: print database version info");
13841                pw.println("    write: write current settings now");
13842                pw.println("    <package.name>: info about given package");
13843                pw.println("    installs: details about install sessions");
13844                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13845                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13846                return;
13847            } else if ("--checkin".equals(opt)) {
13848                checkin = true;
13849            } else if ("-f".equals(opt)) {
13850                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13851            } else {
13852                pw.println("Unknown argument: " + opt + "; use -h for help");
13853            }
13854        }
13855
13856        // Is the caller requesting to dump a particular piece of data?
13857        if (opti < args.length) {
13858            String cmd = args[opti];
13859            opti++;
13860            // Is this a package name?
13861            if ("android".equals(cmd) || cmd.contains(".")) {
13862                packageName = cmd;
13863                // When dumping a single package, we always dump all of its
13864                // filter information since the amount of data will be reasonable.
13865                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13866            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13867                dumpState.setDump(DumpState.DUMP_LIBS);
13868            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13869                dumpState.setDump(DumpState.DUMP_FEATURES);
13870            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13871                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13872            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13873                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13874            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13875                dumpState.setDump(DumpState.DUMP_PREFERRED);
13876            } else if ("preferred-xml".equals(cmd)) {
13877                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13878                if (opti < args.length && "--full".equals(args[opti])) {
13879                    fullPreferred = true;
13880                    opti++;
13881                }
13882            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13883                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13884            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13885                dumpState.setDump(DumpState.DUMP_PACKAGES);
13886            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13887                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13888            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13889                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13890            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13891                dumpState.setDump(DumpState.DUMP_MESSAGES);
13892            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13893                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13894            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13895                    || "intent-filter-verifiers".equals(cmd)) {
13896                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13897            } else if ("version".equals(cmd)) {
13898                dumpState.setDump(DumpState.DUMP_VERSION);
13899            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13900                dumpState.setDump(DumpState.DUMP_KEYSETS);
13901            } else if ("installs".equals(cmd)) {
13902                dumpState.setDump(DumpState.DUMP_INSTALLS);
13903            } else if ("write".equals(cmd)) {
13904                synchronized (mPackages) {
13905                    mSettings.writeLPr();
13906                    pw.println("Settings written.");
13907                    return;
13908                }
13909            }
13910        }
13911
13912        if (checkin) {
13913            pw.println("vers,1");
13914        }
13915
13916        // reader
13917        synchronized (mPackages) {
13918            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13919                if (!checkin) {
13920                    if (dumpState.onTitlePrinted())
13921                        pw.println();
13922                    pw.println("Database versions:");
13923                    pw.print("  SDK Version:");
13924                    pw.print(" internal=");
13925                    pw.print(mSettings.mInternalSdkPlatform);
13926                    pw.print(" external=");
13927                    pw.println(mSettings.mExternalSdkPlatform);
13928                    pw.print("  DB Version:");
13929                    pw.print(" internal=");
13930                    pw.print(mSettings.mInternalDatabaseVersion);
13931                    pw.print(" external=");
13932                    pw.println(mSettings.mExternalDatabaseVersion);
13933                }
13934            }
13935
13936            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13937                if (!checkin) {
13938                    if (dumpState.onTitlePrinted())
13939                        pw.println();
13940                    pw.println("Verifiers:");
13941                    pw.print("  Required: ");
13942                    pw.print(mRequiredVerifierPackage);
13943                    pw.print(" (uid=");
13944                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13945                    pw.println(")");
13946                } else if (mRequiredVerifierPackage != null) {
13947                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13948                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13949                }
13950            }
13951
13952            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13953                    packageName == null) {
13954                if (mIntentFilterVerifierComponent != null) {
13955                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13956                    if (!checkin) {
13957                        if (dumpState.onTitlePrinted())
13958                            pw.println();
13959                        pw.println("Intent Filter Verifier:");
13960                        pw.print("  Using: ");
13961                        pw.print(verifierPackageName);
13962                        pw.print(" (uid=");
13963                        pw.print(getPackageUid(verifierPackageName, 0));
13964                        pw.println(")");
13965                    } else if (verifierPackageName != null) {
13966                        pw.print("ifv,"); pw.print(verifierPackageName);
13967                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13968                    }
13969                } else {
13970                    pw.println();
13971                    pw.println("No Intent Filter Verifier available!");
13972                }
13973            }
13974
13975            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13976                boolean printedHeader = false;
13977                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13978                while (it.hasNext()) {
13979                    String name = it.next();
13980                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13981                    if (!checkin) {
13982                        if (!printedHeader) {
13983                            if (dumpState.onTitlePrinted())
13984                                pw.println();
13985                            pw.println("Libraries:");
13986                            printedHeader = true;
13987                        }
13988                        pw.print("  ");
13989                    } else {
13990                        pw.print("lib,");
13991                    }
13992                    pw.print(name);
13993                    if (!checkin) {
13994                        pw.print(" -> ");
13995                    }
13996                    if (ent.path != null) {
13997                        if (!checkin) {
13998                            pw.print("(jar) ");
13999                            pw.print(ent.path);
14000                        } else {
14001                            pw.print(",jar,");
14002                            pw.print(ent.path);
14003                        }
14004                    } else {
14005                        if (!checkin) {
14006                            pw.print("(apk) ");
14007                            pw.print(ent.apk);
14008                        } else {
14009                            pw.print(",apk,");
14010                            pw.print(ent.apk);
14011                        }
14012                    }
14013                    pw.println();
14014                }
14015            }
14016
14017            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14018                if (dumpState.onTitlePrinted())
14019                    pw.println();
14020                if (!checkin) {
14021                    pw.println("Features:");
14022                }
14023                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14024                while (it.hasNext()) {
14025                    String name = it.next();
14026                    if (!checkin) {
14027                        pw.print("  ");
14028                    } else {
14029                        pw.print("feat,");
14030                    }
14031                    pw.println(name);
14032                }
14033            }
14034
14035            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14036                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14037                        : "Activity Resolver Table:", "  ", packageName,
14038                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14039                    dumpState.setTitlePrinted(true);
14040                }
14041                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14042                        : "Receiver Resolver Table:", "  ", packageName,
14043                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14044                    dumpState.setTitlePrinted(true);
14045                }
14046                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14047                        : "Service Resolver Table:", "  ", packageName,
14048                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14049                    dumpState.setTitlePrinted(true);
14050                }
14051                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14052                        : "Provider Resolver Table:", "  ", packageName,
14053                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14054                    dumpState.setTitlePrinted(true);
14055                }
14056            }
14057
14058            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14059                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14060                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14061                    int user = mSettings.mPreferredActivities.keyAt(i);
14062                    if (pir.dump(pw,
14063                            dumpState.getTitlePrinted()
14064                                ? "\nPreferred Activities User " + user + ":"
14065                                : "Preferred Activities User " + user + ":", "  ",
14066                            packageName, true, false)) {
14067                        dumpState.setTitlePrinted(true);
14068                    }
14069                }
14070            }
14071
14072            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14073                pw.flush();
14074                FileOutputStream fout = new FileOutputStream(fd);
14075                BufferedOutputStream str = new BufferedOutputStream(fout);
14076                XmlSerializer serializer = new FastXmlSerializer();
14077                try {
14078                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14079                    serializer.startDocument(null, true);
14080                    serializer.setFeature(
14081                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14082                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14083                    serializer.endDocument();
14084                    serializer.flush();
14085                } catch (IllegalArgumentException e) {
14086                    pw.println("Failed writing: " + e);
14087                } catch (IllegalStateException e) {
14088                    pw.println("Failed writing: " + e);
14089                } catch (IOException e) {
14090                    pw.println("Failed writing: " + e);
14091                }
14092            }
14093
14094            if (!checkin
14095                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14096                    && packageName == null) {
14097                pw.println();
14098                int count = mSettings.mPackages.size();
14099                if (count == 0) {
14100                    pw.println("No domain preferred apps!");
14101                    pw.println();
14102                } else {
14103                    final String prefix = "  ";
14104                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14105                    if (allPackageSettings.size() == 0) {
14106                        pw.println("No domain preferred apps!");
14107                        pw.println();
14108                    } else {
14109                        pw.println("Domain preferred apps status:");
14110                        pw.println();
14111                        count = 0;
14112                        for (PackageSetting ps : allPackageSettings) {
14113                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14114                            if (ivi == null || ivi.getPackageName() == null) continue;
14115                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14116                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14117                            pw.println(prefix + "Status: " + ivi.getStatusString());
14118                            pw.println();
14119                            count++;
14120                        }
14121                        if (count == 0) {
14122                            pw.println(prefix + "No domain preferred app status!");
14123                            pw.println();
14124                        }
14125                        for (int userId : sUserManager.getUserIds()) {
14126                            pw.println("Domain preferred apps for User " + userId + ":");
14127                            pw.println();
14128                            count = 0;
14129                            for (PackageSetting ps : allPackageSettings) {
14130                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14131                                if (ivi == null || ivi.getPackageName() == null) {
14132                                    continue;
14133                                }
14134                                final int status = ps.getDomainVerificationStatusForUser(userId);
14135                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14136                                    continue;
14137                                }
14138                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14139                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14140                                String statusStr = IntentFilterVerificationInfo.
14141                                        getStatusStringFromValue(status);
14142                                pw.println(prefix + "Status: " + statusStr);
14143                                pw.println();
14144                                count++;
14145                            }
14146                            if (count == 0) {
14147                                pw.println(prefix + "No domain preferred apps!");
14148                                pw.println();
14149                            }
14150                        }
14151                    }
14152                }
14153            }
14154
14155            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14156                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
14157                if (packageName == null) {
14158                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14159                        if (iperm == 0) {
14160                            if (dumpState.onTitlePrinted())
14161                                pw.println();
14162                            pw.println("AppOp Permissions:");
14163                        }
14164                        pw.print("  AppOp Permission ");
14165                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14166                        pw.println(":");
14167                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14168                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14169                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14170                        }
14171                    }
14172                }
14173            }
14174
14175            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14176                boolean printedSomething = false;
14177                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14178                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14179                        continue;
14180                    }
14181                    if (!printedSomething) {
14182                        if (dumpState.onTitlePrinted())
14183                            pw.println();
14184                        pw.println("Registered ContentProviders:");
14185                        printedSomething = true;
14186                    }
14187                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14188                    pw.print("    "); pw.println(p.toString());
14189                }
14190                printedSomething = false;
14191                for (Map.Entry<String, PackageParser.Provider> entry :
14192                        mProvidersByAuthority.entrySet()) {
14193                    PackageParser.Provider p = entry.getValue();
14194                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14195                        continue;
14196                    }
14197                    if (!printedSomething) {
14198                        if (dumpState.onTitlePrinted())
14199                            pw.println();
14200                        pw.println("ContentProvider Authorities:");
14201                        printedSomething = true;
14202                    }
14203                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14204                    pw.print("    "); pw.println(p.toString());
14205                    if (p.info != null && p.info.applicationInfo != null) {
14206                        final String appInfo = p.info.applicationInfo.toString();
14207                        pw.print("      applicationInfo="); pw.println(appInfo);
14208                    }
14209                }
14210            }
14211
14212            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14213                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14214            }
14215
14216            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14217                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
14218            }
14219
14220            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14221                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
14222            }
14223
14224            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14225                // XXX should handle packageName != null by dumping only install data that
14226                // the given package is involved with.
14227                if (dumpState.onTitlePrinted()) pw.println();
14228                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14229            }
14230
14231            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14232                if (dumpState.onTitlePrinted()) pw.println();
14233                mSettings.dumpReadMessagesLPr(pw, dumpState);
14234
14235                pw.println();
14236                pw.println("Package warning messages:");
14237                BufferedReader in = null;
14238                String line = null;
14239                try {
14240                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14241                    while ((line = in.readLine()) != null) {
14242                        if (line.contains("ignored: updated version")) continue;
14243                        pw.println(line);
14244                    }
14245                } catch (IOException ignored) {
14246                } finally {
14247                    IoUtils.closeQuietly(in);
14248                }
14249            }
14250
14251            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14252                BufferedReader in = null;
14253                String line = null;
14254                try {
14255                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14256                    while ((line = in.readLine()) != null) {
14257                        if (line.contains("ignored: updated version")) continue;
14258                        pw.print("msg,");
14259                        pw.println(line);
14260                    }
14261                } catch (IOException ignored) {
14262                } finally {
14263                    IoUtils.closeQuietly(in);
14264                }
14265            }
14266        }
14267    }
14268
14269    // ------- apps on sdcard specific code -------
14270    static final boolean DEBUG_SD_INSTALL = false;
14271
14272    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14273
14274    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14275
14276    private boolean mMediaMounted = false;
14277
14278    static String getEncryptKey() {
14279        try {
14280            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14281                    SD_ENCRYPTION_KEYSTORE_NAME);
14282            if (sdEncKey == null) {
14283                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14284                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14285                if (sdEncKey == null) {
14286                    Slog.e(TAG, "Failed to create encryption keys");
14287                    return null;
14288                }
14289            }
14290            return sdEncKey;
14291        } catch (NoSuchAlgorithmException nsae) {
14292            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14293            return null;
14294        } catch (IOException ioe) {
14295            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14296            return null;
14297        }
14298    }
14299
14300    /*
14301     * Update media status on PackageManager.
14302     */
14303    @Override
14304    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14305        int callingUid = Binder.getCallingUid();
14306        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14307            throw new SecurityException("Media status can only be updated by the system");
14308        }
14309        // reader; this apparently protects mMediaMounted, but should probably
14310        // be a different lock in that case.
14311        synchronized (mPackages) {
14312            Log.i(TAG, "Updating external media status from "
14313                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14314                    + (mediaStatus ? "mounted" : "unmounted"));
14315            if (DEBUG_SD_INSTALL)
14316                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14317                        + ", mMediaMounted=" + mMediaMounted);
14318            if (mediaStatus == mMediaMounted) {
14319                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14320                        : 0, -1);
14321                mHandler.sendMessage(msg);
14322                return;
14323            }
14324            mMediaMounted = mediaStatus;
14325        }
14326        // Queue up an async operation since the package installation may take a
14327        // little while.
14328        mHandler.post(new Runnable() {
14329            public void run() {
14330                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14331            }
14332        });
14333    }
14334
14335    /**
14336     * Called by MountService when the initial ASECs to scan are available.
14337     * Should block until all the ASEC containers are finished being scanned.
14338     */
14339    public void scanAvailableAsecs() {
14340        updateExternalMediaStatusInner(true, false, false);
14341        if (mShouldRestoreconData) {
14342            SELinuxMMAC.setRestoreconDone();
14343            mShouldRestoreconData = false;
14344        }
14345    }
14346
14347    /*
14348     * Collect information of applications on external media, map them against
14349     * existing containers and update information based on current mount status.
14350     * Please note that we always have to report status if reportStatus has been
14351     * set to true especially when unloading packages.
14352     */
14353    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14354            boolean externalStorage) {
14355        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14356        int[] uidArr = EmptyArray.INT;
14357
14358        final String[] list = PackageHelper.getSecureContainerList();
14359        if (ArrayUtils.isEmpty(list)) {
14360            Log.i(TAG, "No secure containers found");
14361        } else {
14362            // Process list of secure containers and categorize them
14363            // as active or stale based on their package internal state.
14364
14365            // reader
14366            synchronized (mPackages) {
14367                for (String cid : list) {
14368                    // Leave stages untouched for now; installer service owns them
14369                    if (PackageInstallerService.isStageName(cid)) continue;
14370
14371                    if (DEBUG_SD_INSTALL)
14372                        Log.i(TAG, "Processing container " + cid);
14373                    String pkgName = getAsecPackageName(cid);
14374                    if (pkgName == null) {
14375                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14376                        continue;
14377                    }
14378                    if (DEBUG_SD_INSTALL)
14379                        Log.i(TAG, "Looking for pkg : " + pkgName);
14380
14381                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14382                    if (ps == null) {
14383                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14384                        continue;
14385                    }
14386
14387                    /*
14388                     * Skip packages that are not external if we're unmounting
14389                     * external storage.
14390                     */
14391                    if (externalStorage && !isMounted && !isExternal(ps)) {
14392                        continue;
14393                    }
14394
14395                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14396                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14397                    // The package status is changed only if the code path
14398                    // matches between settings and the container id.
14399                    if (ps.codePathString != null
14400                            && ps.codePathString.startsWith(args.getCodePath())) {
14401                        if (DEBUG_SD_INSTALL) {
14402                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14403                                    + " at code path: " + ps.codePathString);
14404                        }
14405
14406                        // We do have a valid package installed on sdcard
14407                        processCids.put(args, ps.codePathString);
14408                        final int uid = ps.appId;
14409                        if (uid != -1) {
14410                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14411                        }
14412                    } else {
14413                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14414                                + ps.codePathString);
14415                    }
14416                }
14417            }
14418
14419            Arrays.sort(uidArr);
14420        }
14421
14422        // Process packages with valid entries.
14423        if (isMounted) {
14424            if (DEBUG_SD_INSTALL)
14425                Log.i(TAG, "Loading packages");
14426            loadMediaPackages(processCids, uidArr);
14427            startCleaningPackages();
14428            mInstallerService.onSecureContainersAvailable();
14429        } else {
14430            if (DEBUG_SD_INSTALL)
14431                Log.i(TAG, "Unloading packages");
14432            unloadMediaPackages(processCids, uidArr, reportStatus);
14433        }
14434    }
14435
14436    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14437            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14438        final int size = infos.size();
14439        final String[] packageNames = new String[size];
14440        final int[] packageUids = new int[size];
14441        for (int i = 0; i < size; i++) {
14442            final ApplicationInfo info = infos.get(i);
14443            packageNames[i] = info.packageName;
14444            packageUids[i] = info.uid;
14445        }
14446        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14447                finishedReceiver);
14448    }
14449
14450    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14451            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14452        sendResourcesChangedBroadcast(mediaStatus, replacing,
14453                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14454    }
14455
14456    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14457            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14458        int size = pkgList.length;
14459        if (size > 0) {
14460            // Send broadcasts here
14461            Bundle extras = new Bundle();
14462            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14463            if (uidArr != null) {
14464                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14465            }
14466            if (replacing) {
14467                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14468            }
14469            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14470                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14471            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14472        }
14473    }
14474
14475   /*
14476     * Look at potentially valid container ids from processCids If package
14477     * information doesn't match the one on record or package scanning fails,
14478     * the cid is added to list of removeCids. We currently don't delete stale
14479     * containers.
14480     */
14481    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14482        ArrayList<String> pkgList = new ArrayList<String>();
14483        Set<AsecInstallArgs> keys = processCids.keySet();
14484
14485        for (AsecInstallArgs args : keys) {
14486            String codePath = processCids.get(args);
14487            if (DEBUG_SD_INSTALL)
14488                Log.i(TAG, "Loading container : " + args.cid);
14489            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14490            try {
14491                // Make sure there are no container errors first.
14492                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14493                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14494                            + " when installing from sdcard");
14495                    continue;
14496                }
14497                // Check code path here.
14498                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14499                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14500                            + " does not match one in settings " + codePath);
14501                    continue;
14502                }
14503                // Parse package
14504                int parseFlags = mDefParseFlags;
14505                if (args.isExternalAsec()) {
14506                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14507                }
14508                if (args.isFwdLocked()) {
14509                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14510                }
14511
14512                synchronized (mInstallLock) {
14513                    PackageParser.Package pkg = null;
14514                    try {
14515                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14516                    } catch (PackageManagerException e) {
14517                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14518                    }
14519                    // Scan the package
14520                    if (pkg != null) {
14521                        /*
14522                         * TODO why is the lock being held? doPostInstall is
14523                         * called in other places without the lock. This needs
14524                         * to be straightened out.
14525                         */
14526                        // writer
14527                        synchronized (mPackages) {
14528                            retCode = PackageManager.INSTALL_SUCCEEDED;
14529                            pkgList.add(pkg.packageName);
14530                            // Post process args
14531                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14532                                    pkg.applicationInfo.uid);
14533                        }
14534                    } else {
14535                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14536                    }
14537                }
14538
14539            } finally {
14540                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14541                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14542                }
14543            }
14544        }
14545        // writer
14546        synchronized (mPackages) {
14547            // If the platform SDK has changed since the last time we booted,
14548            // we need to re-grant app permission to catch any new ones that
14549            // appear. This is really a hack, and means that apps can in some
14550            // cases get permissions that the user didn't initially explicitly
14551            // allow... it would be nice to have some better way to handle
14552            // this situation.
14553            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14554            if (regrantPermissions)
14555                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14556                        + mSdkVersion + "; regranting permissions for external storage");
14557            mSettings.mExternalSdkPlatform = mSdkVersion;
14558
14559            // Make sure group IDs have been assigned, and any permission
14560            // changes in other apps are accounted for
14561            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14562                    | (regrantPermissions
14563                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14564                            : 0));
14565
14566            mSettings.updateExternalDatabaseVersion();
14567
14568            // can downgrade to reader
14569            // Persist settings
14570            mSettings.writeLPr();
14571        }
14572        // Send a broadcast to let everyone know we are done processing
14573        if (pkgList.size() > 0) {
14574            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14575        }
14576    }
14577
14578   /*
14579     * Utility method to unload a list of specified containers
14580     */
14581    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14582        // Just unmount all valid containers.
14583        for (AsecInstallArgs arg : cidArgs) {
14584            synchronized (mInstallLock) {
14585                arg.doPostDeleteLI(false);
14586           }
14587       }
14588   }
14589
14590    /*
14591     * Unload packages mounted on external media. This involves deleting package
14592     * data from internal structures, sending broadcasts about diabled packages,
14593     * gc'ing to free up references, unmounting all secure containers
14594     * corresponding to packages on external media, and posting a
14595     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14596     * that we always have to post this message if status has been requested no
14597     * matter what.
14598     */
14599    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14600            final boolean reportStatus) {
14601        if (DEBUG_SD_INSTALL)
14602            Log.i(TAG, "unloading media packages");
14603        ArrayList<String> pkgList = new ArrayList<String>();
14604        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14605        final Set<AsecInstallArgs> keys = processCids.keySet();
14606        for (AsecInstallArgs args : keys) {
14607            String pkgName = args.getPackageName();
14608            if (DEBUG_SD_INSTALL)
14609                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14610            // Delete package internally
14611            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14612            synchronized (mInstallLock) {
14613                boolean res = deletePackageLI(pkgName, null, false, null, null,
14614                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14615                if (res) {
14616                    pkgList.add(pkgName);
14617                } else {
14618                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14619                    failedList.add(args);
14620                }
14621            }
14622        }
14623
14624        // reader
14625        synchronized (mPackages) {
14626            // We didn't update the settings after removing each package;
14627            // write them now for all packages.
14628            mSettings.writeLPr();
14629        }
14630
14631        // We have to absolutely send UPDATED_MEDIA_STATUS only
14632        // after confirming that all the receivers processed the ordered
14633        // broadcast when packages get disabled, force a gc to clean things up.
14634        // and unload all the containers.
14635        if (pkgList.size() > 0) {
14636            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14637                    new IIntentReceiver.Stub() {
14638                public void performReceive(Intent intent, int resultCode, String data,
14639                        Bundle extras, boolean ordered, boolean sticky,
14640                        int sendingUser) throws RemoteException {
14641                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14642                            reportStatus ? 1 : 0, 1, keys);
14643                    mHandler.sendMessage(msg);
14644                }
14645            });
14646        } else {
14647            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14648                    keys);
14649            mHandler.sendMessage(msg);
14650        }
14651    }
14652
14653    private void loadPrivatePackages(VolumeInfo vol) {
14654        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14655        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14656        synchronized (mInstallLock) {
14657        synchronized (mPackages) {
14658            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14659            for (PackageSetting ps : packages) {
14660                final PackageParser.Package pkg;
14661                try {
14662                    pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14663                    loaded.add(pkg.applicationInfo);
14664                } catch (PackageManagerException e) {
14665                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14666                }
14667            }
14668
14669            // TODO: regrant any permissions that changed based since original install
14670
14671            mSettings.writeLPr();
14672        }
14673        }
14674
14675        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
14676        sendResourcesChangedBroadcast(true, false, loaded, null);
14677    }
14678
14679    private void unloadPrivatePackages(VolumeInfo vol) {
14680        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14681        synchronized (mInstallLock) {
14682        synchronized (mPackages) {
14683            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14684            for (PackageSetting ps : packages) {
14685                if (ps.pkg == null) continue;
14686
14687                final ApplicationInfo info = ps.pkg.applicationInfo;
14688                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14689                if (deletePackageLI(ps.name, null, false, null, null,
14690                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14691                    unloaded.add(info);
14692                } else {
14693                    Slog.w(TAG, "Failed to unload " + ps.codePath);
14694                }
14695            }
14696
14697            mSettings.writeLPr();
14698        }
14699        }
14700
14701        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
14702        sendResourcesChangedBroadcast(false, false, unloaded, null);
14703    }
14704
14705    private void unfreezePackage(String packageName) {
14706        synchronized (mPackages) {
14707            final PackageSetting ps = mSettings.mPackages.get(packageName);
14708            if (ps != null) {
14709                ps.frozen = false;
14710            }
14711        }
14712    }
14713
14714    @Override
14715    public int movePackage(final String packageName, final String volumeUuid) {
14716        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14717
14718        final int moveId = mNextMoveId.getAndIncrement();
14719        try {
14720            movePackageInternal(packageName, volumeUuid, moveId);
14721        } catch (PackageManagerException e) {
14722            Slog.w(TAG, "Failed to move " + packageName, e);
14723            mMoveCallbacks.notifyStatusChanged(moveId,
14724                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14725        }
14726        return moveId;
14727    }
14728
14729    private void movePackageInternal(final String packageName, final String volumeUuid,
14730            final int moveId) throws PackageManagerException {
14731        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14732        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14733        final PackageManager pm = mContext.getPackageManager();
14734
14735        final boolean currentAsec;
14736        final String currentVolumeUuid;
14737        final File codeFile;
14738        final String installerPackageName;
14739        final String packageAbiOverride;
14740        final int appId;
14741        final String seinfo;
14742        final String label;
14743
14744        // reader
14745        synchronized (mPackages) {
14746            final PackageParser.Package pkg = mPackages.get(packageName);
14747            final PackageSetting ps = mSettings.mPackages.get(packageName);
14748            if (pkg == null || ps == null) {
14749                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14750            }
14751
14752            if (pkg.applicationInfo.isSystemApp()) {
14753                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14754                        "Cannot move system application");
14755            }
14756
14757            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
14758                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14759                        "Package already moved to " + volumeUuid);
14760            }
14761
14762            final File probe = new File(pkg.codePath);
14763            final File probeOat = new File(probe, "oat");
14764            if (!probe.isDirectory() || !probeOat.isDirectory()) {
14765                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14766                        "Move only supported for modern cluster style installs");
14767            }
14768
14769            if (ps.frozen) {
14770                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14771                        "Failed to move already frozen package");
14772            }
14773            ps.frozen = true;
14774
14775            currentAsec = pkg.applicationInfo.isForwardLocked()
14776                    || pkg.applicationInfo.isExternalAsec();
14777            currentVolumeUuid = ps.volumeUuid;
14778            codeFile = new File(pkg.codePath);
14779            installerPackageName = ps.installerPackageName;
14780            packageAbiOverride = ps.cpuAbiOverrideString;
14781            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14782            seinfo = pkg.applicationInfo.seinfo;
14783            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
14784        }
14785
14786        // Now that we're guarded by frozen state, kill app during move
14787        killApplication(packageName, appId, "move pkg");
14788
14789        final Bundle extras = new Bundle();
14790        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
14791        extras.putString(Intent.EXTRA_TITLE, label);
14792        mMoveCallbacks.notifyCreated(moveId, extras);
14793
14794        int installFlags;
14795        final boolean moveCompleteApp;
14796        final File measurePath;
14797
14798        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
14799            installFlags = INSTALL_INTERNAL;
14800            moveCompleteApp = !currentAsec;
14801            measurePath = Environment.getDataAppDirectory(volumeUuid);
14802        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
14803            installFlags = INSTALL_EXTERNAL;
14804            moveCompleteApp = false;
14805            measurePath = storage.getPrimaryPhysicalVolume().getPath();
14806        } else {
14807            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
14808            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
14809                    || !volume.isMountedWritable()) {
14810                unfreezePackage(packageName);
14811                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14812                        "Move location not mounted private volume");
14813            }
14814
14815            Preconditions.checkState(!currentAsec);
14816
14817            installFlags = INSTALL_INTERNAL;
14818            moveCompleteApp = true;
14819            measurePath = Environment.getDataAppDirectory(volumeUuid);
14820        }
14821
14822        final PackageStats stats = new PackageStats(null, -1);
14823        synchronized (mInstaller) {
14824            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
14825                unfreezePackage(packageName);
14826                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14827                        "Failed to measure package size");
14828            }
14829        }
14830
14831        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
14832                + stats.dataSize);
14833
14834        final long startFreeBytes = measurePath.getFreeSpace();
14835        final long sizeBytes;
14836        if (moveCompleteApp) {
14837            sizeBytes = stats.codeSize + stats.dataSize;
14838        } else {
14839            sizeBytes = stats.codeSize;
14840        }
14841
14842        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
14843            unfreezePackage(packageName);
14844            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14845                    "Not enough free space to move");
14846        }
14847
14848        mMoveCallbacks.notifyStatusChanged(moveId, 10);
14849
14850        final CountDownLatch installedLatch = new CountDownLatch(1);
14851        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14852            @Override
14853            public void onUserActionRequired(Intent intent) throws RemoteException {
14854                throw new IllegalStateException();
14855            }
14856
14857            @Override
14858            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14859                    Bundle extras) throws RemoteException {
14860                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
14861                        + PackageManager.installStatusToString(returnCode, msg));
14862
14863                installedLatch.countDown();
14864
14865                // Regardless of success or failure of the move operation,
14866                // always unfreeze the package
14867                unfreezePackage(packageName);
14868
14869                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14870                switch (status) {
14871                    case PackageInstaller.STATUS_SUCCESS:
14872                        mMoveCallbacks.notifyStatusChanged(moveId,
14873                                PackageManager.MOVE_SUCCEEDED);
14874                        break;
14875                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14876                        mMoveCallbacks.notifyStatusChanged(moveId,
14877                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14878                        break;
14879                    default:
14880                        mMoveCallbacks.notifyStatusChanged(moveId,
14881                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14882                        break;
14883                }
14884            }
14885        };
14886
14887        final MoveInfo move;
14888        if (moveCompleteApp) {
14889            // Kick off a thread to report progress estimates
14890            new Thread() {
14891                @Override
14892                public void run() {
14893                    while (true) {
14894                        try {
14895                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
14896                                break;
14897                            }
14898                        } catch (InterruptedException ignored) {
14899                        }
14900
14901                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
14902                        final int progress = 10 + (int) MathUtils.constrain(
14903                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
14904                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
14905                    }
14906                }
14907            }.start();
14908
14909            final String dataAppName = codeFile.getName();
14910            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
14911                    dataAppName, appId, seinfo);
14912        } else {
14913            move = null;
14914        }
14915
14916        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14917
14918        final Message msg = mHandler.obtainMessage(INIT_COPY);
14919        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14920        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
14921                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14922        mHandler.sendMessage(msg);
14923    }
14924
14925    @Override
14926    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
14927        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14928
14929        final int realMoveId = mNextMoveId.getAndIncrement();
14930        final Bundle extras = new Bundle();
14931        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
14932        mMoveCallbacks.notifyCreated(realMoveId, extras);
14933
14934        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
14935            @Override
14936            public void onCreated(int moveId, Bundle extras) {
14937                // Ignored
14938            }
14939
14940            @Override
14941            public void onStatusChanged(int moveId, int status, long estMillis) {
14942                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
14943            }
14944        };
14945
14946        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14947        storage.setPrimaryStorageUuid(volumeUuid, callback);
14948        return realMoveId;
14949    }
14950
14951    @Override
14952    public int getMoveStatus(int moveId) {
14953        mContext.enforceCallingOrSelfPermission(
14954                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14955        return mMoveCallbacks.mLastStatus.get(moveId);
14956    }
14957
14958    @Override
14959    public void registerMoveCallback(IPackageMoveObserver callback) {
14960        mContext.enforceCallingOrSelfPermission(
14961                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14962        mMoveCallbacks.register(callback);
14963    }
14964
14965    @Override
14966    public void unregisterMoveCallback(IPackageMoveObserver callback) {
14967        mContext.enforceCallingOrSelfPermission(
14968                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14969        mMoveCallbacks.unregister(callback);
14970    }
14971
14972    @Override
14973    public boolean setInstallLocation(int loc) {
14974        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14975                null);
14976        if (getInstallLocation() == loc) {
14977            return true;
14978        }
14979        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14980                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14981            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14982                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14983            return true;
14984        }
14985        return false;
14986   }
14987
14988    @Override
14989    public int getInstallLocation() {
14990        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14991                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14992                PackageHelper.APP_INSTALL_AUTO);
14993    }
14994
14995    /** Called by UserManagerService */
14996    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14997        mDirtyUsers.remove(userHandle);
14998        mSettings.removeUserLPw(userHandle);
14999        mPendingBroadcasts.remove(userHandle);
15000        if (mInstaller != null) {
15001            // Technically, we shouldn't be doing this with the package lock
15002            // held.  However, this is very rare, and there is already so much
15003            // other disk I/O going on, that we'll let it slide for now.
15004            final StorageManager storage = StorageManager.from(mContext);
15005            final List<VolumeInfo> vols = storage.getVolumes();
15006            for (VolumeInfo vol : vols) {
15007                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
15008                    final String volumeUuid = vol.getFsUuid();
15009                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15010                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15011                }
15012            }
15013        }
15014        mUserNeedsBadging.delete(userHandle);
15015        removeUnusedPackagesLILPw(userManager, userHandle);
15016    }
15017
15018    /**
15019     * We're removing userHandle and would like to remove any downloaded packages
15020     * that are no longer in use by any other user.
15021     * @param userHandle the user being removed
15022     */
15023    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15024        final boolean DEBUG_CLEAN_APKS = false;
15025        int [] users = userManager.getUserIdsLPr();
15026        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15027        while (psit.hasNext()) {
15028            PackageSetting ps = psit.next();
15029            if (ps.pkg == null) {
15030                continue;
15031            }
15032            final String packageName = ps.pkg.packageName;
15033            // Skip over if system app
15034            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15035                continue;
15036            }
15037            if (DEBUG_CLEAN_APKS) {
15038                Slog.i(TAG, "Checking package " + packageName);
15039            }
15040            boolean keep = false;
15041            for (int i = 0; i < users.length; i++) {
15042                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15043                    keep = true;
15044                    if (DEBUG_CLEAN_APKS) {
15045                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15046                                + users[i]);
15047                    }
15048                    break;
15049                }
15050            }
15051            if (!keep) {
15052                if (DEBUG_CLEAN_APKS) {
15053                    Slog.i(TAG, "  Removing package " + packageName);
15054                }
15055                mHandler.post(new Runnable() {
15056                    public void run() {
15057                        deletePackageX(packageName, userHandle, 0);
15058                    } //end run
15059                });
15060            }
15061        }
15062    }
15063
15064    /** Called by UserManagerService */
15065    void createNewUserLILPw(int userHandle, File path) {
15066        if (mInstaller != null) {
15067            mInstaller.createUserConfig(userHandle);
15068            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
15069        }
15070    }
15071
15072    void newUserCreatedLILPw(int userHandle) {
15073        // Adding a user requires updating runtime permissions for system apps.
15074        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
15075    }
15076
15077    @Override
15078    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15079        mContext.enforceCallingOrSelfPermission(
15080                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15081                "Only package verification agents can read the verifier device identity");
15082
15083        synchronized (mPackages) {
15084            return mSettings.getVerifierDeviceIdentityLPw();
15085        }
15086    }
15087
15088    @Override
15089    public void setPermissionEnforced(String permission, boolean enforced) {
15090        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15091        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15092            synchronized (mPackages) {
15093                if (mSettings.mReadExternalStorageEnforced == null
15094                        || mSettings.mReadExternalStorageEnforced != enforced) {
15095                    mSettings.mReadExternalStorageEnforced = enforced;
15096                    mSettings.writeLPr();
15097                }
15098            }
15099            // kill any non-foreground processes so we restart them and
15100            // grant/revoke the GID.
15101            final IActivityManager am = ActivityManagerNative.getDefault();
15102            if (am != null) {
15103                final long token = Binder.clearCallingIdentity();
15104                try {
15105                    am.killProcessesBelowForeground("setPermissionEnforcement");
15106                } catch (RemoteException e) {
15107                } finally {
15108                    Binder.restoreCallingIdentity(token);
15109                }
15110            }
15111        } else {
15112            throw new IllegalArgumentException("No selective enforcement for " + permission);
15113        }
15114    }
15115
15116    @Override
15117    @Deprecated
15118    public boolean isPermissionEnforced(String permission) {
15119        return true;
15120    }
15121
15122    @Override
15123    public boolean isStorageLow() {
15124        final long token = Binder.clearCallingIdentity();
15125        try {
15126            final DeviceStorageMonitorInternal
15127                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15128            if (dsm != null) {
15129                return dsm.isMemoryLow();
15130            } else {
15131                return false;
15132            }
15133        } finally {
15134            Binder.restoreCallingIdentity(token);
15135        }
15136    }
15137
15138    @Override
15139    public IPackageInstaller getPackageInstaller() {
15140        return mInstallerService;
15141    }
15142
15143    private boolean userNeedsBadging(int userId) {
15144        int index = mUserNeedsBadging.indexOfKey(userId);
15145        if (index < 0) {
15146            final UserInfo userInfo;
15147            final long token = Binder.clearCallingIdentity();
15148            try {
15149                userInfo = sUserManager.getUserInfo(userId);
15150            } finally {
15151                Binder.restoreCallingIdentity(token);
15152            }
15153            final boolean b;
15154            if (userInfo != null && userInfo.isManagedProfile()) {
15155                b = true;
15156            } else {
15157                b = false;
15158            }
15159            mUserNeedsBadging.put(userId, b);
15160            return b;
15161        }
15162        return mUserNeedsBadging.valueAt(index);
15163    }
15164
15165    @Override
15166    public KeySet getKeySetByAlias(String packageName, String alias) {
15167        if (packageName == null || alias == null) {
15168            return null;
15169        }
15170        synchronized(mPackages) {
15171            final PackageParser.Package pkg = mPackages.get(packageName);
15172            if (pkg == null) {
15173                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15174                throw new IllegalArgumentException("Unknown package: " + packageName);
15175            }
15176            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15177            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15178        }
15179    }
15180
15181    @Override
15182    public KeySet getSigningKeySet(String packageName) {
15183        if (packageName == null) {
15184            return null;
15185        }
15186        synchronized(mPackages) {
15187            final PackageParser.Package pkg = mPackages.get(packageName);
15188            if (pkg == null) {
15189                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15190                throw new IllegalArgumentException("Unknown package: " + packageName);
15191            }
15192            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15193                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15194                throw new SecurityException("May not access signing KeySet of other apps.");
15195            }
15196            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15197            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15198        }
15199    }
15200
15201    @Override
15202    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15203        if (packageName == null || ks == null) {
15204            return false;
15205        }
15206        synchronized(mPackages) {
15207            final PackageParser.Package pkg = mPackages.get(packageName);
15208            if (pkg == null) {
15209                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15210                throw new IllegalArgumentException("Unknown package: " + packageName);
15211            }
15212            IBinder ksh = ks.getToken();
15213            if (ksh instanceof KeySetHandle) {
15214                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15215                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15216            }
15217            return false;
15218        }
15219    }
15220
15221    @Override
15222    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15223        if (packageName == null || ks == null) {
15224            return false;
15225        }
15226        synchronized(mPackages) {
15227            final PackageParser.Package pkg = mPackages.get(packageName);
15228            if (pkg == null) {
15229                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15230                throw new IllegalArgumentException("Unknown package: " + packageName);
15231            }
15232            IBinder ksh = ks.getToken();
15233            if (ksh instanceof KeySetHandle) {
15234                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15235                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15236            }
15237            return false;
15238        }
15239    }
15240
15241    public void getUsageStatsIfNoPackageUsageInfo() {
15242        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15243            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15244            if (usm == null) {
15245                throw new IllegalStateException("UsageStatsManager must be initialized");
15246            }
15247            long now = System.currentTimeMillis();
15248            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15249            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15250                String packageName = entry.getKey();
15251                PackageParser.Package pkg = mPackages.get(packageName);
15252                if (pkg == null) {
15253                    continue;
15254                }
15255                UsageStats usage = entry.getValue();
15256                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15257                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15258            }
15259        }
15260    }
15261
15262    /**
15263     * Check and throw if the given before/after packages would be considered a
15264     * downgrade.
15265     */
15266    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15267            throws PackageManagerException {
15268        if (after.versionCode < before.mVersionCode) {
15269            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15270                    "Update version code " + after.versionCode + " is older than current "
15271                    + before.mVersionCode);
15272        } else if (after.versionCode == before.mVersionCode) {
15273            if (after.baseRevisionCode < before.baseRevisionCode) {
15274                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15275                        "Update base revision code " + after.baseRevisionCode
15276                        + " is older than current " + before.baseRevisionCode);
15277            }
15278
15279            if (!ArrayUtils.isEmpty(after.splitNames)) {
15280                for (int i = 0; i < after.splitNames.length; i++) {
15281                    final String splitName = after.splitNames[i];
15282                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15283                    if (j != -1) {
15284                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15285                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15286                                    "Update split " + splitName + " revision code "
15287                                    + after.splitRevisionCodes[i] + " is older than current "
15288                                    + before.splitRevisionCodes[j]);
15289                        }
15290                    }
15291                }
15292            }
15293        }
15294    }
15295
15296    private static class MoveCallbacks extends Handler {
15297        private static final int MSG_CREATED = 1;
15298        private static final int MSG_STATUS_CHANGED = 2;
15299
15300        private final RemoteCallbackList<IPackageMoveObserver>
15301                mCallbacks = new RemoteCallbackList<>();
15302
15303        private final SparseIntArray mLastStatus = new SparseIntArray();
15304
15305        public MoveCallbacks(Looper looper) {
15306            super(looper);
15307        }
15308
15309        public void register(IPackageMoveObserver callback) {
15310            mCallbacks.register(callback);
15311        }
15312
15313        public void unregister(IPackageMoveObserver callback) {
15314            mCallbacks.unregister(callback);
15315        }
15316
15317        @Override
15318        public void handleMessage(Message msg) {
15319            final SomeArgs args = (SomeArgs) msg.obj;
15320            final int n = mCallbacks.beginBroadcast();
15321            for (int i = 0; i < n; i++) {
15322                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15323                try {
15324                    invokeCallback(callback, msg.what, args);
15325                } catch (RemoteException ignored) {
15326                }
15327            }
15328            mCallbacks.finishBroadcast();
15329            args.recycle();
15330        }
15331
15332        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15333                throws RemoteException {
15334            switch (what) {
15335                case MSG_CREATED: {
15336                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15337                    break;
15338                }
15339                case MSG_STATUS_CHANGED: {
15340                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15341                    break;
15342                }
15343            }
15344        }
15345
15346        private void notifyCreated(int moveId, Bundle extras) {
15347            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15348
15349            final SomeArgs args = SomeArgs.obtain();
15350            args.argi1 = moveId;
15351            args.arg2 = extras;
15352            obtainMessage(MSG_CREATED, args).sendToTarget();
15353        }
15354
15355        private void notifyStatusChanged(int moveId, int status) {
15356            notifyStatusChanged(moveId, status, -1);
15357        }
15358
15359        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15360            Slog.v(TAG, "Move " + moveId + " status " + status);
15361
15362            final SomeArgs args = SomeArgs.obtain();
15363            args.argi1 = moveId;
15364            args.argi2 = status;
15365            args.arg3 = estMillis;
15366            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15367
15368            synchronized (mLastStatus) {
15369                mLastStatus.put(moveId, status);
15370            }
15371        }
15372    }
15373
15374    private final class OnPermissionChangeListeners extends Handler {
15375        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
15376
15377        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
15378                new RemoteCallbackList<>();
15379
15380        public OnPermissionChangeListeners(Looper looper) {
15381            super(looper);
15382        }
15383
15384        @Override
15385        public void handleMessage(Message msg) {
15386            switch (msg.what) {
15387                case MSG_ON_PERMISSIONS_CHANGED: {
15388                    final int uid = msg.arg1;
15389                    handleOnPermissionsChanged(uid);
15390                } break;
15391            }
15392        }
15393
15394        public void addListenerLocked(IOnPermissionsChangeListener listener) {
15395            mPermissionListeners.register(listener);
15396
15397        }
15398
15399        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
15400            mPermissionListeners.unregister(listener);
15401        }
15402
15403        public void onPermissionsChanged(int uid) {
15404            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
15405                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
15406            }
15407        }
15408
15409        private void handleOnPermissionsChanged(int uid) {
15410            final int count = mPermissionListeners.beginBroadcast();
15411            try {
15412                for (int i = 0; i < count; i++) {
15413                    IOnPermissionsChangeListener callback = mPermissionListeners
15414                            .getBroadcastItem(i);
15415                    try {
15416                        callback.onPermissionsChanged(uid);
15417                    } catch (RemoteException e) {
15418                        Log.e(TAG, "Permission listener is dead", e);
15419                    }
15420                }
15421            } finally {
15422                mPermissionListeners.finishBroadcast();
15423            }
15424        }
15425    }
15426}
15427