PackageManagerService.java revision 9a0f9682a91e4000de50c2ced20506516af28342
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.PACKAGE_INFO_GID;
59import static android.os.Process.SYSTEM_UID;
60import static android.system.OsConstants.O_CREAT;
61import static android.system.OsConstants.O_RDWR;
62import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
64import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
65import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
66import static com.android.internal.util.ArrayUtils.appendInt;
67import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
68import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
70import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
71import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
72
73import android.Manifest;
74import android.app.ActivityManager;
75import android.app.ActivityManagerNative;
76import android.app.AppGlobals;
77import android.app.IActivityManager;
78import android.app.admin.IDevicePolicyManager;
79import android.app.backup.IBackupManager;
80import android.app.usage.UsageStats;
81import android.app.usage.UsageStatsManager;
82import android.content.BroadcastReceiver;
83import android.content.ComponentName;
84import android.content.Context;
85import android.content.IIntentReceiver;
86import android.content.Intent;
87import android.content.IntentFilter;
88import android.content.IntentSender;
89import android.content.IntentSender.SendIntentException;
90import android.content.ServiceConnection;
91import android.content.pm.ActivityInfo;
92import android.content.pm.ApplicationInfo;
93import android.content.pm.FeatureInfo;
94import android.content.pm.IOnPermissionsChangeListener;
95import android.content.pm.IPackageDataObserver;
96import android.content.pm.IPackageDeleteObserver;
97import android.content.pm.IPackageDeleteObserver2;
98import android.content.pm.IPackageInstallObserver2;
99import android.content.pm.IPackageInstaller;
100import android.content.pm.IPackageManager;
101import android.content.pm.IPackageMoveObserver;
102import android.content.pm.IPackageStatsObserver;
103import android.content.pm.InstrumentationInfo;
104import android.content.pm.IntentFilterVerificationInfo;
105import android.content.pm.KeySet;
106import android.content.pm.ManifestDigest;
107import android.content.pm.PackageCleanItem;
108import android.content.pm.PackageInfo;
109import android.content.pm.PackageInfoLite;
110import android.content.pm.PackageInstaller;
111import android.content.pm.PackageManager;
112import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
113import android.content.pm.PackageManagerInternal;
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 *
260runtest -c android.content.pm.PackageManagerTests frameworks-core
261 *
262 * {@hide}
263 */
264public class PackageManagerService extends IPackageManager.Stub {
265    static final String TAG = "PackageManager";
266    static final boolean DEBUG_SETTINGS = false;
267    static final boolean DEBUG_PREFERRED = false;
268    static final boolean DEBUG_UPGRADE = false;
269    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
270    private static final boolean DEBUG_BACKUP = true;
271    private static final boolean DEBUG_INSTALL = false;
272    private static final boolean DEBUG_REMOVE = false;
273    private static final boolean DEBUG_BROADCASTS = false;
274    private static final boolean DEBUG_SHOW_INFO = false;
275    private static final boolean DEBUG_PACKAGE_INFO = false;
276    private static final boolean DEBUG_INTENT_MATCHING = false;
277    private static final boolean DEBUG_PACKAGE_SCANNING = false;
278    private static final boolean DEBUG_VERIFY = false;
279    private static final boolean DEBUG_DEXOPT = false;
280    private static final boolean DEBUG_ABI_SELECTION = false;
281
282    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
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    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
555            new DefaultPermissionGrantPolicy(this);
556
557    private interface IntentFilterVerifier<T extends IntentFilter> {
558        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
559                                               T filter, String packageName);
560        void startVerifications(int userId);
561        void receiveVerificationResponse(int verificationId);
562    }
563
564    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
565        private Context mContext;
566        private ComponentName mIntentFilterVerifierComponent;
567        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
568
569        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
570            mContext = context;
571            mIntentFilterVerifierComponent = verifierComponent;
572        }
573
574        private String getDefaultScheme() {
575            return IntentFilter.SCHEME_HTTPS;
576        }
577
578        @Override
579        public void startVerifications(int userId) {
580            // Launch verifications requests
581            int count = mCurrentIntentFilterVerifications.size();
582            for (int n=0; n<count; n++) {
583                int verificationId = mCurrentIntentFilterVerifications.get(n);
584                final IntentFilterVerificationState ivs =
585                        mIntentFilterVerificationStates.get(verificationId);
586
587                String packageName = ivs.getPackageName();
588
589                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
590                final int filterCount = filters.size();
591                ArraySet<String> domainsSet = new ArraySet<>();
592                for (int m=0; m<filterCount; m++) {
593                    PackageParser.ActivityIntentInfo filter = filters.get(m);
594                    domainsSet.addAll(filter.getHostsList());
595                }
596                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
597                synchronized (mPackages) {
598                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
599                            packageName, domainsList) != null) {
600                        scheduleWriteSettingsLocked();
601                    }
602                }
603                sendVerificationRequest(userId, verificationId, ivs);
604            }
605            mCurrentIntentFilterVerifications.clear();
606        }
607
608        private void sendVerificationRequest(int userId, int verificationId,
609                IntentFilterVerificationState ivs) {
610
611            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
612            verificationIntent.putExtra(
613                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
614                    verificationId);
615            verificationIntent.putExtra(
616                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
617                    getDefaultScheme());
618            verificationIntent.putExtra(
619                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
620                    ivs.getHostsString());
621            verificationIntent.putExtra(
622                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
623                    ivs.getPackageName());
624            verificationIntent.setComponent(mIntentFilterVerifierComponent);
625            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
626
627            UserHandle user = new UserHandle(userId);
628            mContext.sendBroadcastAsUser(verificationIntent, user);
629            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
630                    "Sending IntenFilter verification broadcast");
631        }
632
633        public void receiveVerificationResponse(int verificationId) {
634            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
635
636            final boolean verified = ivs.isVerified();
637
638            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
639            final int count = filters.size();
640            for (int n=0; n<count; n++) {
641                PackageParser.ActivityIntentInfo filter = filters.get(n);
642                filter.setVerified(verified);
643
644                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
645                        + " verified with result:" + verified + " and hosts:"
646                        + ivs.getHostsString());
647            }
648
649            mIntentFilterVerificationStates.remove(verificationId);
650
651            final String packageName = ivs.getPackageName();
652            IntentFilterVerificationInfo ivi = null;
653
654            synchronized (mPackages) {
655                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
656            }
657            if (ivi == null) {
658                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
659                        + verificationId + " packageName:" + packageName);
660                return;
661            }
662            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
663                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
664
665            synchronized (mPackages) {
666                if (verified) {
667                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
668                } else {
669                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
670                }
671                scheduleWriteSettingsLocked();
672
673                final int userId = ivs.getUserId();
674                if (userId != UserHandle.USER_ALL) {
675                    final int userStatus =
676                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
677
678                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
679                    boolean needUpdate = false;
680
681                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
682                    // already been set by the User thru the Disambiguation dialog
683                    switch (userStatus) {
684                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
685                            if (verified) {
686                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
687                            } else {
688                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
689                            }
690                            needUpdate = true;
691                            break;
692
693                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
694                            if (verified) {
695                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
696                                needUpdate = true;
697                            }
698                            break;
699
700                        default:
701                            // Nothing to do
702                    }
703
704                    if (needUpdate) {
705                        mSettings.updateIntentFilterVerificationStatusLPw(
706                                packageName, updatedStatus, userId);
707                        scheduleWritePackageRestrictionsLocked(userId);
708                    }
709                }
710            }
711        }
712
713        @Override
714        public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
715                    ActivityIntentInfo filter, String packageName) {
716            if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
717                    filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
718                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
719                        "IntentFilter does not contain HTTP nor HTTPS data scheme");
720                return false;
721            }
722            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
723            if (ivs == null) {
724                ivs = createDomainVerificationState(verifierId, userId, verificationId,
725                        packageName);
726            }
727            if (!hasValidDomains(filter)) {
728                return false;
729            }
730            ivs.addFilter(filter);
731            return true;
732        }
733
734        private IntentFilterVerificationState createDomainVerificationState(int verifierId,
735                int userId, int verificationId, String packageName) {
736            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
737                    verifierId, userId, packageName);
738            ivs.setPendingState();
739            synchronized (mPackages) {
740                mIntentFilterVerificationStates.append(verificationId, ivs);
741                mCurrentIntentFilterVerifications.add(verificationId);
742            }
743            return ivs;
744        }
745    }
746
747    private static boolean hasValidDomains(ActivityIntentInfo filter) {
748        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
749                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
750        if (!hasHTTPorHTTPS) {
751            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
752                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
753            return false;
754        }
755        return true;
756    }
757
758    private IntentFilterVerifier mIntentFilterVerifier;
759
760    // Set of pending broadcasts for aggregating enable/disable of components.
761    static class PendingPackageBroadcasts {
762        // for each user id, a map of <package name -> components within that package>
763        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
764
765        public PendingPackageBroadcasts() {
766            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
767        }
768
769        public ArrayList<String> get(int userId, String packageName) {
770            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
771            return packages.get(packageName);
772        }
773
774        public void put(int userId, String packageName, ArrayList<String> components) {
775            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
776            packages.put(packageName, components);
777        }
778
779        public void remove(int userId, String packageName) {
780            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
781            if (packages != null) {
782                packages.remove(packageName);
783            }
784        }
785
786        public void remove(int userId) {
787            mUidMap.remove(userId);
788        }
789
790        public int userIdCount() {
791            return mUidMap.size();
792        }
793
794        public int userIdAt(int n) {
795            return mUidMap.keyAt(n);
796        }
797
798        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
799            return mUidMap.get(userId);
800        }
801
802        public int size() {
803            // total number of pending broadcast entries across all userIds
804            int num = 0;
805            for (int i = 0; i< mUidMap.size(); i++) {
806                num += mUidMap.valueAt(i).size();
807            }
808            return num;
809        }
810
811        public void clear() {
812            mUidMap.clear();
813        }
814
815        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
816            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
817            if (map == null) {
818                map = new ArrayMap<String, ArrayList<String>>();
819                mUidMap.put(userId, map);
820            }
821            return map;
822        }
823    }
824    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
825
826    // Service Connection to remote media container service to copy
827    // package uri's from external media onto secure containers
828    // or internal storage.
829    private IMediaContainerService mContainerService = null;
830
831    static final int SEND_PENDING_BROADCAST = 1;
832    static final int MCS_BOUND = 3;
833    static final int END_COPY = 4;
834    static final int INIT_COPY = 5;
835    static final int MCS_UNBIND = 6;
836    static final int START_CLEANING_PACKAGE = 7;
837    static final int FIND_INSTALL_LOC = 8;
838    static final int POST_INSTALL = 9;
839    static final int MCS_RECONNECT = 10;
840    static final int MCS_GIVE_UP = 11;
841    static final int UPDATED_MEDIA_STATUS = 12;
842    static final int WRITE_SETTINGS = 13;
843    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
844    static final int PACKAGE_VERIFIED = 15;
845    static final int CHECK_PENDING_VERIFICATION = 16;
846    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
847    static final int INTENT_FILTER_VERIFIED = 18;
848
849    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
850
851    // Delay time in millisecs
852    static final int BROADCAST_DELAY = 10 * 1000;
853
854    static UserManagerService sUserManager;
855
856    // Stores a list of users whose package restrictions file needs to be updated
857    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
858
859    final private DefaultContainerConnection mDefContainerConn =
860            new DefaultContainerConnection();
861    class DefaultContainerConnection implements ServiceConnection {
862        public void onServiceConnected(ComponentName name, IBinder service) {
863            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
864            IMediaContainerService imcs =
865                IMediaContainerService.Stub.asInterface(service);
866            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
867        }
868
869        public void onServiceDisconnected(ComponentName name) {
870            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
871        }
872    }
873
874    // Recordkeeping of restore-after-install operations that are currently in flight
875    // between the Package Manager and the Backup Manager
876    class PostInstallData {
877        public InstallArgs args;
878        public PackageInstalledInfo res;
879
880        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
881            args = _a;
882            res = _r;
883        }
884    }
885
886    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
887    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
888
889    // backup/restore of preferred activity state
890    private static final String TAG_PREFERRED_BACKUP = "pa";
891
892    private final String mRequiredVerifierPackage;
893
894    private final PackageUsage mPackageUsage = new PackageUsage();
895
896    private class PackageUsage {
897        private static final int WRITE_INTERVAL
898            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
899
900        private final Object mFileLock = new Object();
901        private final AtomicLong mLastWritten = new AtomicLong(0);
902        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
903
904        private boolean mIsHistoricalPackageUsageAvailable = true;
905
906        boolean isHistoricalPackageUsageAvailable() {
907            return mIsHistoricalPackageUsageAvailable;
908        }
909
910        void write(boolean force) {
911            if (force) {
912                writeInternal();
913                return;
914            }
915            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
916                && !DEBUG_DEXOPT) {
917                return;
918            }
919            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
920                new Thread("PackageUsage_DiskWriter") {
921                    @Override
922                    public void run() {
923                        try {
924                            writeInternal();
925                        } finally {
926                            mBackgroundWriteRunning.set(false);
927                        }
928                    }
929                }.start();
930            }
931        }
932
933        private void writeInternal() {
934            synchronized (mPackages) {
935                synchronized (mFileLock) {
936                    AtomicFile file = getFile();
937                    FileOutputStream f = null;
938                    try {
939                        f = file.startWrite();
940                        BufferedOutputStream out = new BufferedOutputStream(f);
941                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
942                        StringBuilder sb = new StringBuilder();
943                        for (PackageParser.Package pkg : mPackages.values()) {
944                            if (pkg.mLastPackageUsageTimeInMills == 0) {
945                                continue;
946                            }
947                            sb.setLength(0);
948                            sb.append(pkg.packageName);
949                            sb.append(' ');
950                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
951                            sb.append('\n');
952                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
953                        }
954                        out.flush();
955                        file.finishWrite(f);
956                    } catch (IOException e) {
957                        if (f != null) {
958                            file.failWrite(f);
959                        }
960                        Log.e(TAG, "Failed to write package usage times", e);
961                    }
962                }
963            }
964            mLastWritten.set(SystemClock.elapsedRealtime());
965        }
966
967        void readLP() {
968            synchronized (mFileLock) {
969                AtomicFile file = getFile();
970                BufferedInputStream in = null;
971                try {
972                    in = new BufferedInputStream(file.openRead());
973                    StringBuffer sb = new StringBuffer();
974                    while (true) {
975                        String packageName = readToken(in, sb, ' ');
976                        if (packageName == null) {
977                            break;
978                        }
979                        String timeInMillisString = readToken(in, sb, '\n');
980                        if (timeInMillisString == null) {
981                            throw new IOException("Failed to find last usage time for package "
982                                                  + packageName);
983                        }
984                        PackageParser.Package pkg = mPackages.get(packageName);
985                        if (pkg == null) {
986                            continue;
987                        }
988                        long timeInMillis;
989                        try {
990                            timeInMillis = Long.parseLong(timeInMillisString.toString());
991                        } catch (NumberFormatException e) {
992                            throw new IOException("Failed to parse " + timeInMillisString
993                                                  + " as a long.", e);
994                        }
995                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
996                    }
997                } catch (FileNotFoundException expected) {
998                    mIsHistoricalPackageUsageAvailable = false;
999                } catch (IOException e) {
1000                    Log.w(TAG, "Failed to read package usage times", e);
1001                } finally {
1002                    IoUtils.closeQuietly(in);
1003                }
1004            }
1005            mLastWritten.set(SystemClock.elapsedRealtime());
1006        }
1007
1008        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1009                throws IOException {
1010            sb.setLength(0);
1011            while (true) {
1012                int ch = in.read();
1013                if (ch == -1) {
1014                    if (sb.length() == 0) {
1015                        return null;
1016                    }
1017                    throw new IOException("Unexpected EOF");
1018                }
1019                if (ch == endOfToken) {
1020                    return sb.toString();
1021                }
1022                sb.append((char)ch);
1023            }
1024        }
1025
1026        private AtomicFile getFile() {
1027            File dataDir = Environment.getDataDirectory();
1028            File systemDir = new File(dataDir, "system");
1029            File fname = new File(systemDir, "package-usage.list");
1030            return new AtomicFile(fname);
1031        }
1032    }
1033
1034    class PackageHandler extends Handler {
1035        private boolean mBound = false;
1036        final ArrayList<HandlerParams> mPendingInstalls =
1037            new ArrayList<HandlerParams>();
1038
1039        private boolean connectToService() {
1040            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1041                    " DefaultContainerService");
1042            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1043            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1044            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1045                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1046                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1047                mBound = true;
1048                return true;
1049            }
1050            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1051            return false;
1052        }
1053
1054        private void disconnectService() {
1055            mContainerService = null;
1056            mBound = false;
1057            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1058            mContext.unbindService(mDefContainerConn);
1059            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1060        }
1061
1062        PackageHandler(Looper looper) {
1063            super(looper);
1064        }
1065
1066        public void handleMessage(Message msg) {
1067            try {
1068                doHandleMessage(msg);
1069            } finally {
1070                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1071            }
1072        }
1073
1074        void doHandleMessage(Message msg) {
1075            switch (msg.what) {
1076                case INIT_COPY: {
1077                    HandlerParams params = (HandlerParams) msg.obj;
1078                    int idx = mPendingInstalls.size();
1079                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1080                    // If a bind was already initiated we dont really
1081                    // need to do anything. The pending install
1082                    // will be processed later on.
1083                    if (!mBound) {
1084                        // If this is the only one pending we might
1085                        // have to bind to the service again.
1086                        if (!connectToService()) {
1087                            Slog.e(TAG, "Failed to bind to media container service");
1088                            params.serviceError();
1089                            return;
1090                        } else {
1091                            // Once we bind to the service, the first
1092                            // pending request will be processed.
1093                            mPendingInstalls.add(idx, params);
1094                        }
1095                    } else {
1096                        mPendingInstalls.add(idx, params);
1097                        // Already bound to the service. Just make
1098                        // sure we trigger off processing the first request.
1099                        if (idx == 0) {
1100                            mHandler.sendEmptyMessage(MCS_BOUND);
1101                        }
1102                    }
1103                    break;
1104                }
1105                case MCS_BOUND: {
1106                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1107                    if (msg.obj != null) {
1108                        mContainerService = (IMediaContainerService) msg.obj;
1109                    }
1110                    if (mContainerService == null) {
1111                        if (!mBound) {
1112                            // Something seriously wrong since we are not bound and we are not
1113                            // waiting for connection. Bail out.
1114                            Slog.e(TAG, "Cannot bind to media container service");
1115                            for (HandlerParams params : mPendingInstalls) {
1116                                // Indicate service bind error
1117                                params.serviceError();
1118                            }
1119                            mPendingInstalls.clear();
1120                        } else {
1121                            Slog.w(TAG, "Waiting to connect to media container service");
1122                        }
1123                    } else if (mPendingInstalls.size() > 0) {
1124                        HandlerParams params = mPendingInstalls.get(0);
1125                        if (params != null) {
1126                            if (params.startCopy()) {
1127                                // We are done...  look for more work or to
1128                                // go idle.
1129                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1130                                        "Checking for more work or unbind...");
1131                                // Delete pending install
1132                                if (mPendingInstalls.size() > 0) {
1133                                    mPendingInstalls.remove(0);
1134                                }
1135                                if (mPendingInstalls.size() == 0) {
1136                                    if (mBound) {
1137                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1138                                                "Posting delayed MCS_UNBIND");
1139                                        removeMessages(MCS_UNBIND);
1140                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1141                                        // Unbind after a little delay, to avoid
1142                                        // continual thrashing.
1143                                        sendMessageDelayed(ubmsg, 10000);
1144                                    }
1145                                } else {
1146                                    // There are more pending requests in queue.
1147                                    // Just post MCS_BOUND message to trigger processing
1148                                    // of next pending install.
1149                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1150                                            "Posting MCS_BOUND for next work");
1151                                    mHandler.sendEmptyMessage(MCS_BOUND);
1152                                }
1153                            }
1154                        }
1155                    } else {
1156                        // Should never happen ideally.
1157                        Slog.w(TAG, "Empty queue");
1158                    }
1159                    break;
1160                }
1161                case MCS_RECONNECT: {
1162                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1163                    if (mPendingInstalls.size() > 0) {
1164                        if (mBound) {
1165                            disconnectService();
1166                        }
1167                        if (!connectToService()) {
1168                            Slog.e(TAG, "Failed to bind to media container service");
1169                            for (HandlerParams params : mPendingInstalls) {
1170                                // Indicate service bind error
1171                                params.serviceError();
1172                            }
1173                            mPendingInstalls.clear();
1174                        }
1175                    }
1176                    break;
1177                }
1178                case MCS_UNBIND: {
1179                    // If there is no actual work left, then time to unbind.
1180                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1181
1182                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1183                        if (mBound) {
1184                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1185
1186                            disconnectService();
1187                        }
1188                    } else if (mPendingInstalls.size() > 0) {
1189                        // There are more pending requests in queue.
1190                        // Just post MCS_BOUND message to trigger processing
1191                        // of next pending install.
1192                        mHandler.sendEmptyMessage(MCS_BOUND);
1193                    }
1194
1195                    break;
1196                }
1197                case MCS_GIVE_UP: {
1198                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1199                    mPendingInstalls.remove(0);
1200                    break;
1201                }
1202                case SEND_PENDING_BROADCAST: {
1203                    String packages[];
1204                    ArrayList<String> components[];
1205                    int size = 0;
1206                    int uids[];
1207                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1208                    synchronized (mPackages) {
1209                        if (mPendingBroadcasts == null) {
1210                            return;
1211                        }
1212                        size = mPendingBroadcasts.size();
1213                        if (size <= 0) {
1214                            // Nothing to be done. Just return
1215                            return;
1216                        }
1217                        packages = new String[size];
1218                        components = new ArrayList[size];
1219                        uids = new int[size];
1220                        int i = 0;  // filling out the above arrays
1221
1222                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1223                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1224                            Iterator<Map.Entry<String, ArrayList<String>>> it
1225                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1226                                            .entrySet().iterator();
1227                            while (it.hasNext() && i < size) {
1228                                Map.Entry<String, ArrayList<String>> ent = it.next();
1229                                packages[i] = ent.getKey();
1230                                components[i] = ent.getValue();
1231                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1232                                uids[i] = (ps != null)
1233                                        ? UserHandle.getUid(packageUserId, ps.appId)
1234                                        : -1;
1235                                i++;
1236                            }
1237                        }
1238                        size = i;
1239                        mPendingBroadcasts.clear();
1240                    }
1241                    // Send broadcasts
1242                    for (int i = 0; i < size; i++) {
1243                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1244                    }
1245                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1246                    break;
1247                }
1248                case START_CLEANING_PACKAGE: {
1249                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1250                    final String packageName = (String)msg.obj;
1251                    final int userId = msg.arg1;
1252                    final boolean andCode = msg.arg2 != 0;
1253                    synchronized (mPackages) {
1254                        if (userId == UserHandle.USER_ALL) {
1255                            int[] users = sUserManager.getUserIds();
1256                            for (int user : users) {
1257                                mSettings.addPackageToCleanLPw(
1258                                        new PackageCleanItem(user, packageName, andCode));
1259                            }
1260                        } else {
1261                            mSettings.addPackageToCleanLPw(
1262                                    new PackageCleanItem(userId, packageName, andCode));
1263                        }
1264                    }
1265                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1266                    startCleaningPackages();
1267                } break;
1268                case POST_INSTALL: {
1269                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1270                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1271                    mRunningInstalls.delete(msg.arg1);
1272                    boolean deleteOld = false;
1273
1274                    if (data != null) {
1275                        InstallArgs args = data.args;
1276                        PackageInstalledInfo res = data.res;
1277
1278                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1279                            res.removedInfo.sendBroadcast(false, true, false);
1280                            Bundle extras = new Bundle(1);
1281                            extras.putInt(Intent.EXTRA_UID, res.uid);
1282
1283                            // Now that we successfully installed the package, grant runtime
1284                            // permissions if requested before broadcasting the install.
1285                            if ((args.installFlags
1286                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1287                                grantRequestedRuntimePermissions(res.pkg,
1288                                        args.user.getIdentifier());
1289                            }
1290
1291                            // Determine the set of users who are adding this
1292                            // package for the first time vs. those who are seeing
1293                            // an update.
1294                            int[] firstUsers;
1295                            int[] updateUsers = new int[0];
1296                            if (res.origUsers == null || res.origUsers.length == 0) {
1297                                firstUsers = res.newUsers;
1298                            } else {
1299                                firstUsers = new int[0];
1300                                for (int i=0; i<res.newUsers.length; i++) {
1301                                    int user = res.newUsers[i];
1302                                    boolean isNew = true;
1303                                    for (int j=0; j<res.origUsers.length; j++) {
1304                                        if (res.origUsers[j] == user) {
1305                                            isNew = false;
1306                                            break;
1307                                        }
1308                                    }
1309                                    if (isNew) {
1310                                        int[] newFirst = new int[firstUsers.length+1];
1311                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1312                                                firstUsers.length);
1313                                        newFirst[firstUsers.length] = user;
1314                                        firstUsers = newFirst;
1315                                    } else {
1316                                        int[] newUpdate = new int[updateUsers.length+1];
1317                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1318                                                updateUsers.length);
1319                                        newUpdate[updateUsers.length] = user;
1320                                        updateUsers = newUpdate;
1321                                    }
1322                                }
1323                            }
1324                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1325                                    res.pkg.applicationInfo.packageName,
1326                                    extras, null, null, firstUsers);
1327                            final boolean update = res.removedInfo.removedPackage != null;
1328                            if (update) {
1329                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1330                            }
1331                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1332                                    res.pkg.applicationInfo.packageName,
1333                                    extras, null, null, updateUsers);
1334                            if (update) {
1335                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1336                                        res.pkg.applicationInfo.packageName,
1337                                        extras, null, null, updateUsers);
1338                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1339                                        null, null,
1340                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1341
1342                                // treat asec-hosted packages like removable media on upgrade
1343                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1344                                    if (DEBUG_INSTALL) {
1345                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1346                                                + " is ASEC-hosted -> AVAILABLE");
1347                                    }
1348                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1349                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1350                                    pkgList.add(res.pkg.applicationInfo.packageName);
1351                                    sendResourcesChangedBroadcast(true, true,
1352                                            pkgList,uidArray, null);
1353                                }
1354                            }
1355                            if (res.removedInfo.args != null) {
1356                                // Remove the replaced package's older resources safely now
1357                                deleteOld = true;
1358                            }
1359
1360                            // Log current value of "unknown sources" setting
1361                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1362                                getUnknownSourcesSettings());
1363                        }
1364                        // Force a gc to clear up things
1365                        Runtime.getRuntime().gc();
1366                        // We delete after a gc for applications  on sdcard.
1367                        if (deleteOld) {
1368                            synchronized (mInstallLock) {
1369                                res.removedInfo.args.doPostDeleteLI(true);
1370                            }
1371                        }
1372                        if (args.observer != null) {
1373                            try {
1374                                Bundle extras = extrasForInstallResult(res);
1375                                args.observer.onPackageInstalled(res.name, res.returnCode,
1376                                        res.returnMsg, extras);
1377                            } catch (RemoteException e) {
1378                                Slog.i(TAG, "Observer no longer exists.");
1379                            }
1380                        }
1381                    } else {
1382                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1383                    }
1384                } break;
1385                case UPDATED_MEDIA_STATUS: {
1386                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1387                    boolean reportStatus = msg.arg1 == 1;
1388                    boolean doGc = msg.arg2 == 1;
1389                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1390                    if (doGc) {
1391                        // Force a gc to clear up stale containers.
1392                        Runtime.getRuntime().gc();
1393                    }
1394                    if (msg.obj != null) {
1395                        @SuppressWarnings("unchecked")
1396                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1397                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1398                        // Unload containers
1399                        unloadAllContainers(args);
1400                    }
1401                    if (reportStatus) {
1402                        try {
1403                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1404                            PackageHelper.getMountService().finishMediaUpdate();
1405                        } catch (RemoteException e) {
1406                            Log.e(TAG, "MountService not running?");
1407                        }
1408                    }
1409                } break;
1410                case WRITE_SETTINGS: {
1411                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1412                    synchronized (mPackages) {
1413                        removeMessages(WRITE_SETTINGS);
1414                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1415                        mSettings.writeLPr();
1416                        mDirtyUsers.clear();
1417                    }
1418                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1419                } break;
1420                case WRITE_PACKAGE_RESTRICTIONS: {
1421                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1422                    synchronized (mPackages) {
1423                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1424                        for (int userId : mDirtyUsers) {
1425                            mSettings.writePackageRestrictionsLPr(userId);
1426                        }
1427                        mDirtyUsers.clear();
1428                    }
1429                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1430                } break;
1431                case CHECK_PENDING_VERIFICATION: {
1432                    final int verificationId = msg.arg1;
1433                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1434
1435                    if ((state != null) && !state.timeoutExtended()) {
1436                        final InstallArgs args = state.getInstallArgs();
1437                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1438
1439                        Slog.i(TAG, "Verification timed out for " + originUri);
1440                        mPendingVerification.remove(verificationId);
1441
1442                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1443
1444                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1445                            Slog.i(TAG, "Continuing with installation of " + originUri);
1446                            state.setVerifierResponse(Binder.getCallingUid(),
1447                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1448                            broadcastPackageVerified(verificationId, originUri,
1449                                    PackageManager.VERIFICATION_ALLOW,
1450                                    state.getInstallArgs().getUser());
1451                            try {
1452                                ret = args.copyApk(mContainerService, true);
1453                            } catch (RemoteException e) {
1454                                Slog.e(TAG, "Could not contact the ContainerService");
1455                            }
1456                        } else {
1457                            broadcastPackageVerified(verificationId, originUri,
1458                                    PackageManager.VERIFICATION_REJECT,
1459                                    state.getInstallArgs().getUser());
1460                        }
1461
1462                        processPendingInstall(args, ret);
1463                        mHandler.sendEmptyMessage(MCS_UNBIND);
1464                    }
1465                    break;
1466                }
1467                case PACKAGE_VERIFIED: {
1468                    final int verificationId = msg.arg1;
1469
1470                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1471                    if (state == null) {
1472                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1473                        break;
1474                    }
1475
1476                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1477
1478                    state.setVerifierResponse(response.callerUid, response.code);
1479
1480                    if (state.isVerificationComplete()) {
1481                        mPendingVerification.remove(verificationId);
1482
1483                        final InstallArgs args = state.getInstallArgs();
1484                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1485
1486                        int ret;
1487                        if (state.isInstallAllowed()) {
1488                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1489                            broadcastPackageVerified(verificationId, originUri,
1490                                    response.code, state.getInstallArgs().getUser());
1491                            try {
1492                                ret = args.copyApk(mContainerService, true);
1493                            } catch (RemoteException e) {
1494                                Slog.e(TAG, "Could not contact the ContainerService");
1495                            }
1496                        } else {
1497                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1498                        }
1499
1500                        processPendingInstall(args, ret);
1501
1502                        mHandler.sendEmptyMessage(MCS_UNBIND);
1503                    }
1504
1505                    break;
1506                }
1507                case START_INTENT_FILTER_VERIFICATIONS: {
1508                    int userId = msg.arg1;
1509                    int verifierUid = msg.arg2;
1510                    PackageParser.Package pkg = (PackageParser.Package)msg.obj;
1511
1512                    verifyIntentFiltersIfNeeded(userId, verifierUid, pkg);
1513                    break;
1514                }
1515                case INTENT_FILTER_VERIFIED: {
1516                    final int verificationId = msg.arg1;
1517
1518                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1519                            verificationId);
1520                    if (state == null) {
1521                        Slog.w(TAG, "Invalid IntentFilter verification token "
1522                                + verificationId + " received");
1523                        break;
1524                    }
1525
1526                    final int userId = state.getUserId();
1527
1528                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1529                            "Processing IntentFilter verification with token:"
1530                            + verificationId + " and userId:" + userId);
1531
1532                    final IntentFilterVerificationResponse response =
1533                            (IntentFilterVerificationResponse) msg.obj;
1534
1535                    state.setVerifierResponse(response.callerUid, response.code);
1536
1537                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1538                            "IntentFilter verification with token:" + verificationId
1539                            + " and userId:" + userId
1540                            + " is settings verifier response with response code:"
1541                            + response.code);
1542
1543                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1544                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1545                                + response.getFailedDomainsString());
1546                    }
1547
1548                    if (state.isVerificationComplete()) {
1549                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1550                    } else {
1551                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1552                                "IntentFilter verification with token:" + verificationId
1553                                + " was not said to be complete");
1554                    }
1555
1556                    break;
1557                }
1558            }
1559        }
1560    }
1561
1562    private StorageEventListener mStorageListener = new StorageEventListener() {
1563        @Override
1564        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1565            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1566                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1567                    // TODO: ensure that private directories exist for all active users
1568                    // TODO: remove user data whose serial number doesn't match
1569                    loadPrivatePackages(vol);
1570                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1571                    unloadPrivatePackages(vol);
1572                }
1573            }
1574
1575            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1576                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1577                    updateExternalMediaStatus(true, false);
1578                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1579                    updateExternalMediaStatus(false, false);
1580                }
1581            }
1582        }
1583
1584        @Override
1585        public void onVolumeForgotten(String fsUuid) {
1586            // TODO: remove all packages hosted on this uuid
1587        }
1588    };
1589
1590    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1591        if (userId >= UserHandle.USER_OWNER) {
1592            grantRequestedRuntimePermissionsForUser(pkg, userId);
1593        } else if (userId == UserHandle.USER_ALL) {
1594            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1595                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1596            }
1597        }
1598
1599        // We could have touched GID membership, so flush out packages.list
1600        synchronized (mPackages) {
1601            mSettings.writePackageListLPr();
1602        }
1603    }
1604
1605    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1606        SettingBase sb = (SettingBase) pkg.mExtras;
1607        if (sb == null) {
1608            return;
1609        }
1610
1611        PermissionsState permissionsState = sb.getPermissionsState();
1612
1613        for (String permission : pkg.requestedPermissions) {
1614            BasePermission bp = mSettings.mPermissions.get(permission);
1615            if (bp != null && bp.isRuntime()) {
1616                permissionsState.grantRuntimePermission(bp, userId);
1617            }
1618        }
1619    }
1620
1621    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1622        Bundle extras = null;
1623        switch (res.returnCode) {
1624            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1625                extras = new Bundle();
1626                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1627                        res.origPermission);
1628                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1629                        res.origPackage);
1630                break;
1631            }
1632            case PackageManager.INSTALL_SUCCEEDED: {
1633                extras = new Bundle();
1634                extras.putBoolean(Intent.EXTRA_REPLACING,
1635                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1636                break;
1637            }
1638        }
1639        return extras;
1640    }
1641
1642    void scheduleWriteSettingsLocked() {
1643        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1644            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1645        }
1646    }
1647
1648    void scheduleWritePackageRestrictionsLocked(int userId) {
1649        if (!sUserManager.exists(userId)) return;
1650        mDirtyUsers.add(userId);
1651        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1652            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1653        }
1654    }
1655
1656    public static PackageManagerService main(Context context, Installer installer,
1657            boolean factoryTest, boolean onlyCore) {
1658        PackageManagerService m = new PackageManagerService(context, installer,
1659                factoryTest, onlyCore);
1660        ServiceManager.addService("package", m);
1661        return m;
1662    }
1663
1664    static String[] splitString(String str, char sep) {
1665        int count = 1;
1666        int i = 0;
1667        while ((i=str.indexOf(sep, i)) >= 0) {
1668            count++;
1669            i++;
1670        }
1671
1672        String[] res = new String[count];
1673        i=0;
1674        count = 0;
1675        int lastI=0;
1676        while ((i=str.indexOf(sep, i)) >= 0) {
1677            res[count] = str.substring(lastI, i);
1678            count++;
1679            i++;
1680            lastI = i;
1681        }
1682        res[count] = str.substring(lastI, str.length());
1683        return res;
1684    }
1685
1686    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1687        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1688                Context.DISPLAY_SERVICE);
1689        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1690    }
1691
1692    public PackageManagerService(Context context, Installer installer,
1693            boolean factoryTest, boolean onlyCore) {
1694        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1695                SystemClock.uptimeMillis());
1696
1697        if (mSdkVersion <= 0) {
1698            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1699        }
1700
1701        mContext = context;
1702        mFactoryTest = factoryTest;
1703        mOnlyCore = onlyCore;
1704        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1705        mMetrics = new DisplayMetrics();
1706        mSettings = new Settings(mPackages);
1707        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1708                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1709        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1710                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1711        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1712                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1713        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1714                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1715        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1716                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1717        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1718                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1719
1720        // TODO: add a property to control this?
1721        long dexOptLRUThresholdInMinutes;
1722        if (mLazyDexOpt) {
1723            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1724        } else {
1725            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1726        }
1727        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1728
1729        String separateProcesses = SystemProperties.get("debug.separate_processes");
1730        if (separateProcesses != null && separateProcesses.length() > 0) {
1731            if ("*".equals(separateProcesses)) {
1732                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1733                mSeparateProcesses = null;
1734                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1735            } else {
1736                mDefParseFlags = 0;
1737                mSeparateProcesses = separateProcesses.split(",");
1738                Slog.w(TAG, "Running with debug.separate_processes: "
1739                        + separateProcesses);
1740            }
1741        } else {
1742            mDefParseFlags = 0;
1743            mSeparateProcesses = null;
1744        }
1745
1746        mInstaller = installer;
1747        mPackageDexOptimizer = new PackageDexOptimizer(this);
1748        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1749
1750        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1751                FgThread.get().getLooper());
1752
1753        getDefaultDisplayMetrics(context, mMetrics);
1754
1755        SystemConfig systemConfig = SystemConfig.getInstance();
1756        mGlobalGids = systemConfig.getGlobalGids();
1757        mSystemPermissions = systemConfig.getSystemPermissions();
1758        mAvailableFeatures = systemConfig.getAvailableFeatures();
1759
1760        synchronized (mInstallLock) {
1761        // writer
1762        synchronized (mPackages) {
1763            mHandlerThread = new ServiceThread(TAG,
1764                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1765            mHandlerThread.start();
1766            mHandler = new PackageHandler(mHandlerThread.getLooper());
1767            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1768
1769            File dataDir = Environment.getDataDirectory();
1770            mAppDataDir = new File(dataDir, "data");
1771            mAppInstallDir = new File(dataDir, "app");
1772            mAppLib32InstallDir = new File(dataDir, "app-lib");
1773            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1774            mUserAppDataDir = new File(dataDir, "user");
1775            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1776
1777            sUserManager = new UserManagerService(context, this,
1778                    mInstallLock, mPackages);
1779
1780            // Propagate permission configuration in to package manager.
1781            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1782                    = systemConfig.getPermissions();
1783            for (int i=0; i<permConfig.size(); i++) {
1784                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1785                BasePermission bp = mSettings.mPermissions.get(perm.name);
1786                if (bp == null) {
1787                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1788                    mSettings.mPermissions.put(perm.name, bp);
1789                }
1790                if (perm.gids != null) {
1791                    bp.setGids(perm.gids, perm.perUser);
1792                }
1793            }
1794
1795            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1796            for (int i=0; i<libConfig.size(); i++) {
1797                mSharedLibraries.put(libConfig.keyAt(i),
1798                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1799            }
1800
1801            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1802
1803            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1804                    mSdkVersion, mOnlyCore);
1805
1806            String customResolverActivity = Resources.getSystem().getString(
1807                    R.string.config_customResolverActivity);
1808            if (TextUtils.isEmpty(customResolverActivity)) {
1809                customResolverActivity = null;
1810            } else {
1811                mCustomResolverComponentName = ComponentName.unflattenFromString(
1812                        customResolverActivity);
1813            }
1814
1815            long startTime = SystemClock.uptimeMillis();
1816
1817            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1818                    startTime);
1819
1820            // Set flag to monitor and not change apk file paths when
1821            // scanning install directories.
1822            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1823
1824            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1825
1826            /**
1827             * Add everything in the in the boot class path to the
1828             * list of process files because dexopt will have been run
1829             * if necessary during zygote startup.
1830             */
1831            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1832            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1833
1834            if (bootClassPath != null) {
1835                String[] bootClassPathElements = splitString(bootClassPath, ':');
1836                for (String element : bootClassPathElements) {
1837                    alreadyDexOpted.add(element);
1838                }
1839            } else {
1840                Slog.w(TAG, "No BOOTCLASSPATH found!");
1841            }
1842
1843            if (systemServerClassPath != null) {
1844                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1845                for (String element : systemServerClassPathElements) {
1846                    alreadyDexOpted.add(element);
1847                }
1848            } else {
1849                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1850            }
1851
1852            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1853            final String[] dexCodeInstructionSets =
1854                    getDexCodeInstructionSets(
1855                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1856
1857            /**
1858             * Ensure all external libraries have had dexopt run on them.
1859             */
1860            if (mSharedLibraries.size() > 0) {
1861                // NOTE: For now, we're compiling these system "shared libraries"
1862                // (and framework jars) into all available architectures. It's possible
1863                // to compile them only when we come across an app that uses them (there's
1864                // already logic for that in scanPackageLI) but that adds some complexity.
1865                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1866                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1867                        final String lib = libEntry.path;
1868                        if (lib == null) {
1869                            continue;
1870                        }
1871
1872                        try {
1873                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1874                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1875                                alreadyDexOpted.add(lib);
1876                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1877                            }
1878                        } catch (FileNotFoundException e) {
1879                            Slog.w(TAG, "Library not found: " + lib);
1880                        } catch (IOException e) {
1881                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1882                                    + e.getMessage());
1883                        }
1884                    }
1885                }
1886            }
1887
1888            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1889
1890            // Gross hack for now: we know this file doesn't contain any
1891            // code, so don't dexopt it to avoid the resulting log spew.
1892            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1893
1894            // Gross hack for now: we know this file is only part of
1895            // the boot class path for art, so don't dexopt it to
1896            // avoid the resulting log spew.
1897            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1898
1899            /**
1900             * There are a number of commands implemented in Java, which
1901             * we currently need to do the dexopt on so that they can be
1902             * run from a non-root shell.
1903             */
1904            String[] frameworkFiles = frameworkDir.list();
1905            if (frameworkFiles != null) {
1906                // TODO: We could compile these only for the most preferred ABI. We should
1907                // first double check that the dex files for these commands are not referenced
1908                // by other system apps.
1909                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1910                    for (int i=0; i<frameworkFiles.length; i++) {
1911                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1912                        String path = libPath.getPath();
1913                        // Skip the file if we already did it.
1914                        if (alreadyDexOpted.contains(path)) {
1915                            continue;
1916                        }
1917                        // Skip the file if it is not a type we want to dexopt.
1918                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1919                            continue;
1920                        }
1921                        try {
1922                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1923                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1924                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1925                            }
1926                        } catch (FileNotFoundException e) {
1927                            Slog.w(TAG, "Jar not found: " + path);
1928                        } catch (IOException e) {
1929                            Slog.w(TAG, "Exception reading jar: " + path, e);
1930                        }
1931                    }
1932                }
1933            }
1934
1935            // Collect vendor overlay packages.
1936            // (Do this before scanning any apps.)
1937            // For security and version matching reason, only consider
1938            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1939            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1940            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1941                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1942
1943            // Find base frameworks (resource packages without code).
1944            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1945                    | PackageParser.PARSE_IS_SYSTEM_DIR
1946                    | PackageParser.PARSE_IS_PRIVILEGED,
1947                    scanFlags | SCAN_NO_DEX, 0);
1948
1949            // Collected privileged system packages.
1950            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1951            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1952                    | PackageParser.PARSE_IS_SYSTEM_DIR
1953                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1954
1955            // Collect ordinary system packages.
1956            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1957            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1958                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1959
1960            // Collect all vendor packages.
1961            File vendorAppDir = new File("/vendor/app");
1962            try {
1963                vendorAppDir = vendorAppDir.getCanonicalFile();
1964            } catch (IOException e) {
1965                // failed to look up canonical path, continue with original one
1966            }
1967            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1968                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1969
1970            // Collect all OEM packages.
1971            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1972            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1973                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1974
1975            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1976            mInstaller.moveFiles();
1977
1978            // Prune any system packages that no longer exist.
1979            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1980            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1981            if (!mOnlyCore) {
1982                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1983                while (psit.hasNext()) {
1984                    PackageSetting ps = psit.next();
1985
1986                    /*
1987                     * If this is not a system app, it can't be a
1988                     * disable system app.
1989                     */
1990                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1991                        continue;
1992                    }
1993
1994                    /*
1995                     * If the package is scanned, it's not erased.
1996                     */
1997                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1998                    if (scannedPkg != null) {
1999                        /*
2000                         * If the system app is both scanned and in the
2001                         * disabled packages list, then it must have been
2002                         * added via OTA. Remove it from the currently
2003                         * scanned package so the previously user-installed
2004                         * application can be scanned.
2005                         */
2006                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2007                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2008                                    + ps.name + "; removing system app.  Last known codePath="
2009                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2010                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2011                                    + scannedPkg.mVersionCode);
2012                            removePackageLI(ps, true);
2013                            expectingBetter.put(ps.name, ps.codePath);
2014                        }
2015
2016                        continue;
2017                    }
2018
2019                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2020                        psit.remove();
2021                        logCriticalInfo(Log.WARN, "System package " + ps.name
2022                                + " no longer exists; wiping its data");
2023                        removeDataDirsLI(null, ps.name);
2024                    } else {
2025                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2026                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2027                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2028                        }
2029                    }
2030                }
2031            }
2032
2033            //look for any incomplete package installations
2034            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2035            //clean up list
2036            for(int i = 0; i < deletePkgsList.size(); i++) {
2037                //clean up here
2038                cleanupInstallFailedPackage(deletePkgsList.get(i));
2039            }
2040            //delete tmp files
2041            deleteTempPackageFiles();
2042
2043            // Remove any shared userIDs that have no associated packages
2044            mSettings.pruneSharedUsersLPw();
2045
2046            if (!mOnlyCore) {
2047                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2048                        SystemClock.uptimeMillis());
2049                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2050
2051                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2052                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2053
2054                /**
2055                 * Remove disable package settings for any updated system
2056                 * apps that were removed via an OTA. If they're not a
2057                 * previously-updated app, remove them completely.
2058                 * Otherwise, just revoke their system-level permissions.
2059                 */
2060                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2061                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2062                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2063
2064                    String msg;
2065                    if (deletedPkg == null) {
2066                        msg = "Updated system package " + deletedAppName
2067                                + " no longer exists; wiping its data";
2068                        removeDataDirsLI(null, deletedAppName);
2069                    } else {
2070                        msg = "Updated system app + " + deletedAppName
2071                                + " no longer present; removing system privileges for "
2072                                + deletedAppName;
2073
2074                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2075
2076                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2077                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2078                    }
2079                    logCriticalInfo(Log.WARN, msg);
2080                }
2081
2082                /**
2083                 * Make sure all system apps that we expected to appear on
2084                 * the userdata partition actually showed up. If they never
2085                 * appeared, crawl back and revive the system version.
2086                 */
2087                for (int i = 0; i < expectingBetter.size(); i++) {
2088                    final String packageName = expectingBetter.keyAt(i);
2089                    if (!mPackages.containsKey(packageName)) {
2090                        final File scanFile = expectingBetter.valueAt(i);
2091
2092                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2093                                + " but never showed up; reverting to system");
2094
2095                        final int reparseFlags;
2096                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2097                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2098                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2099                                    | PackageParser.PARSE_IS_PRIVILEGED;
2100                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2101                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2102                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2103                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2104                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2105                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2106                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2107                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2108                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2109                        } else {
2110                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2111                            continue;
2112                        }
2113
2114                        mSettings.enableSystemPackageLPw(packageName);
2115
2116                        try {
2117                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2118                        } catch (PackageManagerException e) {
2119                            Slog.e(TAG, "Failed to parse original system package: "
2120                                    + e.getMessage());
2121                        }
2122                    }
2123                }
2124            }
2125
2126            // Now that we know all of the shared libraries, update all clients to have
2127            // the correct library paths.
2128            updateAllSharedLibrariesLPw();
2129
2130            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2131                // NOTE: We ignore potential failures here during a system scan (like
2132                // the rest of the commands above) because there's precious little we
2133                // can do about it. A settings error is reported, though.
2134                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2135                        false /* force dexopt */, false /* defer dexopt */);
2136            }
2137
2138            // Now that we know all the packages we are keeping,
2139            // read and update their last usage times.
2140            mPackageUsage.readLP();
2141
2142            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2143                    SystemClock.uptimeMillis());
2144            Slog.i(TAG, "Time to scan packages: "
2145                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2146                    + " seconds");
2147
2148            // If the platform SDK has changed since the last time we booted,
2149            // we need to re-grant app permission to catch any new ones that
2150            // appear.  This is really a hack, and means that apps can in some
2151            // cases get permissions that the user didn't initially explicitly
2152            // allow...  it would be nice to have some better way to handle
2153            // this situation.
2154            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2155                    != mSdkVersion;
2156            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2157                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2158                    + "; regranting permissions for internal storage");
2159            mSettings.mInternalSdkPlatform = mSdkVersion;
2160
2161            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2162                    | (regrantPermissions
2163                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2164                            : 0));
2165
2166            // If this is the first boot, and it is a normal boot, then
2167            // we need to initialize the default preferred apps.
2168            if (!mRestoredSettings && !onlyCore) {
2169                mSettings.readDefaultPreferredAppsLPw(this, 0);
2170            }
2171
2172            // If this is first boot after an OTA, and a normal boot, then
2173            // we need to clear code cache directories.
2174            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2175            if (mIsUpgrade && !onlyCore) {
2176                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2177                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2178                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2179                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2180                }
2181                mSettings.mFingerprint = Build.FINGERPRINT;
2182            }
2183
2184            primeDomainVerificationsLPw();
2185            checkDefaultBrowser();
2186
2187            // All the changes are done during package scanning.
2188            mSettings.updateInternalDatabaseVersion();
2189
2190            // can downgrade to reader
2191            mSettings.writeLPr();
2192
2193            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2194                    SystemClock.uptimeMillis());
2195
2196            mRequiredVerifierPackage = getRequiredVerifierLPr();
2197
2198            mInstallerService = new PackageInstallerService(context, this);
2199
2200            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2201            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2202                    mIntentFilterVerifierComponent);
2203
2204        } // synchronized (mPackages)
2205        } // synchronized (mInstallLock)
2206
2207        // Now after opening every single application zip, make sure they
2208        // are all flushed.  Not really needed, but keeps things nice and
2209        // tidy.
2210        Runtime.getRuntime().gc();
2211
2212        // Expose private service for system components to use.
2213        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2214    }
2215
2216    @Override
2217    public boolean isFirstBoot() {
2218        return !mRestoredSettings;
2219    }
2220
2221    @Override
2222    public boolean isOnlyCoreApps() {
2223        return mOnlyCore;
2224    }
2225
2226    @Override
2227    public boolean isUpgrade() {
2228        return mIsUpgrade;
2229    }
2230
2231    private String getRequiredVerifierLPr() {
2232        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2233        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2234                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2235
2236        String requiredVerifier = null;
2237
2238        final int N = receivers.size();
2239        for (int i = 0; i < N; i++) {
2240            final ResolveInfo info = receivers.get(i);
2241
2242            if (info.activityInfo == null) {
2243                continue;
2244            }
2245
2246            final String packageName = info.activityInfo.packageName;
2247
2248            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2249                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2250                continue;
2251            }
2252
2253            if (requiredVerifier != null) {
2254                throw new RuntimeException("There can be only one required verifier");
2255            }
2256
2257            requiredVerifier = packageName;
2258        }
2259
2260        return requiredVerifier;
2261    }
2262
2263    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2264        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2265        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2266                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2267
2268        ComponentName verifierComponentName = null;
2269
2270        int priority = -1000;
2271        final int N = receivers.size();
2272        for (int i = 0; i < N; i++) {
2273            final ResolveInfo info = receivers.get(i);
2274
2275            if (info.activityInfo == null) {
2276                continue;
2277            }
2278
2279            final String packageName = info.activityInfo.packageName;
2280
2281            final PackageSetting ps = mSettings.mPackages.get(packageName);
2282            if (ps == null) {
2283                continue;
2284            }
2285
2286            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2287                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2288                continue;
2289            }
2290
2291            // Select the IntentFilterVerifier with the highest priority
2292            if (priority < info.priority) {
2293                priority = info.priority;
2294                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2295                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2296                        + verifierComponentName + " with priority: " + info.priority);
2297            }
2298        }
2299
2300        return verifierComponentName;
2301    }
2302
2303    private void primeDomainVerificationsLPw() {
2304        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2305        boolean updated = false;
2306        ArraySet<String> allHostsSet = new ArraySet<>();
2307        for (PackageParser.Package pkg : mPackages.values()) {
2308            final String packageName = pkg.packageName;
2309            if (!hasDomainURLs(pkg)) {
2310                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2311                            "package with no domain URLs: " + packageName);
2312                continue;
2313            }
2314            if (!pkg.isSystemApp()) {
2315                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2316                        "No priming domain verifications for a non system package : " +
2317                                packageName);
2318                continue;
2319            }
2320            for (PackageParser.Activity a : pkg.activities) {
2321                for (ActivityIntentInfo filter : a.intents) {
2322                    if (hasValidDomains(filter)) {
2323                        allHostsSet.addAll(filter.getHostsList());
2324                    }
2325                }
2326            }
2327            if (allHostsSet.size() == 0) {
2328                allHostsSet.add("*");
2329            }
2330            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2331            IntentFilterVerificationInfo ivi =
2332                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2333            if (ivi != null) {
2334                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2335                        "Priming domain verifications for package: " + packageName +
2336                        " with hosts:" + ivi.getDomainsString());
2337                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2338                updated = true;
2339            }
2340            else {
2341                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2342                        "No priming domain verifications for package: " + packageName);
2343            }
2344            allHostsSet.clear();
2345        }
2346        if (updated) {
2347            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2348                    "Will need to write primed domain verifications");
2349        }
2350        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2351    }
2352
2353    private void checkDefaultBrowser() {
2354        final int myUserId = UserHandle.myUserId();
2355        final String packageName = getDefaultBrowserPackageName(myUserId);
2356        PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2357        if (info == null) {
2358            Slog.w(TAG, "Clearing default Browser as its package is no more installed: " +
2359                    packageName);
2360            setDefaultBrowserPackageName(null, myUserId);
2361        }
2362    }
2363
2364    @Override
2365    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2366            throws RemoteException {
2367        try {
2368            return super.onTransact(code, data, reply, flags);
2369        } catch (RuntimeException e) {
2370            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2371                Slog.wtf(TAG, "Package Manager Crash", e);
2372            }
2373            throw e;
2374        }
2375    }
2376
2377    void cleanupInstallFailedPackage(PackageSetting ps) {
2378        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2379
2380        removeDataDirsLI(ps.volumeUuid, ps.name);
2381        if (ps.codePath != null) {
2382            if (ps.codePath.isDirectory()) {
2383                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2384            } else {
2385                ps.codePath.delete();
2386            }
2387        }
2388        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2389            if (ps.resourcePath.isDirectory()) {
2390                FileUtils.deleteContents(ps.resourcePath);
2391            }
2392            ps.resourcePath.delete();
2393        }
2394        mSettings.removePackageLPw(ps.name);
2395    }
2396
2397    static int[] appendInts(int[] cur, int[] add) {
2398        if (add == null) return cur;
2399        if (cur == null) return add;
2400        final int N = add.length;
2401        for (int i=0; i<N; i++) {
2402            cur = appendInt(cur, add[i]);
2403        }
2404        return cur;
2405    }
2406
2407    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2408        if (!sUserManager.exists(userId)) return null;
2409        final PackageSetting ps = (PackageSetting) p.mExtras;
2410        if (ps == null) {
2411            return null;
2412        }
2413
2414        final PermissionsState permissionsState = ps.getPermissionsState();
2415
2416        final int[] gids = permissionsState.computeGids(userId);
2417        final Set<String> permissions = permissionsState.getPermissions(userId);
2418        final PackageUserState state = ps.readUserState(userId);
2419
2420        return PackageParser.generatePackageInfo(p, gids, flags,
2421                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2422    }
2423
2424    @Override
2425    public boolean isPackageFrozen(String packageName) {
2426        synchronized (mPackages) {
2427            final PackageSetting ps = mSettings.mPackages.get(packageName);
2428            if (ps != null) {
2429                return ps.frozen;
2430            }
2431        }
2432        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2433        return true;
2434    }
2435
2436    @Override
2437    public boolean isPackageAvailable(String packageName, int userId) {
2438        if (!sUserManager.exists(userId)) return false;
2439        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2440        synchronized (mPackages) {
2441            PackageParser.Package p = mPackages.get(packageName);
2442            if (p != null) {
2443                final PackageSetting ps = (PackageSetting) p.mExtras;
2444                if (ps != null) {
2445                    final PackageUserState state = ps.readUserState(userId);
2446                    if (state != null) {
2447                        return PackageParser.isAvailable(state);
2448                    }
2449                }
2450            }
2451        }
2452        return false;
2453    }
2454
2455    @Override
2456    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2457        if (!sUserManager.exists(userId)) return null;
2458        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2459        // reader
2460        synchronized (mPackages) {
2461            PackageParser.Package p = mPackages.get(packageName);
2462            if (DEBUG_PACKAGE_INFO)
2463                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2464            if (p != null) {
2465                return generatePackageInfo(p, flags, userId);
2466            }
2467            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2468                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2469            }
2470        }
2471        return null;
2472    }
2473
2474    @Override
2475    public String[] currentToCanonicalPackageNames(String[] names) {
2476        String[] out = new String[names.length];
2477        // reader
2478        synchronized (mPackages) {
2479            for (int i=names.length-1; i>=0; i--) {
2480                PackageSetting ps = mSettings.mPackages.get(names[i]);
2481                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2482            }
2483        }
2484        return out;
2485    }
2486
2487    @Override
2488    public String[] canonicalToCurrentPackageNames(String[] names) {
2489        String[] out = new String[names.length];
2490        // reader
2491        synchronized (mPackages) {
2492            for (int i=names.length-1; i>=0; i--) {
2493                String cur = mSettings.mRenamedPackages.get(names[i]);
2494                out[i] = cur != null ? cur : names[i];
2495            }
2496        }
2497        return out;
2498    }
2499
2500    @Override
2501    public int getPackageUid(String packageName, int userId) {
2502        if (!sUserManager.exists(userId)) return -1;
2503        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2504
2505        // reader
2506        synchronized (mPackages) {
2507            PackageParser.Package p = mPackages.get(packageName);
2508            if(p != null) {
2509                return UserHandle.getUid(userId, p.applicationInfo.uid);
2510            }
2511            PackageSetting ps = mSettings.mPackages.get(packageName);
2512            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2513                return -1;
2514            }
2515            p = ps.pkg;
2516            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2517        }
2518    }
2519
2520    @Override
2521    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2522        if (!sUserManager.exists(userId)) {
2523            return null;
2524        }
2525
2526        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2527                "getPackageGids");
2528
2529        // reader
2530        synchronized (mPackages) {
2531            PackageParser.Package p = mPackages.get(packageName);
2532            if (DEBUG_PACKAGE_INFO) {
2533                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2534            }
2535            if (p != null) {
2536                PackageSetting ps = (PackageSetting) p.mExtras;
2537                return ps.getPermissionsState().computeGids(userId);
2538            }
2539        }
2540
2541        return null;
2542    }
2543
2544    static PermissionInfo generatePermissionInfo(
2545            BasePermission bp, int flags) {
2546        if (bp.perm != null) {
2547            return PackageParser.generatePermissionInfo(bp.perm, flags);
2548        }
2549        PermissionInfo pi = new PermissionInfo();
2550        pi.name = bp.name;
2551        pi.packageName = bp.sourcePackage;
2552        pi.nonLocalizedLabel = bp.name;
2553        pi.protectionLevel = bp.protectionLevel;
2554        return pi;
2555    }
2556
2557    @Override
2558    public PermissionInfo getPermissionInfo(String name, int flags) {
2559        // reader
2560        synchronized (mPackages) {
2561            final BasePermission p = mSettings.mPermissions.get(name);
2562            if (p != null) {
2563                return generatePermissionInfo(p, flags);
2564            }
2565            return null;
2566        }
2567    }
2568
2569    @Override
2570    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2571        // reader
2572        synchronized (mPackages) {
2573            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2574            for (BasePermission p : mSettings.mPermissions.values()) {
2575                if (group == null) {
2576                    if (p.perm == null || p.perm.info.group == null) {
2577                        out.add(generatePermissionInfo(p, flags));
2578                    }
2579                } else {
2580                    if (p.perm != null && group.equals(p.perm.info.group)) {
2581                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2582                    }
2583                }
2584            }
2585
2586            if (out.size() > 0) {
2587                return out;
2588            }
2589            return mPermissionGroups.containsKey(group) ? out : null;
2590        }
2591    }
2592
2593    @Override
2594    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2595        // reader
2596        synchronized (mPackages) {
2597            return PackageParser.generatePermissionGroupInfo(
2598                    mPermissionGroups.get(name), flags);
2599        }
2600    }
2601
2602    @Override
2603    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2604        // reader
2605        synchronized (mPackages) {
2606            final int N = mPermissionGroups.size();
2607            ArrayList<PermissionGroupInfo> out
2608                    = new ArrayList<PermissionGroupInfo>(N);
2609            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2610                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2611            }
2612            return out;
2613        }
2614    }
2615
2616    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2617            int userId) {
2618        if (!sUserManager.exists(userId)) return null;
2619        PackageSetting ps = mSettings.mPackages.get(packageName);
2620        if (ps != null) {
2621            if (ps.pkg == null) {
2622                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2623                        flags, userId);
2624                if (pInfo != null) {
2625                    return pInfo.applicationInfo;
2626                }
2627                return null;
2628            }
2629            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2630                    ps.readUserState(userId), userId);
2631        }
2632        return null;
2633    }
2634
2635    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2636            int userId) {
2637        if (!sUserManager.exists(userId)) return null;
2638        PackageSetting ps = mSettings.mPackages.get(packageName);
2639        if (ps != null) {
2640            PackageParser.Package pkg = ps.pkg;
2641            if (pkg == null) {
2642                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2643                    return null;
2644                }
2645                // Only data remains, so we aren't worried about code paths
2646                pkg = new PackageParser.Package(packageName);
2647                pkg.applicationInfo.packageName = packageName;
2648                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2649                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2650                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2651                        packageName, userId).getAbsolutePath();
2652                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2653                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2654            }
2655            return generatePackageInfo(pkg, flags, userId);
2656        }
2657        return null;
2658    }
2659
2660    @Override
2661    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2662        if (!sUserManager.exists(userId)) return null;
2663        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2664        // writer
2665        synchronized (mPackages) {
2666            PackageParser.Package p = mPackages.get(packageName);
2667            if (DEBUG_PACKAGE_INFO) Log.v(
2668                    TAG, "getApplicationInfo " + packageName
2669                    + ": " + p);
2670            if (p != null) {
2671                PackageSetting ps = mSettings.mPackages.get(packageName);
2672                if (ps == null) return null;
2673                // Note: isEnabledLP() does not apply here - always return info
2674                return PackageParser.generateApplicationInfo(
2675                        p, flags, ps.readUserState(userId), userId);
2676            }
2677            if ("android".equals(packageName)||"system".equals(packageName)) {
2678                return mAndroidApplication;
2679            }
2680            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2681                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2682            }
2683        }
2684        return null;
2685    }
2686
2687    @Override
2688    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2689            final IPackageDataObserver observer) {
2690        mContext.enforceCallingOrSelfPermission(
2691                android.Manifest.permission.CLEAR_APP_CACHE, null);
2692        // Queue up an async operation since clearing cache may take a little while.
2693        mHandler.post(new Runnable() {
2694            public void run() {
2695                mHandler.removeCallbacks(this);
2696                int retCode = -1;
2697                synchronized (mInstallLock) {
2698                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2699                    if (retCode < 0) {
2700                        Slog.w(TAG, "Couldn't clear application caches");
2701                    }
2702                }
2703                if (observer != null) {
2704                    try {
2705                        observer.onRemoveCompleted(null, (retCode >= 0));
2706                    } catch (RemoteException e) {
2707                        Slog.w(TAG, "RemoveException when invoking call back");
2708                    }
2709                }
2710            }
2711        });
2712    }
2713
2714    @Override
2715    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2716            final IntentSender pi) {
2717        mContext.enforceCallingOrSelfPermission(
2718                android.Manifest.permission.CLEAR_APP_CACHE, null);
2719        // Queue up an async operation since clearing cache may take a little while.
2720        mHandler.post(new Runnable() {
2721            public void run() {
2722                mHandler.removeCallbacks(this);
2723                int retCode = -1;
2724                synchronized (mInstallLock) {
2725                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2726                    if (retCode < 0) {
2727                        Slog.w(TAG, "Couldn't clear application caches");
2728                    }
2729                }
2730                if(pi != null) {
2731                    try {
2732                        // Callback via pending intent
2733                        int code = (retCode >= 0) ? 1 : 0;
2734                        pi.sendIntent(null, code, null,
2735                                null, null);
2736                    } catch (SendIntentException e1) {
2737                        Slog.i(TAG, "Failed to send pending intent");
2738                    }
2739                }
2740            }
2741        });
2742    }
2743
2744    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2745        synchronized (mInstallLock) {
2746            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2747                throw new IOException("Failed to free enough space");
2748            }
2749        }
2750    }
2751
2752    @Override
2753    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2754        if (!sUserManager.exists(userId)) return null;
2755        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2756        synchronized (mPackages) {
2757            PackageParser.Activity a = mActivities.mActivities.get(component);
2758
2759            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2760            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2761                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2762                if (ps == null) return null;
2763                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2764                        userId);
2765            }
2766            if (mResolveComponentName.equals(component)) {
2767                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2768                        new PackageUserState(), userId);
2769            }
2770        }
2771        return null;
2772    }
2773
2774    @Override
2775    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2776            String resolvedType) {
2777        synchronized (mPackages) {
2778            PackageParser.Activity a = mActivities.mActivities.get(component);
2779            if (a == null) {
2780                return false;
2781            }
2782            for (int i=0; i<a.intents.size(); i++) {
2783                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2784                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2785                    return true;
2786                }
2787            }
2788            return false;
2789        }
2790    }
2791
2792    @Override
2793    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2794        if (!sUserManager.exists(userId)) return null;
2795        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2796        synchronized (mPackages) {
2797            PackageParser.Activity a = mReceivers.mActivities.get(component);
2798            if (DEBUG_PACKAGE_INFO) Log.v(
2799                TAG, "getReceiverInfo " + component + ": " + a);
2800            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2801                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2802                if (ps == null) return null;
2803                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2804                        userId);
2805            }
2806        }
2807        return null;
2808    }
2809
2810    @Override
2811    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2812        if (!sUserManager.exists(userId)) return null;
2813        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2814        synchronized (mPackages) {
2815            PackageParser.Service s = mServices.mServices.get(component);
2816            if (DEBUG_PACKAGE_INFO) Log.v(
2817                TAG, "getServiceInfo " + component + ": " + s);
2818            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2819                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2820                if (ps == null) return null;
2821                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2822                        userId);
2823            }
2824        }
2825        return null;
2826    }
2827
2828    @Override
2829    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2830        if (!sUserManager.exists(userId)) return null;
2831        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2832        synchronized (mPackages) {
2833            PackageParser.Provider p = mProviders.mProviders.get(component);
2834            if (DEBUG_PACKAGE_INFO) Log.v(
2835                TAG, "getProviderInfo " + component + ": " + p);
2836            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2837                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2838                if (ps == null) return null;
2839                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2840                        userId);
2841            }
2842        }
2843        return null;
2844    }
2845
2846    @Override
2847    public String[] getSystemSharedLibraryNames() {
2848        Set<String> libSet;
2849        synchronized (mPackages) {
2850            libSet = mSharedLibraries.keySet();
2851            int size = libSet.size();
2852            if (size > 0) {
2853                String[] libs = new String[size];
2854                libSet.toArray(libs);
2855                return libs;
2856            }
2857        }
2858        return null;
2859    }
2860
2861    /**
2862     * @hide
2863     */
2864    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2865        synchronized (mPackages) {
2866            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2867            if (lib != null && lib.apk != null) {
2868                return mPackages.get(lib.apk);
2869            }
2870        }
2871        return null;
2872    }
2873
2874    @Override
2875    public FeatureInfo[] getSystemAvailableFeatures() {
2876        Collection<FeatureInfo> featSet;
2877        synchronized (mPackages) {
2878            featSet = mAvailableFeatures.values();
2879            int size = featSet.size();
2880            if (size > 0) {
2881                FeatureInfo[] features = new FeatureInfo[size+1];
2882                featSet.toArray(features);
2883                FeatureInfo fi = new FeatureInfo();
2884                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2885                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2886                features[size] = fi;
2887                return features;
2888            }
2889        }
2890        return null;
2891    }
2892
2893    @Override
2894    public boolean hasSystemFeature(String name) {
2895        synchronized (mPackages) {
2896            return mAvailableFeatures.containsKey(name);
2897        }
2898    }
2899
2900    private void checkValidCaller(int uid, int userId) {
2901        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2902            return;
2903
2904        throw new SecurityException("Caller uid=" + uid
2905                + " is not privileged to communicate with user=" + userId);
2906    }
2907
2908    @Override
2909    public int checkPermission(String permName, String pkgName, int userId) {
2910        if (!sUserManager.exists(userId)) {
2911            return PackageManager.PERMISSION_DENIED;
2912        }
2913
2914        synchronized (mPackages) {
2915            final PackageParser.Package p = mPackages.get(pkgName);
2916            if (p != null && p.mExtras != null) {
2917                final PackageSetting ps = (PackageSetting) p.mExtras;
2918                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2919                    return PackageManager.PERMISSION_GRANTED;
2920                }
2921            }
2922        }
2923
2924        return PackageManager.PERMISSION_DENIED;
2925    }
2926
2927    @Override
2928    public int checkUidPermission(String permName, int uid) {
2929        final int userId = UserHandle.getUserId(uid);
2930
2931        if (!sUserManager.exists(userId)) {
2932            return PackageManager.PERMISSION_DENIED;
2933        }
2934
2935        synchronized (mPackages) {
2936            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2937            if (obj != null) {
2938                final SettingBase ps = (SettingBase) obj;
2939                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2940                    return PackageManager.PERMISSION_GRANTED;
2941                }
2942            } else {
2943                ArraySet<String> perms = mSystemPermissions.get(uid);
2944                if (perms != null && perms.contains(permName)) {
2945                    return PackageManager.PERMISSION_GRANTED;
2946                }
2947            }
2948        }
2949
2950        return PackageManager.PERMISSION_DENIED;
2951    }
2952
2953    /**
2954     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2955     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2956     * @param checkShell TODO(yamasani):
2957     * @param message the message to log on security exception
2958     */
2959    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2960            boolean checkShell, String message) {
2961        if (userId < 0) {
2962            throw new IllegalArgumentException("Invalid userId " + userId);
2963        }
2964        if (checkShell) {
2965            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2966        }
2967        if (userId == UserHandle.getUserId(callingUid)) return;
2968        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2969            if (requireFullPermission) {
2970                mContext.enforceCallingOrSelfPermission(
2971                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2972            } else {
2973                try {
2974                    mContext.enforceCallingOrSelfPermission(
2975                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2976                } catch (SecurityException se) {
2977                    mContext.enforceCallingOrSelfPermission(
2978                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2979                }
2980            }
2981        }
2982    }
2983
2984    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2985        if (callingUid == Process.SHELL_UID) {
2986            if (userHandle >= 0
2987                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2988                throw new SecurityException("Shell does not have permission to access user "
2989                        + userHandle);
2990            } else if (userHandle < 0) {
2991                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2992                        + Debug.getCallers(3));
2993            }
2994        }
2995    }
2996
2997    private BasePermission findPermissionTreeLP(String permName) {
2998        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2999            if (permName.startsWith(bp.name) &&
3000                    permName.length() > bp.name.length() &&
3001                    permName.charAt(bp.name.length()) == '.') {
3002                return bp;
3003            }
3004        }
3005        return null;
3006    }
3007
3008    private BasePermission checkPermissionTreeLP(String permName) {
3009        if (permName != null) {
3010            BasePermission bp = findPermissionTreeLP(permName);
3011            if (bp != null) {
3012                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3013                    return bp;
3014                }
3015                throw new SecurityException("Calling uid "
3016                        + Binder.getCallingUid()
3017                        + " is not allowed to add to permission tree "
3018                        + bp.name + " owned by uid " + bp.uid);
3019            }
3020        }
3021        throw new SecurityException("No permission tree found for " + permName);
3022    }
3023
3024    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3025        if (s1 == null) {
3026            return s2 == null;
3027        }
3028        if (s2 == null) {
3029            return false;
3030        }
3031        if (s1.getClass() != s2.getClass()) {
3032            return false;
3033        }
3034        return s1.equals(s2);
3035    }
3036
3037    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3038        if (pi1.icon != pi2.icon) return false;
3039        if (pi1.logo != pi2.logo) return false;
3040        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3041        if (!compareStrings(pi1.name, pi2.name)) return false;
3042        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3043        // We'll take care of setting this one.
3044        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3045        // These are not currently stored in settings.
3046        //if (!compareStrings(pi1.group, pi2.group)) return false;
3047        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3048        //if (pi1.labelRes != pi2.labelRes) return false;
3049        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3050        return true;
3051    }
3052
3053    int permissionInfoFootprint(PermissionInfo info) {
3054        int size = info.name.length();
3055        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3056        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3057        return size;
3058    }
3059
3060    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3061        int size = 0;
3062        for (BasePermission perm : mSettings.mPermissions.values()) {
3063            if (perm.uid == tree.uid) {
3064                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3065            }
3066        }
3067        return size;
3068    }
3069
3070    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3071        // We calculate the max size of permissions defined by this uid and throw
3072        // if that plus the size of 'info' would exceed our stated maximum.
3073        if (tree.uid != Process.SYSTEM_UID) {
3074            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3075            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3076                throw new SecurityException("Permission tree size cap exceeded");
3077            }
3078        }
3079    }
3080
3081    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3082        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3083            throw new SecurityException("Label must be specified in permission");
3084        }
3085        BasePermission tree = checkPermissionTreeLP(info.name);
3086        BasePermission bp = mSettings.mPermissions.get(info.name);
3087        boolean added = bp == null;
3088        boolean changed = true;
3089        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3090        if (added) {
3091            enforcePermissionCapLocked(info, tree);
3092            bp = new BasePermission(info.name, tree.sourcePackage,
3093                    BasePermission.TYPE_DYNAMIC);
3094        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3095            throw new SecurityException(
3096                    "Not allowed to modify non-dynamic permission "
3097                    + info.name);
3098        } else {
3099            if (bp.protectionLevel == fixedLevel
3100                    && bp.perm.owner.equals(tree.perm.owner)
3101                    && bp.uid == tree.uid
3102                    && comparePermissionInfos(bp.perm.info, info)) {
3103                changed = false;
3104            }
3105        }
3106        bp.protectionLevel = fixedLevel;
3107        info = new PermissionInfo(info);
3108        info.protectionLevel = fixedLevel;
3109        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3110        bp.perm.info.packageName = tree.perm.info.packageName;
3111        bp.uid = tree.uid;
3112        if (added) {
3113            mSettings.mPermissions.put(info.name, bp);
3114        }
3115        if (changed) {
3116            if (!async) {
3117                mSettings.writeLPr();
3118            } else {
3119                scheduleWriteSettingsLocked();
3120            }
3121        }
3122        return added;
3123    }
3124
3125    @Override
3126    public boolean addPermission(PermissionInfo info) {
3127        synchronized (mPackages) {
3128            return addPermissionLocked(info, false);
3129        }
3130    }
3131
3132    @Override
3133    public boolean addPermissionAsync(PermissionInfo info) {
3134        synchronized (mPackages) {
3135            return addPermissionLocked(info, true);
3136        }
3137    }
3138
3139    @Override
3140    public void removePermission(String name) {
3141        synchronized (mPackages) {
3142            checkPermissionTreeLP(name);
3143            BasePermission bp = mSettings.mPermissions.get(name);
3144            if (bp != null) {
3145                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3146                    throw new SecurityException(
3147                            "Not allowed to modify non-dynamic permission "
3148                            + name);
3149                }
3150                mSettings.mPermissions.remove(name);
3151                mSettings.writeLPr();
3152            }
3153        }
3154    }
3155
3156    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3157            BasePermission bp) {
3158        int index = pkg.requestedPermissions.indexOf(bp.name);
3159        if (index == -1) {
3160            throw new SecurityException("Package " + pkg.packageName
3161                    + " has not requested permission " + bp.name);
3162        }
3163        if (!bp.isRuntime()) {
3164            throw new SecurityException("Permission " + bp.name
3165                    + " is not a changeable permission type");
3166        }
3167    }
3168
3169    @Override
3170    public void grantRuntimePermission(String packageName, String name, final int userId) {
3171        if (!sUserManager.exists(userId)) {
3172            Log.e(TAG, "No such user:" + userId);
3173            return;
3174        }
3175
3176        mContext.enforceCallingOrSelfPermission(
3177                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3178                "grantRuntimePermission");
3179
3180        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3181                "grantRuntimePermission");
3182
3183        final SettingBase sb;
3184
3185        synchronized (mPackages) {
3186            final PackageParser.Package pkg = mPackages.get(packageName);
3187            if (pkg == null) {
3188                throw new IllegalArgumentException("Unknown package: " + packageName);
3189            }
3190
3191            final BasePermission bp = mSettings.mPermissions.get(name);
3192            if (bp == null) {
3193                throw new IllegalArgumentException("Unknown permission: " + name);
3194            }
3195
3196            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3197
3198            sb = (SettingBase) pkg.mExtras;
3199            if (sb == null) {
3200                throw new IllegalArgumentException("Unknown package: " + packageName);
3201            }
3202
3203            final PermissionsState permissionsState = sb.getPermissionsState();
3204
3205            final int flags = permissionsState.getPermissionFlags(name, userId);
3206            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3207                throw new SecurityException("Cannot grant system fixed permission: "
3208                        + name + " for package: " + packageName);
3209            }
3210
3211            final int result = permissionsState.grantRuntimePermission(bp, userId);
3212            switch (result) {
3213                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3214                    return;
3215                }
3216
3217                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3218                    mHandler.post(new Runnable() {
3219                        @Override
3220                        public void run() {
3221                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3222                        }
3223                    });
3224                } break;
3225            }
3226
3227            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3228
3229            // Not critical if that is lost - app has to request again.
3230            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3231        }
3232    }
3233
3234    @Override
3235    public void revokeRuntimePermission(String packageName, String name, int userId) {
3236        if (!sUserManager.exists(userId)) {
3237            Log.e(TAG, "No such user:" + userId);
3238            return;
3239        }
3240
3241        mContext.enforceCallingOrSelfPermission(
3242                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3243                "revokeRuntimePermission");
3244
3245        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3246                "revokeRuntimePermission");
3247
3248        final SettingBase sb;
3249
3250        synchronized (mPackages) {
3251            final PackageParser.Package pkg = mPackages.get(packageName);
3252            if (pkg == null) {
3253                throw new IllegalArgumentException("Unknown package: " + packageName);
3254            }
3255
3256            final BasePermission bp = mSettings.mPermissions.get(name);
3257            if (bp == null) {
3258                throw new IllegalArgumentException("Unknown permission: " + name);
3259            }
3260
3261            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3262
3263            sb = (SettingBase) pkg.mExtras;
3264            if (sb == null) {
3265                throw new IllegalArgumentException("Unknown package: " + packageName);
3266            }
3267
3268            final PermissionsState permissionsState = sb.getPermissionsState();
3269
3270            final int flags = permissionsState.getPermissionFlags(name, userId);
3271            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3272                throw new SecurityException("Cannot revoke system fixed permission: "
3273                        + name + " for package: " + packageName);
3274            }
3275
3276            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3277                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3278                return;
3279            }
3280
3281            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3282
3283            // Critical, after this call app should never have the permission.
3284            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3285        }
3286
3287        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3288    }
3289
3290    @Override
3291    public int getPermissionFlags(String name, String packageName, int userId) {
3292        if (!sUserManager.exists(userId)) {
3293            return 0;
3294        }
3295
3296        mContext.enforceCallingOrSelfPermission(
3297                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3298                "getPermissionFlags");
3299
3300        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3301                "getPermissionFlags");
3302
3303        synchronized (mPackages) {
3304            final PackageParser.Package pkg = mPackages.get(packageName);
3305            if (pkg == null) {
3306                throw new IllegalArgumentException("Unknown package: " + packageName);
3307            }
3308
3309            final BasePermission bp = mSettings.mPermissions.get(name);
3310            if (bp == null) {
3311                throw new IllegalArgumentException("Unknown permission: " + name);
3312            }
3313
3314            SettingBase sb = (SettingBase) pkg.mExtras;
3315            if (sb == null) {
3316                throw new IllegalArgumentException("Unknown package: " + packageName);
3317            }
3318
3319            PermissionsState permissionsState = sb.getPermissionsState();
3320            return permissionsState.getPermissionFlags(name, userId);
3321        }
3322    }
3323
3324    @Override
3325    public void updatePermissionFlags(String name, String packageName, int flagMask,
3326            int flagValues, int userId) {
3327        if (!sUserManager.exists(userId)) {
3328            return;
3329        }
3330
3331        mContext.enforceCallingOrSelfPermission(
3332                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3333                "updatePermissionFlags");
3334
3335        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3336                "updatePermissionFlags");
3337
3338        // Only the system can change policy and system fixed flags.
3339        if (getCallingUid() != Process.SYSTEM_UID) {
3340            flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3341            flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3342
3343            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3344            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3345        }
3346
3347        synchronized (mPackages) {
3348            final PackageParser.Package pkg = mPackages.get(packageName);
3349            if (pkg == null) {
3350                throw new IllegalArgumentException("Unknown package: " + packageName);
3351            }
3352
3353            final BasePermission bp = mSettings.mPermissions.get(name);
3354            if (bp == null) {
3355                throw new IllegalArgumentException("Unknown permission: " + name);
3356            }
3357
3358            SettingBase sb = (SettingBase) pkg.mExtras;
3359            if (sb == null) {
3360                throw new IllegalArgumentException("Unknown package: " + packageName);
3361            }
3362
3363            PermissionsState permissionsState = sb.getPermissionsState();
3364
3365            // Only the package manager can change flags for system component permissions.
3366            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3367            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3368                return;
3369            }
3370
3371            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3372                // Install and runtime permissions are stored in different places,
3373                // so figure out what permission changed and persist the change.
3374                if (permissionsState.getInstallPermissionState(name) != null) {
3375                    scheduleWriteSettingsLocked();
3376                } else if (permissionsState.getRuntimePermissionState(name, userId) != null) {
3377                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3378                }
3379            }
3380        }
3381    }
3382
3383    @Override
3384    public boolean shouldShowRequestPermissionRationale(String permissionName,
3385            String packageName, int userId) {
3386        if (UserHandle.getCallingUserId() != userId) {
3387            mContext.enforceCallingPermission(
3388                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3389                    "canShowRequestPermissionRationale for user " + userId);
3390        }
3391
3392        final int uid = getPackageUid(packageName, userId);
3393        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3394            return false;
3395        }
3396
3397        if (checkPermission(permissionName, packageName, userId)
3398                == PackageManager.PERMISSION_GRANTED) {
3399            return false;
3400        }
3401
3402        final int flags;
3403
3404        final long identity = Binder.clearCallingIdentity();
3405        try {
3406            flags = getPermissionFlags(permissionName,
3407                    packageName, userId);
3408        } finally {
3409            Binder.restoreCallingIdentity(identity);
3410        }
3411
3412        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3413                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3414                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3415
3416        if ((flags & fixedFlags) != 0) {
3417            return false;
3418        }
3419
3420        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3421    }
3422
3423    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3424        BasePermission bp = mSettings.mPermissions.get(permission);
3425        if (bp == null) {
3426            throw new SecurityException("Missing " + permission + " permission");
3427        }
3428
3429        SettingBase sb = (SettingBase) pkg.mExtras;
3430        PermissionsState permissionsState = sb.getPermissionsState();
3431
3432        if (permissionsState.grantInstallPermission(bp) !=
3433                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3434            scheduleWriteSettingsLocked();
3435        }
3436    }
3437
3438    @Override
3439    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3440        mContext.enforceCallingOrSelfPermission(
3441                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3442                "addOnPermissionsChangeListener");
3443
3444        synchronized (mPackages) {
3445            mOnPermissionChangeListeners.addListenerLocked(listener);
3446        }
3447    }
3448
3449    @Override
3450    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3451        synchronized (mPackages) {
3452            mOnPermissionChangeListeners.removeListenerLocked(listener);
3453        }
3454    }
3455
3456    @Override
3457    public boolean isProtectedBroadcast(String actionName) {
3458        synchronized (mPackages) {
3459            return mProtectedBroadcasts.contains(actionName);
3460        }
3461    }
3462
3463    @Override
3464    public int checkSignatures(String pkg1, String pkg2) {
3465        synchronized (mPackages) {
3466            final PackageParser.Package p1 = mPackages.get(pkg1);
3467            final PackageParser.Package p2 = mPackages.get(pkg2);
3468            if (p1 == null || p1.mExtras == null
3469                    || p2 == null || p2.mExtras == null) {
3470                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3471            }
3472            return compareSignatures(p1.mSignatures, p2.mSignatures);
3473        }
3474    }
3475
3476    @Override
3477    public int checkUidSignatures(int uid1, int uid2) {
3478        // Map to base uids.
3479        uid1 = UserHandle.getAppId(uid1);
3480        uid2 = UserHandle.getAppId(uid2);
3481        // reader
3482        synchronized (mPackages) {
3483            Signature[] s1;
3484            Signature[] s2;
3485            Object obj = mSettings.getUserIdLPr(uid1);
3486            if (obj != null) {
3487                if (obj instanceof SharedUserSetting) {
3488                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3489                } else if (obj instanceof PackageSetting) {
3490                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3491                } else {
3492                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3493                }
3494            } else {
3495                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3496            }
3497            obj = mSettings.getUserIdLPr(uid2);
3498            if (obj != null) {
3499                if (obj instanceof SharedUserSetting) {
3500                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3501                } else if (obj instanceof PackageSetting) {
3502                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3503                } else {
3504                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3505                }
3506            } else {
3507                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3508            }
3509            return compareSignatures(s1, s2);
3510        }
3511    }
3512
3513    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3514        final long identity = Binder.clearCallingIdentity();
3515        try {
3516            if (sb instanceof SharedUserSetting) {
3517                SharedUserSetting sus = (SharedUserSetting) sb;
3518                final int packageCount = sus.packages.size();
3519                for (int i = 0; i < packageCount; i++) {
3520                    PackageSetting susPs = sus.packages.valueAt(i);
3521                    if (userId == UserHandle.USER_ALL) {
3522                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3523                    } else {
3524                        final int uid = UserHandle.getUid(userId, susPs.appId);
3525                        killUid(uid, reason);
3526                    }
3527                }
3528            } else if (sb instanceof PackageSetting) {
3529                PackageSetting ps = (PackageSetting) sb;
3530                if (userId == UserHandle.USER_ALL) {
3531                    killApplication(ps.pkg.packageName, ps.appId, reason);
3532                } else {
3533                    final int uid = UserHandle.getUid(userId, ps.appId);
3534                    killUid(uid, reason);
3535                }
3536            }
3537        } finally {
3538            Binder.restoreCallingIdentity(identity);
3539        }
3540    }
3541
3542    private static void killUid(int uid, String reason) {
3543        IActivityManager am = ActivityManagerNative.getDefault();
3544        if (am != null) {
3545            try {
3546                am.killUid(uid, reason);
3547            } catch (RemoteException e) {
3548                /* ignore - same process */
3549            }
3550        }
3551    }
3552
3553    /**
3554     * Compares two sets of signatures. Returns:
3555     * <br />
3556     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3557     * <br />
3558     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3559     * <br />
3560     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3561     * <br />
3562     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3563     * <br />
3564     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3565     */
3566    static int compareSignatures(Signature[] s1, Signature[] s2) {
3567        if (s1 == null) {
3568            return s2 == null
3569                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3570                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3571        }
3572
3573        if (s2 == null) {
3574            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3575        }
3576
3577        if (s1.length != s2.length) {
3578            return PackageManager.SIGNATURE_NO_MATCH;
3579        }
3580
3581        // Since both signature sets are of size 1, we can compare without HashSets.
3582        if (s1.length == 1) {
3583            return s1[0].equals(s2[0]) ?
3584                    PackageManager.SIGNATURE_MATCH :
3585                    PackageManager.SIGNATURE_NO_MATCH;
3586        }
3587
3588        ArraySet<Signature> set1 = new ArraySet<Signature>();
3589        for (Signature sig : s1) {
3590            set1.add(sig);
3591        }
3592        ArraySet<Signature> set2 = new ArraySet<Signature>();
3593        for (Signature sig : s2) {
3594            set2.add(sig);
3595        }
3596        // Make sure s2 contains all signatures in s1.
3597        if (set1.equals(set2)) {
3598            return PackageManager.SIGNATURE_MATCH;
3599        }
3600        return PackageManager.SIGNATURE_NO_MATCH;
3601    }
3602
3603    /**
3604     * If the database version for this type of package (internal storage or
3605     * external storage) is less than the version where package signatures
3606     * were updated, return true.
3607     */
3608    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3609        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3610                DatabaseVersion.SIGNATURE_END_ENTITY))
3611                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3612                        DatabaseVersion.SIGNATURE_END_ENTITY));
3613    }
3614
3615    /**
3616     * Used for backward compatibility to make sure any packages with
3617     * certificate chains get upgraded to the new style. {@code existingSigs}
3618     * will be in the old format (since they were stored on disk from before the
3619     * system upgrade) and {@code scannedSigs} will be in the newer format.
3620     */
3621    private int compareSignaturesCompat(PackageSignatures existingSigs,
3622            PackageParser.Package scannedPkg) {
3623        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3624            return PackageManager.SIGNATURE_NO_MATCH;
3625        }
3626
3627        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3628        for (Signature sig : existingSigs.mSignatures) {
3629            existingSet.add(sig);
3630        }
3631        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3632        for (Signature sig : scannedPkg.mSignatures) {
3633            try {
3634                Signature[] chainSignatures = sig.getChainSignatures();
3635                for (Signature chainSig : chainSignatures) {
3636                    scannedCompatSet.add(chainSig);
3637                }
3638            } catch (CertificateEncodingException e) {
3639                scannedCompatSet.add(sig);
3640            }
3641        }
3642        /*
3643         * Make sure the expanded scanned set contains all signatures in the
3644         * existing one.
3645         */
3646        if (scannedCompatSet.equals(existingSet)) {
3647            // Migrate the old signatures to the new scheme.
3648            existingSigs.assignSignatures(scannedPkg.mSignatures);
3649            // The new KeySets will be re-added later in the scanning process.
3650            synchronized (mPackages) {
3651                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3652            }
3653            return PackageManager.SIGNATURE_MATCH;
3654        }
3655        return PackageManager.SIGNATURE_NO_MATCH;
3656    }
3657
3658    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3659        if (isExternal(scannedPkg)) {
3660            return mSettings.isExternalDatabaseVersionOlderThan(
3661                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3662        } else {
3663            return mSettings.isInternalDatabaseVersionOlderThan(
3664                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3665        }
3666    }
3667
3668    private int compareSignaturesRecover(PackageSignatures existingSigs,
3669            PackageParser.Package scannedPkg) {
3670        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3671            return PackageManager.SIGNATURE_NO_MATCH;
3672        }
3673
3674        String msg = null;
3675        try {
3676            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3677                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3678                        + scannedPkg.packageName);
3679                return PackageManager.SIGNATURE_MATCH;
3680            }
3681        } catch (CertificateException e) {
3682            msg = e.getMessage();
3683        }
3684
3685        logCriticalInfo(Log.INFO,
3686                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3687        return PackageManager.SIGNATURE_NO_MATCH;
3688    }
3689
3690    @Override
3691    public String[] getPackagesForUid(int uid) {
3692        uid = UserHandle.getAppId(uid);
3693        // reader
3694        synchronized (mPackages) {
3695            Object obj = mSettings.getUserIdLPr(uid);
3696            if (obj instanceof SharedUserSetting) {
3697                final SharedUserSetting sus = (SharedUserSetting) obj;
3698                final int N = sus.packages.size();
3699                final String[] res = new String[N];
3700                final Iterator<PackageSetting> it = sus.packages.iterator();
3701                int i = 0;
3702                while (it.hasNext()) {
3703                    res[i++] = it.next().name;
3704                }
3705                return res;
3706            } else if (obj instanceof PackageSetting) {
3707                final PackageSetting ps = (PackageSetting) obj;
3708                return new String[] { ps.name };
3709            }
3710        }
3711        return null;
3712    }
3713
3714    @Override
3715    public String getNameForUid(int uid) {
3716        // reader
3717        synchronized (mPackages) {
3718            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3719            if (obj instanceof SharedUserSetting) {
3720                final SharedUserSetting sus = (SharedUserSetting) obj;
3721                return sus.name + ":" + sus.userId;
3722            } else if (obj instanceof PackageSetting) {
3723                final PackageSetting ps = (PackageSetting) obj;
3724                return ps.name;
3725            }
3726        }
3727        return null;
3728    }
3729
3730    @Override
3731    public int getUidForSharedUser(String sharedUserName) {
3732        if(sharedUserName == null) {
3733            return -1;
3734        }
3735        // reader
3736        synchronized (mPackages) {
3737            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3738            if (suid == null) {
3739                return -1;
3740            }
3741            return suid.userId;
3742        }
3743    }
3744
3745    @Override
3746    public int getFlagsForUid(int uid) {
3747        synchronized (mPackages) {
3748            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3749            if (obj instanceof SharedUserSetting) {
3750                final SharedUserSetting sus = (SharedUserSetting) obj;
3751                return sus.pkgFlags;
3752            } else if (obj instanceof PackageSetting) {
3753                final PackageSetting ps = (PackageSetting) obj;
3754                return ps.pkgFlags;
3755            }
3756        }
3757        return 0;
3758    }
3759
3760    @Override
3761    public int getPrivateFlagsForUid(int uid) {
3762        synchronized (mPackages) {
3763            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3764            if (obj instanceof SharedUserSetting) {
3765                final SharedUserSetting sus = (SharedUserSetting) obj;
3766                return sus.pkgPrivateFlags;
3767            } else if (obj instanceof PackageSetting) {
3768                final PackageSetting ps = (PackageSetting) obj;
3769                return ps.pkgPrivateFlags;
3770            }
3771        }
3772        return 0;
3773    }
3774
3775    @Override
3776    public boolean isUidPrivileged(int uid) {
3777        uid = UserHandle.getAppId(uid);
3778        // reader
3779        synchronized (mPackages) {
3780            Object obj = mSettings.getUserIdLPr(uid);
3781            if (obj instanceof SharedUserSetting) {
3782                final SharedUserSetting sus = (SharedUserSetting) obj;
3783                final Iterator<PackageSetting> it = sus.packages.iterator();
3784                while (it.hasNext()) {
3785                    if (it.next().isPrivileged()) {
3786                        return true;
3787                    }
3788                }
3789            } else if (obj instanceof PackageSetting) {
3790                final PackageSetting ps = (PackageSetting) obj;
3791                return ps.isPrivileged();
3792            }
3793        }
3794        return false;
3795    }
3796
3797    @Override
3798    public String[] getAppOpPermissionPackages(String permissionName) {
3799        synchronized (mPackages) {
3800            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3801            if (pkgs == null) {
3802                return null;
3803            }
3804            return pkgs.toArray(new String[pkgs.size()]);
3805        }
3806    }
3807
3808    @Override
3809    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3810            int flags, int userId) {
3811        if (!sUserManager.exists(userId)) return null;
3812        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3813        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3814        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3815    }
3816
3817    @Override
3818    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3819            IntentFilter filter, int match, ComponentName activity) {
3820        final int userId = UserHandle.getCallingUserId();
3821        if (DEBUG_PREFERRED) {
3822            Log.v(TAG, "setLastChosenActivity intent=" + intent
3823                + " resolvedType=" + resolvedType
3824                + " flags=" + flags
3825                + " filter=" + filter
3826                + " match=" + match
3827                + " activity=" + activity);
3828            filter.dump(new PrintStreamPrinter(System.out), "    ");
3829        }
3830        intent.setComponent(null);
3831        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3832        // Find any earlier preferred or last chosen entries and nuke them
3833        findPreferredActivity(intent, resolvedType,
3834                flags, query, 0, false, true, false, userId);
3835        // Add the new activity as the last chosen for this filter
3836        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3837                "Setting last chosen");
3838    }
3839
3840    @Override
3841    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3842        final int userId = UserHandle.getCallingUserId();
3843        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3844        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3845        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3846                false, false, false, userId);
3847    }
3848
3849    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3850            int flags, List<ResolveInfo> query, int userId) {
3851        if (query != null) {
3852            final int N = query.size();
3853            if (N == 1) {
3854                return query.get(0);
3855            } else if (N > 1) {
3856                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3857                // If there is more than one activity with the same priority,
3858                // then let the user decide between them.
3859                ResolveInfo r0 = query.get(0);
3860                ResolveInfo r1 = query.get(1);
3861                if (DEBUG_INTENT_MATCHING || debug) {
3862                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3863                            + r1.activityInfo.name + "=" + r1.priority);
3864                }
3865                // If the first activity has a higher priority, or a different
3866                // default, then it is always desireable to pick it.
3867                if (r0.priority != r1.priority
3868                        || r0.preferredOrder != r1.preferredOrder
3869                        || r0.isDefault != r1.isDefault) {
3870                    return query.get(0);
3871                }
3872                // If we have saved a preference for a preferred activity for
3873                // this Intent, use that.
3874                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3875                        flags, query, r0.priority, true, false, debug, userId);
3876                if (ri != null) {
3877                    return ri;
3878                }
3879                if (userId != 0) {
3880                    ri = new ResolveInfo(mResolveInfo);
3881                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3882                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3883                            ri.activityInfo.applicationInfo);
3884                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3885                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3886                    return ri;
3887                }
3888                return mResolveInfo;
3889            }
3890        }
3891        return null;
3892    }
3893
3894    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3895            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3896        final int N = query.size();
3897        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3898                .get(userId);
3899        // Get the list of persistent preferred activities that handle the intent
3900        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3901        List<PersistentPreferredActivity> pprefs = ppir != null
3902                ? ppir.queryIntent(intent, resolvedType,
3903                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3904                : null;
3905        if (pprefs != null && pprefs.size() > 0) {
3906            final int M = pprefs.size();
3907            for (int i=0; i<M; i++) {
3908                final PersistentPreferredActivity ppa = pprefs.get(i);
3909                if (DEBUG_PREFERRED || debug) {
3910                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3911                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3912                            + "\n  component=" + ppa.mComponent);
3913                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3914                }
3915                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3916                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3917                if (DEBUG_PREFERRED || debug) {
3918                    Slog.v(TAG, "Found persistent preferred activity:");
3919                    if (ai != null) {
3920                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3921                    } else {
3922                        Slog.v(TAG, "  null");
3923                    }
3924                }
3925                if (ai == null) {
3926                    // This previously registered persistent preferred activity
3927                    // component is no longer known. Ignore it and do NOT remove it.
3928                    continue;
3929                }
3930                for (int j=0; j<N; j++) {
3931                    final ResolveInfo ri = query.get(j);
3932                    if (!ri.activityInfo.applicationInfo.packageName
3933                            .equals(ai.applicationInfo.packageName)) {
3934                        continue;
3935                    }
3936                    if (!ri.activityInfo.name.equals(ai.name)) {
3937                        continue;
3938                    }
3939                    //  Found a persistent preference that can handle the intent.
3940                    if (DEBUG_PREFERRED || debug) {
3941                        Slog.v(TAG, "Returning persistent preferred activity: " +
3942                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3943                    }
3944                    return ri;
3945                }
3946            }
3947        }
3948        return null;
3949    }
3950
3951    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3952            List<ResolveInfo> query, int priority, boolean always,
3953            boolean removeMatches, boolean debug, int userId) {
3954        if (!sUserManager.exists(userId)) return null;
3955        // writer
3956        synchronized (mPackages) {
3957            if (intent.getSelector() != null) {
3958                intent = intent.getSelector();
3959            }
3960            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3961
3962            // Try to find a matching persistent preferred activity.
3963            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3964                    debug, userId);
3965
3966            // If a persistent preferred activity matched, use it.
3967            if (pri != null) {
3968                return pri;
3969            }
3970
3971            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3972            // Get the list of preferred activities that handle the intent
3973            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3974            List<PreferredActivity> prefs = pir != null
3975                    ? pir.queryIntent(intent, resolvedType,
3976                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3977                    : null;
3978            if (prefs != null && prefs.size() > 0) {
3979                boolean changed = false;
3980                try {
3981                    // First figure out how good the original match set is.
3982                    // We will only allow preferred activities that came
3983                    // from the same match quality.
3984                    int match = 0;
3985
3986                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3987
3988                    final int N = query.size();
3989                    for (int j=0; j<N; j++) {
3990                        final ResolveInfo ri = query.get(j);
3991                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3992                                + ": 0x" + Integer.toHexString(match));
3993                        if (ri.match > match) {
3994                            match = ri.match;
3995                        }
3996                    }
3997
3998                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3999                            + Integer.toHexString(match));
4000
4001                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4002                    final int M = prefs.size();
4003                    for (int i=0; i<M; i++) {
4004                        final PreferredActivity pa = prefs.get(i);
4005                        if (DEBUG_PREFERRED || debug) {
4006                            Slog.v(TAG, "Checking PreferredActivity ds="
4007                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4008                                    + "\n  component=" + pa.mPref.mComponent);
4009                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4010                        }
4011                        if (pa.mPref.mMatch != match) {
4012                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4013                                    + Integer.toHexString(pa.mPref.mMatch));
4014                            continue;
4015                        }
4016                        // If it's not an "always" type preferred activity and that's what we're
4017                        // looking for, skip it.
4018                        if (always && !pa.mPref.mAlways) {
4019                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4020                            continue;
4021                        }
4022                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4023                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4024                        if (DEBUG_PREFERRED || debug) {
4025                            Slog.v(TAG, "Found preferred activity:");
4026                            if (ai != null) {
4027                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4028                            } else {
4029                                Slog.v(TAG, "  null");
4030                            }
4031                        }
4032                        if (ai == null) {
4033                            // This previously registered preferred activity
4034                            // component is no longer known.  Most likely an update
4035                            // to the app was installed and in the new version this
4036                            // component no longer exists.  Clean it up by removing
4037                            // it from the preferred activities list, and skip it.
4038                            Slog.w(TAG, "Removing dangling preferred activity: "
4039                                    + pa.mPref.mComponent);
4040                            pir.removeFilter(pa);
4041                            changed = true;
4042                            continue;
4043                        }
4044                        for (int j=0; j<N; j++) {
4045                            final ResolveInfo ri = query.get(j);
4046                            if (!ri.activityInfo.applicationInfo.packageName
4047                                    .equals(ai.applicationInfo.packageName)) {
4048                                continue;
4049                            }
4050                            if (!ri.activityInfo.name.equals(ai.name)) {
4051                                continue;
4052                            }
4053
4054                            if (removeMatches) {
4055                                pir.removeFilter(pa);
4056                                changed = true;
4057                                if (DEBUG_PREFERRED) {
4058                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4059                                }
4060                                break;
4061                            }
4062
4063                            // Okay we found a previously set preferred or last chosen app.
4064                            // If the result set is different from when this
4065                            // was created, we need to clear it and re-ask the
4066                            // user their preference, if we're looking for an "always" type entry.
4067                            if (always && !pa.mPref.sameSet(query)) {
4068                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4069                                        + intent + " type " + resolvedType);
4070                                if (DEBUG_PREFERRED) {
4071                                    Slog.v(TAG, "Removing preferred activity since set changed "
4072                                            + pa.mPref.mComponent);
4073                                }
4074                                pir.removeFilter(pa);
4075                                // Re-add the filter as a "last chosen" entry (!always)
4076                                PreferredActivity lastChosen = new PreferredActivity(
4077                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4078                                pir.addFilter(lastChosen);
4079                                changed = true;
4080                                return null;
4081                            }
4082
4083                            // Yay! Either the set matched or we're looking for the last chosen
4084                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4085                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4086                            return ri;
4087                        }
4088                    }
4089                } finally {
4090                    if (changed) {
4091                        if (DEBUG_PREFERRED) {
4092                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4093                        }
4094                        scheduleWritePackageRestrictionsLocked(userId);
4095                    }
4096                }
4097            }
4098        }
4099        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4100        return null;
4101    }
4102
4103    /*
4104     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4105     */
4106    @Override
4107    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4108            int targetUserId) {
4109        mContext.enforceCallingOrSelfPermission(
4110                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4111        List<CrossProfileIntentFilter> matches =
4112                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4113        if (matches != null) {
4114            int size = matches.size();
4115            for (int i = 0; i < size; i++) {
4116                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4117            }
4118        }
4119        if (hasWebURI(intent)) {
4120            // cross-profile app linking works only towards the parent.
4121            final UserInfo parent = getProfileParent(sourceUserId);
4122            synchronized(mPackages) {
4123                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4124                        parent.id) != null;
4125            }
4126        }
4127        return false;
4128    }
4129
4130    private UserInfo getProfileParent(int userId) {
4131        final long identity = Binder.clearCallingIdentity();
4132        try {
4133            return sUserManager.getProfileParent(userId);
4134        } finally {
4135            Binder.restoreCallingIdentity(identity);
4136        }
4137    }
4138
4139    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4140            String resolvedType, int userId) {
4141        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4142        if (resolver != null) {
4143            return resolver.queryIntent(intent, resolvedType, false, userId);
4144        }
4145        return null;
4146    }
4147
4148    @Override
4149    public List<ResolveInfo> queryIntentActivities(Intent intent,
4150            String resolvedType, int flags, int userId) {
4151        if (!sUserManager.exists(userId)) return Collections.emptyList();
4152        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4153        ComponentName comp = intent.getComponent();
4154        if (comp == null) {
4155            if (intent.getSelector() != null) {
4156                intent = intent.getSelector();
4157                comp = intent.getComponent();
4158            }
4159        }
4160
4161        if (comp != null) {
4162            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4163            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4164            if (ai != null) {
4165                final ResolveInfo ri = new ResolveInfo();
4166                ri.activityInfo = ai;
4167                list.add(ri);
4168            }
4169            return list;
4170        }
4171
4172        // reader
4173        synchronized (mPackages) {
4174            final String pkgName = intent.getPackage();
4175            if (pkgName == null) {
4176                List<CrossProfileIntentFilter> matchingFilters =
4177                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4178                // Check for results that need to skip the current profile.
4179                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4180                        resolvedType, flags, userId);
4181                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4182                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4183                    result.add(xpResolveInfo);
4184                    return filterIfNotPrimaryUser(result, userId);
4185                }
4186
4187                // Check for results in the current profile.
4188                List<ResolveInfo> result = mActivities.queryIntent(
4189                        intent, resolvedType, flags, userId);
4190
4191                // Check for cross profile results.
4192                xpResolveInfo = queryCrossProfileIntents(
4193                        matchingFilters, intent, resolvedType, flags, userId);
4194                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4195                    result.add(xpResolveInfo);
4196                    Collections.sort(result, mResolvePrioritySorter);
4197                }
4198                result = filterIfNotPrimaryUser(result, userId);
4199                if (hasWebURI(intent)) {
4200                    CrossProfileDomainInfo xpDomainInfo = null;
4201                    final UserInfo parent = getProfileParent(userId);
4202                    if (parent != null) {
4203                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4204                                flags, userId, parent.id);
4205                    }
4206                    if (xpDomainInfo != null) {
4207                        if (xpResolveInfo != null) {
4208                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4209                            // in the result.
4210                            result.remove(xpResolveInfo);
4211                        }
4212                        if (result.size() == 0) {
4213                            result.add(xpDomainInfo.resolveInfo);
4214                            return result;
4215                        }
4216                    } else if (result.size() <= 1) {
4217                        return result;
4218                    }
4219                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4220                            xpDomainInfo);
4221                    Collections.sort(result, mResolvePrioritySorter);
4222                }
4223                return result;
4224            }
4225            final PackageParser.Package pkg = mPackages.get(pkgName);
4226            if (pkg != null) {
4227                return filterIfNotPrimaryUser(
4228                        mActivities.queryIntentForPackage(
4229                                intent, resolvedType, flags, pkg.activities, userId),
4230                        userId);
4231            }
4232            return new ArrayList<ResolveInfo>();
4233        }
4234    }
4235
4236    private static class CrossProfileDomainInfo {
4237        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4238        ResolveInfo resolveInfo;
4239        /* Best domain verification status of the activities found in the other profile */
4240        int bestDomainVerificationStatus;
4241    }
4242
4243    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4244            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4245        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_APP_LINKING,
4246                sourceUserId)) {
4247            return null;
4248        }
4249        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4250                resolvedType, flags, parentUserId);
4251
4252        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4253            return null;
4254        }
4255        CrossProfileDomainInfo result = null;
4256        int size = resultTargetUser.size();
4257        for (int i = 0; i < size; i++) {
4258            ResolveInfo riTargetUser = resultTargetUser.get(i);
4259            // Intent filter verification is only for filters that specify a host. So don't return
4260            // those that handle all web uris.
4261            if (riTargetUser.handleAllWebDataURI) {
4262                continue;
4263            }
4264            String packageName = riTargetUser.activityInfo.packageName;
4265            PackageSetting ps = mSettings.mPackages.get(packageName);
4266            if (ps == null) {
4267                continue;
4268            }
4269            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4270            if (result == null) {
4271                result = new CrossProfileDomainInfo();
4272                result.resolveInfo =
4273                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4274                result.bestDomainVerificationStatus = status;
4275            } else {
4276                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4277                        result.bestDomainVerificationStatus);
4278            }
4279        }
4280        return result;
4281    }
4282
4283    /**
4284     * Verification statuses are ordered from the worse to the best, except for
4285     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4286     */
4287    private int bestDomainVerificationStatus(int status1, int status2) {
4288        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4289            return status2;
4290        }
4291        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4292            return status1;
4293        }
4294        return (int) MathUtils.max(status1, status2);
4295    }
4296
4297    private boolean isUserEnabled(int userId) {
4298        long callingId = Binder.clearCallingIdentity();
4299        try {
4300            UserInfo userInfo = sUserManager.getUserInfo(userId);
4301            return userInfo != null && userInfo.isEnabled();
4302        } finally {
4303            Binder.restoreCallingIdentity(callingId);
4304        }
4305    }
4306
4307    /**
4308     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4309     *
4310     * @return filtered list
4311     */
4312    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4313        if (userId == UserHandle.USER_OWNER) {
4314            return resolveInfos;
4315        }
4316        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4317            ResolveInfo info = resolveInfos.get(i);
4318            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4319                resolveInfos.remove(i);
4320            }
4321        }
4322        return resolveInfos;
4323    }
4324
4325    private static boolean hasWebURI(Intent intent) {
4326        if (intent.getData() == null) {
4327            return false;
4328        }
4329        final String scheme = intent.getScheme();
4330        if (TextUtils.isEmpty(scheme)) {
4331            return false;
4332        }
4333        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4334    }
4335
4336    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4337            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4338        if (DEBUG_PREFERRED) {
4339            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4340                    candidates.size());
4341        }
4342
4343        final int userId = UserHandle.getCallingUserId();
4344        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4345        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4346        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4347        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4348        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4349
4350        synchronized (mPackages) {
4351            final int count = candidates.size();
4352            // First, try to use the domain prefered App. Partition the candidates into four lists:
4353            // one for the final results, one for the "do not use ever", one for "undefined status"
4354            // and finally one for "Browser App type".
4355            for (int n=0; n<count; n++) {
4356                ResolveInfo info = candidates.get(n);
4357                String packageName = info.activityInfo.packageName;
4358                PackageSetting ps = mSettings.mPackages.get(packageName);
4359                if (ps != null) {
4360                    // Add to the special match all list (Browser use case)
4361                    if (info.handleAllWebDataURI) {
4362                        matchAllList.add(info);
4363                        continue;
4364                    }
4365                    // Try to get the status from User settings first
4366                    int status = getDomainVerificationStatusLPr(ps, userId);
4367                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4368                        alwaysList.add(info);
4369                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4370                        neverList.add(info);
4371                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4372                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4373                        undefinedList.add(info);
4374                    }
4375                }
4376            }
4377            // First try to add the "always" resolution for the current user if there is any
4378            if (alwaysList.size() > 0) {
4379                result.addAll(alwaysList);
4380            // if there is an "always" for the parent user, add it.
4381            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4382                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4383                result.add(xpDomainInfo.resolveInfo);
4384            } else {
4385                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4386                result.addAll(undefinedList);
4387                if (xpDomainInfo != null && (
4388                        xpDomainInfo.bestDomainVerificationStatus
4389                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4390                        || xpDomainInfo.bestDomainVerificationStatus
4391                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4392                    result.add(xpDomainInfo.resolveInfo);
4393                }
4394                // Also add Browsers (all of them or only the default one)
4395                if ((flags & MATCH_ALL) != 0) {
4396                    result.addAll(matchAllList);
4397                } else {
4398                    // Try to add the Default Browser if we can
4399                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4400                            UserHandle.myUserId());
4401                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4402                        boolean defaultBrowserFound = false;
4403                        final int browserCount = matchAllList.size();
4404                        for (int n=0; n<browserCount; n++) {
4405                            ResolveInfo browser = matchAllList.get(n);
4406                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4407                                result.add(browser);
4408                                defaultBrowserFound = true;
4409                                break;
4410                            }
4411                        }
4412                        if (!defaultBrowserFound) {
4413                            result.addAll(matchAllList);
4414                        }
4415                    } else {
4416                        result.addAll(matchAllList);
4417                    }
4418                }
4419
4420                // If there is nothing selected, add all candidates and remove the ones that the User
4421                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4422                if (result.size() == 0) {
4423                    result.addAll(candidates);
4424                    result.removeAll(neverList);
4425                }
4426            }
4427        }
4428        if (DEBUG_PREFERRED) {
4429            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4430                    result.size());
4431        }
4432        return result;
4433    }
4434
4435    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4436        int status = ps.getDomainVerificationStatusForUser(userId);
4437        // if none available, get the master status
4438        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4439            if (ps.getIntentFilterVerificationInfo() != null) {
4440                status = ps.getIntentFilterVerificationInfo().getStatus();
4441            }
4442        }
4443        return status;
4444    }
4445
4446    private ResolveInfo querySkipCurrentProfileIntents(
4447            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4448            int flags, int sourceUserId) {
4449        if (matchingFilters != null) {
4450            int size = matchingFilters.size();
4451            for (int i = 0; i < size; i ++) {
4452                CrossProfileIntentFilter filter = matchingFilters.get(i);
4453                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4454                    // Checking if there are activities in the target user that can handle the
4455                    // intent.
4456                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4457                            flags, sourceUserId);
4458                    if (resolveInfo != null) {
4459                        return resolveInfo;
4460                    }
4461                }
4462            }
4463        }
4464        return null;
4465    }
4466
4467    // Return matching ResolveInfo if any for skip current profile intent filters.
4468    private ResolveInfo queryCrossProfileIntents(
4469            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4470            int flags, int sourceUserId) {
4471        if (matchingFilters != null) {
4472            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4473            // match the same intent. For performance reasons, it is better not to
4474            // run queryIntent twice for the same userId
4475            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4476            int size = matchingFilters.size();
4477            for (int i = 0; i < size; i++) {
4478                CrossProfileIntentFilter filter = matchingFilters.get(i);
4479                int targetUserId = filter.getTargetUserId();
4480                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4481                        && !alreadyTriedUserIds.get(targetUserId)) {
4482                    // Checking if there are activities in the target user that can handle the
4483                    // intent.
4484                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4485                            flags, sourceUserId);
4486                    if (resolveInfo != null) return resolveInfo;
4487                    alreadyTriedUserIds.put(targetUserId, true);
4488                }
4489            }
4490        }
4491        return null;
4492    }
4493
4494    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4495            String resolvedType, int flags, int sourceUserId) {
4496        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4497                resolvedType, flags, filter.getTargetUserId());
4498        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4499            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4500        }
4501        return null;
4502    }
4503
4504    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4505            int sourceUserId, int targetUserId) {
4506        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4507        String className;
4508        if (targetUserId == UserHandle.USER_OWNER) {
4509            className = FORWARD_INTENT_TO_USER_OWNER;
4510        } else {
4511            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4512        }
4513        ComponentName forwardingActivityComponentName = new ComponentName(
4514                mAndroidApplication.packageName, className);
4515        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4516                sourceUserId);
4517        if (targetUserId == UserHandle.USER_OWNER) {
4518            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4519            forwardingResolveInfo.noResourceId = true;
4520        }
4521        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4522        forwardingResolveInfo.priority = 0;
4523        forwardingResolveInfo.preferredOrder = 0;
4524        forwardingResolveInfo.match = 0;
4525        forwardingResolveInfo.isDefault = true;
4526        forwardingResolveInfo.filter = filter;
4527        forwardingResolveInfo.targetUserId = targetUserId;
4528        return forwardingResolveInfo;
4529    }
4530
4531    @Override
4532    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4533            Intent[] specifics, String[] specificTypes, Intent intent,
4534            String resolvedType, int flags, int userId) {
4535        if (!sUserManager.exists(userId)) return Collections.emptyList();
4536        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4537                false, "query intent activity options");
4538        final String resultsAction = intent.getAction();
4539
4540        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4541                | PackageManager.GET_RESOLVED_FILTER, userId);
4542
4543        if (DEBUG_INTENT_MATCHING) {
4544            Log.v(TAG, "Query " + intent + ": " + results);
4545        }
4546
4547        int specificsPos = 0;
4548        int N;
4549
4550        // todo: note that the algorithm used here is O(N^2).  This
4551        // isn't a problem in our current environment, but if we start running
4552        // into situations where we have more than 5 or 10 matches then this
4553        // should probably be changed to something smarter...
4554
4555        // First we go through and resolve each of the specific items
4556        // that were supplied, taking care of removing any corresponding
4557        // duplicate items in the generic resolve list.
4558        if (specifics != null) {
4559            for (int i=0; i<specifics.length; i++) {
4560                final Intent sintent = specifics[i];
4561                if (sintent == null) {
4562                    continue;
4563                }
4564
4565                if (DEBUG_INTENT_MATCHING) {
4566                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4567                }
4568
4569                String action = sintent.getAction();
4570                if (resultsAction != null && resultsAction.equals(action)) {
4571                    // If this action was explicitly requested, then don't
4572                    // remove things that have it.
4573                    action = null;
4574                }
4575
4576                ResolveInfo ri = null;
4577                ActivityInfo ai = null;
4578
4579                ComponentName comp = sintent.getComponent();
4580                if (comp == null) {
4581                    ri = resolveIntent(
4582                        sintent,
4583                        specificTypes != null ? specificTypes[i] : null,
4584                            flags, userId);
4585                    if (ri == null) {
4586                        continue;
4587                    }
4588                    if (ri == mResolveInfo) {
4589                        // ACK!  Must do something better with this.
4590                    }
4591                    ai = ri.activityInfo;
4592                    comp = new ComponentName(ai.applicationInfo.packageName,
4593                            ai.name);
4594                } else {
4595                    ai = getActivityInfo(comp, flags, userId);
4596                    if (ai == null) {
4597                        continue;
4598                    }
4599                }
4600
4601                // Look for any generic query activities that are duplicates
4602                // of this specific one, and remove them from the results.
4603                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4604                N = results.size();
4605                int j;
4606                for (j=specificsPos; j<N; j++) {
4607                    ResolveInfo sri = results.get(j);
4608                    if ((sri.activityInfo.name.equals(comp.getClassName())
4609                            && sri.activityInfo.applicationInfo.packageName.equals(
4610                                    comp.getPackageName()))
4611                        || (action != null && sri.filter.matchAction(action))) {
4612                        results.remove(j);
4613                        if (DEBUG_INTENT_MATCHING) Log.v(
4614                            TAG, "Removing duplicate item from " + j
4615                            + " due to specific " + specificsPos);
4616                        if (ri == null) {
4617                            ri = sri;
4618                        }
4619                        j--;
4620                        N--;
4621                    }
4622                }
4623
4624                // Add this specific item to its proper place.
4625                if (ri == null) {
4626                    ri = new ResolveInfo();
4627                    ri.activityInfo = ai;
4628                }
4629                results.add(specificsPos, ri);
4630                ri.specificIndex = i;
4631                specificsPos++;
4632            }
4633        }
4634
4635        // Now we go through the remaining generic results and remove any
4636        // duplicate actions that are found here.
4637        N = results.size();
4638        for (int i=specificsPos; i<N-1; i++) {
4639            final ResolveInfo rii = results.get(i);
4640            if (rii.filter == null) {
4641                continue;
4642            }
4643
4644            // Iterate over all of the actions of this result's intent
4645            // filter...  typically this should be just one.
4646            final Iterator<String> it = rii.filter.actionsIterator();
4647            if (it == null) {
4648                continue;
4649            }
4650            while (it.hasNext()) {
4651                final String action = it.next();
4652                if (resultsAction != null && resultsAction.equals(action)) {
4653                    // If this action was explicitly requested, then don't
4654                    // remove things that have it.
4655                    continue;
4656                }
4657                for (int j=i+1; j<N; j++) {
4658                    final ResolveInfo rij = results.get(j);
4659                    if (rij.filter != null && rij.filter.hasAction(action)) {
4660                        results.remove(j);
4661                        if (DEBUG_INTENT_MATCHING) Log.v(
4662                            TAG, "Removing duplicate item from " + j
4663                            + " due to action " + action + " at " + i);
4664                        j--;
4665                        N--;
4666                    }
4667                }
4668            }
4669
4670            // If the caller didn't request filter information, drop it now
4671            // so we don't have to marshall/unmarshall it.
4672            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4673                rii.filter = null;
4674            }
4675        }
4676
4677        // Filter out the caller activity if so requested.
4678        if (caller != null) {
4679            N = results.size();
4680            for (int i=0; i<N; i++) {
4681                ActivityInfo ainfo = results.get(i).activityInfo;
4682                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4683                        && caller.getClassName().equals(ainfo.name)) {
4684                    results.remove(i);
4685                    break;
4686                }
4687            }
4688        }
4689
4690        // If the caller didn't request filter information,
4691        // drop them now so we don't have to
4692        // marshall/unmarshall it.
4693        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4694            N = results.size();
4695            for (int i=0; i<N; i++) {
4696                results.get(i).filter = null;
4697            }
4698        }
4699
4700        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4701        return results;
4702    }
4703
4704    @Override
4705    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4706            int userId) {
4707        if (!sUserManager.exists(userId)) return Collections.emptyList();
4708        ComponentName comp = intent.getComponent();
4709        if (comp == null) {
4710            if (intent.getSelector() != null) {
4711                intent = intent.getSelector();
4712                comp = intent.getComponent();
4713            }
4714        }
4715        if (comp != null) {
4716            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4717            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4718            if (ai != null) {
4719                ResolveInfo ri = new ResolveInfo();
4720                ri.activityInfo = ai;
4721                list.add(ri);
4722            }
4723            return list;
4724        }
4725
4726        // reader
4727        synchronized (mPackages) {
4728            String pkgName = intent.getPackage();
4729            if (pkgName == null) {
4730                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4731            }
4732            final PackageParser.Package pkg = mPackages.get(pkgName);
4733            if (pkg != null) {
4734                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4735                        userId);
4736            }
4737            return null;
4738        }
4739    }
4740
4741    @Override
4742    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4743        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4744        if (!sUserManager.exists(userId)) return null;
4745        if (query != null) {
4746            if (query.size() >= 1) {
4747                // If there is more than one service with the same priority,
4748                // just arbitrarily pick the first one.
4749                return query.get(0);
4750            }
4751        }
4752        return null;
4753    }
4754
4755    @Override
4756    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4757            int userId) {
4758        if (!sUserManager.exists(userId)) return Collections.emptyList();
4759        ComponentName comp = intent.getComponent();
4760        if (comp == null) {
4761            if (intent.getSelector() != null) {
4762                intent = intent.getSelector();
4763                comp = intent.getComponent();
4764            }
4765        }
4766        if (comp != null) {
4767            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4768            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4769            if (si != null) {
4770                final ResolveInfo ri = new ResolveInfo();
4771                ri.serviceInfo = si;
4772                list.add(ri);
4773            }
4774            return list;
4775        }
4776
4777        // reader
4778        synchronized (mPackages) {
4779            String pkgName = intent.getPackage();
4780            if (pkgName == null) {
4781                return mServices.queryIntent(intent, resolvedType, flags, userId);
4782            }
4783            final PackageParser.Package pkg = mPackages.get(pkgName);
4784            if (pkg != null) {
4785                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4786                        userId);
4787            }
4788            return null;
4789        }
4790    }
4791
4792    @Override
4793    public List<ResolveInfo> queryIntentContentProviders(
4794            Intent intent, String resolvedType, int flags, int userId) {
4795        if (!sUserManager.exists(userId)) return Collections.emptyList();
4796        ComponentName comp = intent.getComponent();
4797        if (comp == null) {
4798            if (intent.getSelector() != null) {
4799                intent = intent.getSelector();
4800                comp = intent.getComponent();
4801            }
4802        }
4803        if (comp != null) {
4804            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4805            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4806            if (pi != null) {
4807                final ResolveInfo ri = new ResolveInfo();
4808                ri.providerInfo = pi;
4809                list.add(ri);
4810            }
4811            return list;
4812        }
4813
4814        // reader
4815        synchronized (mPackages) {
4816            String pkgName = intent.getPackage();
4817            if (pkgName == null) {
4818                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4819            }
4820            final PackageParser.Package pkg = mPackages.get(pkgName);
4821            if (pkg != null) {
4822                return mProviders.queryIntentForPackage(
4823                        intent, resolvedType, flags, pkg.providers, userId);
4824            }
4825            return null;
4826        }
4827    }
4828
4829    @Override
4830    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4831        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4832
4833        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4834
4835        // writer
4836        synchronized (mPackages) {
4837            ArrayList<PackageInfo> list;
4838            if (listUninstalled) {
4839                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4840                for (PackageSetting ps : mSettings.mPackages.values()) {
4841                    PackageInfo pi;
4842                    if (ps.pkg != null) {
4843                        pi = generatePackageInfo(ps.pkg, flags, userId);
4844                    } else {
4845                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4846                    }
4847                    if (pi != null) {
4848                        list.add(pi);
4849                    }
4850                }
4851            } else {
4852                list = new ArrayList<PackageInfo>(mPackages.size());
4853                for (PackageParser.Package p : mPackages.values()) {
4854                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4855                    if (pi != null) {
4856                        list.add(pi);
4857                    }
4858                }
4859            }
4860
4861            return new ParceledListSlice<PackageInfo>(list);
4862        }
4863    }
4864
4865    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4866            String[] permissions, boolean[] tmp, int flags, int userId) {
4867        int numMatch = 0;
4868        final PermissionsState permissionsState = ps.getPermissionsState();
4869        for (int i=0; i<permissions.length; i++) {
4870            final String permission = permissions[i];
4871            if (permissionsState.hasPermission(permission, userId)) {
4872                tmp[i] = true;
4873                numMatch++;
4874            } else {
4875                tmp[i] = false;
4876            }
4877        }
4878        if (numMatch == 0) {
4879            return;
4880        }
4881        PackageInfo pi;
4882        if (ps.pkg != null) {
4883            pi = generatePackageInfo(ps.pkg, flags, userId);
4884        } else {
4885            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4886        }
4887        // The above might return null in cases of uninstalled apps or install-state
4888        // skew across users/profiles.
4889        if (pi != null) {
4890            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4891                if (numMatch == permissions.length) {
4892                    pi.requestedPermissions = permissions;
4893                } else {
4894                    pi.requestedPermissions = new String[numMatch];
4895                    numMatch = 0;
4896                    for (int i=0; i<permissions.length; i++) {
4897                        if (tmp[i]) {
4898                            pi.requestedPermissions[numMatch] = permissions[i];
4899                            numMatch++;
4900                        }
4901                    }
4902                }
4903            }
4904            list.add(pi);
4905        }
4906    }
4907
4908    @Override
4909    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4910            String[] permissions, int flags, int userId) {
4911        if (!sUserManager.exists(userId)) return null;
4912        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4913
4914        // writer
4915        synchronized (mPackages) {
4916            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4917            boolean[] tmpBools = new boolean[permissions.length];
4918            if (listUninstalled) {
4919                for (PackageSetting ps : mSettings.mPackages.values()) {
4920                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4921                }
4922            } else {
4923                for (PackageParser.Package pkg : mPackages.values()) {
4924                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4925                    if (ps != null) {
4926                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4927                                userId);
4928                    }
4929                }
4930            }
4931
4932            return new ParceledListSlice<PackageInfo>(list);
4933        }
4934    }
4935
4936    @Override
4937    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4938        if (!sUserManager.exists(userId)) return null;
4939        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4940
4941        // writer
4942        synchronized (mPackages) {
4943            ArrayList<ApplicationInfo> list;
4944            if (listUninstalled) {
4945                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4946                for (PackageSetting ps : mSettings.mPackages.values()) {
4947                    ApplicationInfo ai;
4948                    if (ps.pkg != null) {
4949                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4950                                ps.readUserState(userId), userId);
4951                    } else {
4952                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4953                    }
4954                    if (ai != null) {
4955                        list.add(ai);
4956                    }
4957                }
4958            } else {
4959                list = new ArrayList<ApplicationInfo>(mPackages.size());
4960                for (PackageParser.Package p : mPackages.values()) {
4961                    if (p.mExtras != null) {
4962                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4963                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4964                        if (ai != null) {
4965                            list.add(ai);
4966                        }
4967                    }
4968                }
4969            }
4970
4971            return new ParceledListSlice<ApplicationInfo>(list);
4972        }
4973    }
4974
4975    public List<ApplicationInfo> getPersistentApplications(int flags) {
4976        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4977
4978        // reader
4979        synchronized (mPackages) {
4980            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4981            final int userId = UserHandle.getCallingUserId();
4982            while (i.hasNext()) {
4983                final PackageParser.Package p = i.next();
4984                if (p.applicationInfo != null
4985                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4986                        && (!mSafeMode || isSystemApp(p))) {
4987                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4988                    if (ps != null) {
4989                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4990                                ps.readUserState(userId), userId);
4991                        if (ai != null) {
4992                            finalList.add(ai);
4993                        }
4994                    }
4995                }
4996            }
4997        }
4998
4999        return finalList;
5000    }
5001
5002    @Override
5003    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5004        if (!sUserManager.exists(userId)) return null;
5005        // reader
5006        synchronized (mPackages) {
5007            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5008            PackageSetting ps = provider != null
5009                    ? mSettings.mPackages.get(provider.owner.packageName)
5010                    : null;
5011            return ps != null
5012                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5013                    && (!mSafeMode || (provider.info.applicationInfo.flags
5014                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5015                    ? PackageParser.generateProviderInfo(provider, flags,
5016                            ps.readUserState(userId), userId)
5017                    : null;
5018        }
5019    }
5020
5021    /**
5022     * @deprecated
5023     */
5024    @Deprecated
5025    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5026        // reader
5027        synchronized (mPackages) {
5028            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5029                    .entrySet().iterator();
5030            final int userId = UserHandle.getCallingUserId();
5031            while (i.hasNext()) {
5032                Map.Entry<String, PackageParser.Provider> entry = i.next();
5033                PackageParser.Provider p = entry.getValue();
5034                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5035
5036                if (ps != null && p.syncable
5037                        && (!mSafeMode || (p.info.applicationInfo.flags
5038                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5039                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5040                            ps.readUserState(userId), userId);
5041                    if (info != null) {
5042                        outNames.add(entry.getKey());
5043                        outInfo.add(info);
5044                    }
5045                }
5046            }
5047        }
5048    }
5049
5050    @Override
5051    public List<ProviderInfo> queryContentProviders(String processName,
5052            int uid, int flags) {
5053        ArrayList<ProviderInfo> finalList = null;
5054        // reader
5055        synchronized (mPackages) {
5056            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5057            final int userId = processName != null ?
5058                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5059            while (i.hasNext()) {
5060                final PackageParser.Provider p = i.next();
5061                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5062                if (ps != null && p.info.authority != null
5063                        && (processName == null
5064                                || (p.info.processName.equals(processName)
5065                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5066                        && mSettings.isEnabledLPr(p.info, flags, userId)
5067                        && (!mSafeMode
5068                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5069                    if (finalList == null) {
5070                        finalList = new ArrayList<ProviderInfo>(3);
5071                    }
5072                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5073                            ps.readUserState(userId), userId);
5074                    if (info != null) {
5075                        finalList.add(info);
5076                    }
5077                }
5078            }
5079        }
5080
5081        if (finalList != null) {
5082            Collections.sort(finalList, mProviderInitOrderSorter);
5083        }
5084
5085        return finalList;
5086    }
5087
5088    @Override
5089    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5090            int flags) {
5091        // reader
5092        synchronized (mPackages) {
5093            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5094            return PackageParser.generateInstrumentationInfo(i, flags);
5095        }
5096    }
5097
5098    @Override
5099    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5100            int flags) {
5101        ArrayList<InstrumentationInfo> finalList =
5102            new ArrayList<InstrumentationInfo>();
5103
5104        // reader
5105        synchronized (mPackages) {
5106            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5107            while (i.hasNext()) {
5108                final PackageParser.Instrumentation p = i.next();
5109                if (targetPackage == null
5110                        || targetPackage.equals(p.info.targetPackage)) {
5111                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5112                            flags);
5113                    if (ii != null) {
5114                        finalList.add(ii);
5115                    }
5116                }
5117            }
5118        }
5119
5120        return finalList;
5121    }
5122
5123    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5124        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5125        if (overlays == null) {
5126            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5127            return;
5128        }
5129        for (PackageParser.Package opkg : overlays.values()) {
5130            // Not much to do if idmap fails: we already logged the error
5131            // and we certainly don't want to abort installation of pkg simply
5132            // because an overlay didn't fit properly. For these reasons,
5133            // ignore the return value of createIdmapForPackagePairLI.
5134            createIdmapForPackagePairLI(pkg, opkg);
5135        }
5136    }
5137
5138    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5139            PackageParser.Package opkg) {
5140        if (!opkg.mTrustedOverlay) {
5141            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5142                    opkg.baseCodePath + ": overlay not trusted");
5143            return false;
5144        }
5145        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5146        if (overlaySet == null) {
5147            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5148                    opkg.baseCodePath + " but target package has no known overlays");
5149            return false;
5150        }
5151        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5152        // TODO: generate idmap for split APKs
5153        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5154            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5155                    + opkg.baseCodePath);
5156            return false;
5157        }
5158        PackageParser.Package[] overlayArray =
5159            overlaySet.values().toArray(new PackageParser.Package[0]);
5160        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5161            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5162                return p1.mOverlayPriority - p2.mOverlayPriority;
5163            }
5164        };
5165        Arrays.sort(overlayArray, cmp);
5166
5167        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5168        int i = 0;
5169        for (PackageParser.Package p : overlayArray) {
5170            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5171        }
5172        return true;
5173    }
5174
5175    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5176        final File[] files = dir.listFiles();
5177        if (ArrayUtils.isEmpty(files)) {
5178            Log.d(TAG, "No files in app dir " + dir);
5179            return;
5180        }
5181
5182        if (DEBUG_PACKAGE_SCANNING) {
5183            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5184                    + " flags=0x" + Integer.toHexString(parseFlags));
5185        }
5186
5187        for (File file : files) {
5188            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5189                    && !PackageInstallerService.isStageName(file.getName());
5190            if (!isPackage) {
5191                // Ignore entries which are not packages
5192                continue;
5193            }
5194            try {
5195                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5196                        scanFlags, currentTime, null);
5197            } catch (PackageManagerException e) {
5198                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5199
5200                // Delete invalid userdata apps
5201                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5202                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5203                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5204                    if (file.isDirectory()) {
5205                        mInstaller.rmPackageDir(file.getAbsolutePath());
5206                    } else {
5207                        file.delete();
5208                    }
5209                }
5210            }
5211        }
5212    }
5213
5214    private static File getSettingsProblemFile() {
5215        File dataDir = Environment.getDataDirectory();
5216        File systemDir = new File(dataDir, "system");
5217        File fname = new File(systemDir, "uiderrors.txt");
5218        return fname;
5219    }
5220
5221    static void reportSettingsProblem(int priority, String msg) {
5222        logCriticalInfo(priority, msg);
5223    }
5224
5225    static void logCriticalInfo(int priority, String msg) {
5226        Slog.println(priority, TAG, msg);
5227        EventLogTags.writePmCriticalInfo(msg);
5228        try {
5229            File fname = getSettingsProblemFile();
5230            FileOutputStream out = new FileOutputStream(fname, true);
5231            PrintWriter pw = new FastPrintWriter(out);
5232            SimpleDateFormat formatter = new SimpleDateFormat();
5233            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5234            pw.println(dateString + ": " + msg);
5235            pw.close();
5236            FileUtils.setPermissions(
5237                    fname.toString(),
5238                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5239                    -1, -1);
5240        } catch (java.io.IOException e) {
5241        }
5242    }
5243
5244    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5245            PackageParser.Package pkg, File srcFile, int parseFlags)
5246            throws PackageManagerException {
5247        if (ps != null
5248                && ps.codePath.equals(srcFile)
5249                && ps.timeStamp == srcFile.lastModified()
5250                && !isCompatSignatureUpdateNeeded(pkg)
5251                && !isRecoverSignatureUpdateNeeded(pkg)) {
5252            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5253            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5254            ArraySet<PublicKey> signingKs;
5255            synchronized (mPackages) {
5256                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5257            }
5258            if (ps.signatures.mSignatures != null
5259                    && ps.signatures.mSignatures.length != 0
5260                    && signingKs != null) {
5261                // Optimization: reuse the existing cached certificates
5262                // if the package appears to be unchanged.
5263                pkg.mSignatures = ps.signatures.mSignatures;
5264                pkg.mSigningKeys = signingKs;
5265                return;
5266            }
5267
5268            Slog.w(TAG, "PackageSetting for " + ps.name
5269                    + " is missing signatures.  Collecting certs again to recover them.");
5270        } else {
5271            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5272        }
5273
5274        try {
5275            pp.collectCertificates(pkg, parseFlags);
5276            pp.collectManifestDigest(pkg);
5277        } catch (PackageParserException e) {
5278            throw PackageManagerException.from(e);
5279        }
5280    }
5281
5282    /*
5283     *  Scan a package and return the newly parsed package.
5284     *  Returns null in case of errors and the error code is stored in mLastScanError
5285     */
5286    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5287            long currentTime, UserHandle user) throws PackageManagerException {
5288        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5289        parseFlags |= mDefParseFlags;
5290        PackageParser pp = new PackageParser();
5291        pp.setSeparateProcesses(mSeparateProcesses);
5292        pp.setOnlyCoreApps(mOnlyCore);
5293        pp.setDisplayMetrics(mMetrics);
5294
5295        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5296            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5297        }
5298
5299        final PackageParser.Package pkg;
5300        try {
5301            pkg = pp.parsePackage(scanFile, parseFlags);
5302        } catch (PackageParserException e) {
5303            throw PackageManagerException.from(e);
5304        }
5305
5306        PackageSetting ps = null;
5307        PackageSetting updatedPkg;
5308        // reader
5309        synchronized (mPackages) {
5310            // Look to see if we already know about this package.
5311            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5312            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5313                // This package has been renamed to its original name.  Let's
5314                // use that.
5315                ps = mSettings.peekPackageLPr(oldName);
5316            }
5317            // If there was no original package, see one for the real package name.
5318            if (ps == null) {
5319                ps = mSettings.peekPackageLPr(pkg.packageName);
5320            }
5321            // Check to see if this package could be hiding/updating a system
5322            // package.  Must look for it either under the original or real
5323            // package name depending on our state.
5324            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5325            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5326        }
5327        boolean updatedPkgBetter = false;
5328        // First check if this is a system package that may involve an update
5329        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5330            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5331            // it needs to drop FLAG_PRIVILEGED.
5332            if (locationIsPrivileged(scanFile)) {
5333                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5334            } else {
5335                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5336            }
5337
5338            if (ps != null && !ps.codePath.equals(scanFile)) {
5339                // The path has changed from what was last scanned...  check the
5340                // version of the new path against what we have stored to determine
5341                // what to do.
5342                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5343                if (pkg.mVersionCode <= ps.versionCode) {
5344                    // The system package has been updated and the code path does not match
5345                    // Ignore entry. Skip it.
5346                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5347                            + " ignored: updated version " + ps.versionCode
5348                            + " better than this " + pkg.mVersionCode);
5349                    if (!updatedPkg.codePath.equals(scanFile)) {
5350                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5351                                + ps.name + " changing from " + updatedPkg.codePathString
5352                                + " to " + scanFile);
5353                        updatedPkg.codePath = scanFile;
5354                        updatedPkg.codePathString = scanFile.toString();
5355                        updatedPkg.resourcePath = scanFile;
5356                        updatedPkg.resourcePathString = scanFile.toString();
5357                    }
5358                    updatedPkg.pkg = pkg;
5359                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5360                } else {
5361                    // The current app on the system partition is better than
5362                    // what we have updated to on the data partition; switch
5363                    // back to the system partition version.
5364                    // At this point, its safely assumed that package installation for
5365                    // apps in system partition will go through. If not there won't be a working
5366                    // version of the app
5367                    // writer
5368                    synchronized (mPackages) {
5369                        // Just remove the loaded entries from package lists.
5370                        mPackages.remove(ps.name);
5371                    }
5372
5373                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5374                            + " reverting from " + ps.codePathString
5375                            + ": new version " + pkg.mVersionCode
5376                            + " better than installed " + ps.versionCode);
5377
5378                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5379                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5380                    synchronized (mInstallLock) {
5381                        args.cleanUpResourcesLI();
5382                    }
5383                    synchronized (mPackages) {
5384                        mSettings.enableSystemPackageLPw(ps.name);
5385                    }
5386                    updatedPkgBetter = true;
5387                }
5388            }
5389        }
5390
5391        if (updatedPkg != null) {
5392            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5393            // initially
5394            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5395
5396            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5397            // flag set initially
5398            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5399                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5400            }
5401        }
5402
5403        // Verify certificates against what was last scanned
5404        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5405
5406        /*
5407         * A new system app appeared, but we already had a non-system one of the
5408         * same name installed earlier.
5409         */
5410        boolean shouldHideSystemApp = false;
5411        if (updatedPkg == null && ps != null
5412                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5413            /*
5414             * Check to make sure the signatures match first. If they don't,
5415             * wipe the installed application and its data.
5416             */
5417            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5418                    != PackageManager.SIGNATURE_MATCH) {
5419                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5420                        + " signatures don't match existing userdata copy; removing");
5421                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5422                ps = null;
5423            } else {
5424                /*
5425                 * If the newly-added system app is an older version than the
5426                 * already installed version, hide it. It will be scanned later
5427                 * and re-added like an update.
5428                 */
5429                if (pkg.mVersionCode <= ps.versionCode) {
5430                    shouldHideSystemApp = true;
5431                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5432                            + " but new version " + pkg.mVersionCode + " better than installed "
5433                            + ps.versionCode + "; hiding system");
5434                } else {
5435                    /*
5436                     * The newly found system app is a newer version that the
5437                     * one previously installed. Simply remove the
5438                     * already-installed application and replace it with our own
5439                     * while keeping the application data.
5440                     */
5441                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5442                            + " reverting from " + ps.codePathString + ": new version "
5443                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5444                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5445                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5446                    synchronized (mInstallLock) {
5447                        args.cleanUpResourcesLI();
5448                    }
5449                }
5450            }
5451        }
5452
5453        // The apk is forward locked (not public) if its code and resources
5454        // are kept in different files. (except for app in either system or
5455        // vendor path).
5456        // TODO grab this value from PackageSettings
5457        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5458            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5459                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5460            }
5461        }
5462
5463        // TODO: extend to support forward-locked splits
5464        String resourcePath = null;
5465        String baseResourcePath = null;
5466        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5467            if (ps != null && ps.resourcePathString != null) {
5468                resourcePath = ps.resourcePathString;
5469                baseResourcePath = ps.resourcePathString;
5470            } else {
5471                // Should not happen at all. Just log an error.
5472                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5473            }
5474        } else {
5475            resourcePath = pkg.codePath;
5476            baseResourcePath = pkg.baseCodePath;
5477        }
5478
5479        // Set application objects path explicitly.
5480        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5481        pkg.applicationInfo.setCodePath(pkg.codePath);
5482        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5483        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5484        pkg.applicationInfo.setResourcePath(resourcePath);
5485        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5486        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5487
5488        // Note that we invoke the following method only if we are about to unpack an application
5489        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5490                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5491
5492        /*
5493         * If the system app should be overridden by a previously installed
5494         * data, hide the system app now and let the /data/app scan pick it up
5495         * again.
5496         */
5497        if (shouldHideSystemApp) {
5498            synchronized (mPackages) {
5499                /*
5500                 * We have to grant systems permissions before we hide, because
5501                 * grantPermissions will assume the package update is trying to
5502                 * expand its permissions.
5503                 */
5504                grantPermissionsLPw(pkg, true, pkg.packageName);
5505                mSettings.disableSystemPackageLPw(pkg.packageName);
5506            }
5507        }
5508
5509        return scannedPkg;
5510    }
5511
5512    private static String fixProcessName(String defProcessName,
5513            String processName, int uid) {
5514        if (processName == null) {
5515            return defProcessName;
5516        }
5517        return processName;
5518    }
5519
5520    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5521            throws PackageManagerException {
5522        if (pkgSetting.signatures.mSignatures != null) {
5523            // Already existing package. Make sure signatures match
5524            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5525                    == PackageManager.SIGNATURE_MATCH;
5526            if (!match) {
5527                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5528                        == PackageManager.SIGNATURE_MATCH;
5529            }
5530            if (!match) {
5531                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5532                        == PackageManager.SIGNATURE_MATCH;
5533            }
5534            if (!match) {
5535                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5536                        + pkg.packageName + " signatures do not match the "
5537                        + "previously installed version; ignoring!");
5538            }
5539        }
5540
5541        // Check for shared user signatures
5542        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5543            // Already existing package. Make sure signatures match
5544            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5545                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5546            if (!match) {
5547                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5548                        == PackageManager.SIGNATURE_MATCH;
5549            }
5550            if (!match) {
5551                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5552                        == PackageManager.SIGNATURE_MATCH;
5553            }
5554            if (!match) {
5555                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5556                        "Package " + pkg.packageName
5557                        + " has no signatures that match those in shared user "
5558                        + pkgSetting.sharedUser.name + "; ignoring!");
5559            }
5560        }
5561    }
5562
5563    /**
5564     * Enforces that only the system UID or root's UID can call a method exposed
5565     * via Binder.
5566     *
5567     * @param message used as message if SecurityException is thrown
5568     * @throws SecurityException if the caller is not system or root
5569     */
5570    private static final void enforceSystemOrRoot(String message) {
5571        final int uid = Binder.getCallingUid();
5572        if (uid != Process.SYSTEM_UID && uid != 0) {
5573            throw new SecurityException(message);
5574        }
5575    }
5576
5577    @Override
5578    public void performBootDexOpt() {
5579        enforceSystemOrRoot("Only the system can request dexopt be performed");
5580
5581        // Before everything else, see whether we need to fstrim.
5582        try {
5583            IMountService ms = PackageHelper.getMountService();
5584            if (ms != null) {
5585                final boolean isUpgrade = isUpgrade();
5586                boolean doTrim = isUpgrade;
5587                if (doTrim) {
5588                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5589                } else {
5590                    final long interval = android.provider.Settings.Global.getLong(
5591                            mContext.getContentResolver(),
5592                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5593                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5594                    if (interval > 0) {
5595                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5596                        if (timeSinceLast > interval) {
5597                            doTrim = true;
5598                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5599                                    + "; running immediately");
5600                        }
5601                    }
5602                }
5603                if (doTrim) {
5604                    if (!isFirstBoot()) {
5605                        try {
5606                            ActivityManagerNative.getDefault().showBootMessage(
5607                                    mContext.getResources().getString(
5608                                            R.string.android_upgrading_fstrim), true);
5609                        } catch (RemoteException e) {
5610                        }
5611                    }
5612                    ms.runMaintenance();
5613                }
5614            } else {
5615                Slog.e(TAG, "Mount service unavailable!");
5616            }
5617        } catch (RemoteException e) {
5618            // Can't happen; MountService is local
5619        }
5620
5621        final ArraySet<PackageParser.Package> pkgs;
5622        synchronized (mPackages) {
5623            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5624        }
5625
5626        if (pkgs != null) {
5627            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5628            // in case the device runs out of space.
5629            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5630            // Give priority to core apps.
5631            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5632                PackageParser.Package pkg = it.next();
5633                if (pkg.coreApp) {
5634                    if (DEBUG_DEXOPT) {
5635                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5636                    }
5637                    sortedPkgs.add(pkg);
5638                    it.remove();
5639                }
5640            }
5641            // Give priority to system apps that listen for pre boot complete.
5642            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5643            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5644            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5645                PackageParser.Package pkg = it.next();
5646                if (pkgNames.contains(pkg.packageName)) {
5647                    if (DEBUG_DEXOPT) {
5648                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5649                    }
5650                    sortedPkgs.add(pkg);
5651                    it.remove();
5652                }
5653            }
5654            // Give priority to system apps.
5655            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5656                PackageParser.Package pkg = it.next();
5657                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5658                    if (DEBUG_DEXOPT) {
5659                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5660                    }
5661                    sortedPkgs.add(pkg);
5662                    it.remove();
5663                }
5664            }
5665            // Give priority to updated system apps.
5666            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5667                PackageParser.Package pkg = it.next();
5668                if (pkg.isUpdatedSystemApp()) {
5669                    if (DEBUG_DEXOPT) {
5670                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5671                    }
5672                    sortedPkgs.add(pkg);
5673                    it.remove();
5674                }
5675            }
5676            // Give priority to apps that listen for boot complete.
5677            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5678            pkgNames = getPackageNamesForIntent(intent);
5679            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5680                PackageParser.Package pkg = it.next();
5681                if (pkgNames.contains(pkg.packageName)) {
5682                    if (DEBUG_DEXOPT) {
5683                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5684                    }
5685                    sortedPkgs.add(pkg);
5686                    it.remove();
5687                }
5688            }
5689            // Filter out packages that aren't recently used.
5690            filterRecentlyUsedApps(pkgs);
5691            // Add all remaining apps.
5692            for (PackageParser.Package pkg : pkgs) {
5693                if (DEBUG_DEXOPT) {
5694                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5695                }
5696                sortedPkgs.add(pkg);
5697            }
5698
5699            // If we want to be lazy, filter everything that wasn't recently used.
5700            if (mLazyDexOpt) {
5701                filterRecentlyUsedApps(sortedPkgs);
5702            }
5703
5704            int i = 0;
5705            int total = sortedPkgs.size();
5706            File dataDir = Environment.getDataDirectory();
5707            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5708            if (lowThreshold == 0) {
5709                throw new IllegalStateException("Invalid low memory threshold");
5710            }
5711            for (PackageParser.Package pkg : sortedPkgs) {
5712                long usableSpace = dataDir.getUsableSpace();
5713                if (usableSpace < lowThreshold) {
5714                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5715                    break;
5716                }
5717                performBootDexOpt(pkg, ++i, total);
5718            }
5719        }
5720    }
5721
5722    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5723        // Filter out packages that aren't recently used.
5724        //
5725        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5726        // should do a full dexopt.
5727        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5728            int total = pkgs.size();
5729            int skipped = 0;
5730            long now = System.currentTimeMillis();
5731            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5732                PackageParser.Package pkg = i.next();
5733                long then = pkg.mLastPackageUsageTimeInMills;
5734                if (then + mDexOptLRUThresholdInMills < now) {
5735                    if (DEBUG_DEXOPT) {
5736                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5737                              ((then == 0) ? "never" : new Date(then)));
5738                    }
5739                    i.remove();
5740                    skipped++;
5741                }
5742            }
5743            if (DEBUG_DEXOPT) {
5744                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5745            }
5746        }
5747    }
5748
5749    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5750        List<ResolveInfo> ris = null;
5751        try {
5752            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5753                    intent, null, 0, UserHandle.USER_OWNER);
5754        } catch (RemoteException e) {
5755        }
5756        ArraySet<String> pkgNames = new ArraySet<String>();
5757        if (ris != null) {
5758            for (ResolveInfo ri : ris) {
5759                pkgNames.add(ri.activityInfo.packageName);
5760            }
5761        }
5762        return pkgNames;
5763    }
5764
5765    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5766        if (DEBUG_DEXOPT) {
5767            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5768        }
5769        if (!isFirstBoot()) {
5770            try {
5771                ActivityManagerNative.getDefault().showBootMessage(
5772                        mContext.getResources().getString(R.string.android_upgrading_apk,
5773                                curr, total), true);
5774            } catch (RemoteException e) {
5775            }
5776        }
5777        PackageParser.Package p = pkg;
5778        synchronized (mInstallLock) {
5779            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5780                    false /* force dex */, false /* defer */, true /* include dependencies */);
5781        }
5782    }
5783
5784    @Override
5785    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5786        return performDexOpt(packageName, instructionSet, false);
5787    }
5788
5789    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5790        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5791        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5792        if (!dexopt && !updateUsage) {
5793            // We aren't going to dexopt or update usage, so bail early.
5794            return false;
5795        }
5796        PackageParser.Package p;
5797        final String targetInstructionSet;
5798        synchronized (mPackages) {
5799            p = mPackages.get(packageName);
5800            if (p == null) {
5801                return false;
5802            }
5803            if (updateUsage) {
5804                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5805            }
5806            mPackageUsage.write(false);
5807            if (!dexopt) {
5808                // We aren't going to dexopt, so bail early.
5809                return false;
5810            }
5811
5812            targetInstructionSet = instructionSet != null ? instructionSet :
5813                    getPrimaryInstructionSet(p.applicationInfo);
5814            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5815                return false;
5816            }
5817        }
5818
5819        synchronized (mInstallLock) {
5820            final String[] instructionSets = new String[] { targetInstructionSet };
5821            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5822                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5823            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5824        }
5825    }
5826
5827    public ArraySet<String> getPackagesThatNeedDexOpt() {
5828        ArraySet<String> pkgs = null;
5829        synchronized (mPackages) {
5830            for (PackageParser.Package p : mPackages.values()) {
5831                if (DEBUG_DEXOPT) {
5832                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5833                }
5834                if (!p.mDexOptPerformed.isEmpty()) {
5835                    continue;
5836                }
5837                if (pkgs == null) {
5838                    pkgs = new ArraySet<String>();
5839                }
5840                pkgs.add(p.packageName);
5841            }
5842        }
5843        return pkgs;
5844    }
5845
5846    public void shutdown() {
5847        mPackageUsage.write(true);
5848    }
5849
5850    @Override
5851    public void forceDexOpt(String packageName) {
5852        enforceSystemOrRoot("forceDexOpt");
5853
5854        PackageParser.Package pkg;
5855        synchronized (mPackages) {
5856            pkg = mPackages.get(packageName);
5857            if (pkg == null) {
5858                throw new IllegalArgumentException("Missing package: " + packageName);
5859            }
5860        }
5861
5862        synchronized (mInstallLock) {
5863            final String[] instructionSets = new String[] {
5864                    getPrimaryInstructionSet(pkg.applicationInfo) };
5865            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5866                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5867            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5868                throw new IllegalStateException("Failed to dexopt: " + res);
5869            }
5870        }
5871    }
5872
5873    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5874        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5875            Slog.w(TAG, "Unable to update from " + oldPkg.name
5876                    + " to " + newPkg.packageName
5877                    + ": old package not in system partition");
5878            return false;
5879        } else if (mPackages.get(oldPkg.name) != null) {
5880            Slog.w(TAG, "Unable to update from " + oldPkg.name
5881                    + " to " + newPkg.packageName
5882                    + ": old package still exists");
5883            return false;
5884        }
5885        return true;
5886    }
5887
5888    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5889        int[] users = sUserManager.getUserIds();
5890        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5891        if (res < 0) {
5892            return res;
5893        }
5894        for (int user : users) {
5895            if (user != 0) {
5896                res = mInstaller.createUserData(volumeUuid, packageName,
5897                        UserHandle.getUid(user, uid), user, seinfo);
5898                if (res < 0) {
5899                    return res;
5900                }
5901            }
5902        }
5903        return res;
5904    }
5905
5906    private int removeDataDirsLI(String volumeUuid, String packageName) {
5907        int[] users = sUserManager.getUserIds();
5908        int res = 0;
5909        for (int user : users) {
5910            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5911            if (resInner < 0) {
5912                res = resInner;
5913            }
5914        }
5915
5916        return res;
5917    }
5918
5919    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5920        int[] users = sUserManager.getUserIds();
5921        int res = 0;
5922        for (int user : users) {
5923            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5924            if (resInner < 0) {
5925                res = resInner;
5926            }
5927        }
5928        return res;
5929    }
5930
5931    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5932            PackageParser.Package changingLib) {
5933        if (file.path != null) {
5934            usesLibraryFiles.add(file.path);
5935            return;
5936        }
5937        PackageParser.Package p = mPackages.get(file.apk);
5938        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5939            // If we are doing this while in the middle of updating a library apk,
5940            // then we need to make sure to use that new apk for determining the
5941            // dependencies here.  (We haven't yet finished committing the new apk
5942            // to the package manager state.)
5943            if (p == null || p.packageName.equals(changingLib.packageName)) {
5944                p = changingLib;
5945            }
5946        }
5947        if (p != null) {
5948            usesLibraryFiles.addAll(p.getAllCodePaths());
5949        }
5950    }
5951
5952    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5953            PackageParser.Package changingLib) throws PackageManagerException {
5954        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5955            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5956            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5957            for (int i=0; i<N; i++) {
5958                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5959                if (file == null) {
5960                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5961                            "Package " + pkg.packageName + " requires unavailable shared library "
5962                            + pkg.usesLibraries.get(i) + "; failing!");
5963                }
5964                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5965            }
5966            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5967            for (int i=0; i<N; i++) {
5968                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5969                if (file == null) {
5970                    Slog.w(TAG, "Package " + pkg.packageName
5971                            + " desires unavailable shared library "
5972                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5973                } else {
5974                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5975                }
5976            }
5977            N = usesLibraryFiles.size();
5978            if (N > 0) {
5979                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5980            } else {
5981                pkg.usesLibraryFiles = null;
5982            }
5983        }
5984    }
5985
5986    private static boolean hasString(List<String> list, List<String> which) {
5987        if (list == null) {
5988            return false;
5989        }
5990        for (int i=list.size()-1; i>=0; i--) {
5991            for (int j=which.size()-1; j>=0; j--) {
5992                if (which.get(j).equals(list.get(i))) {
5993                    return true;
5994                }
5995            }
5996        }
5997        return false;
5998    }
5999
6000    private void updateAllSharedLibrariesLPw() {
6001        for (PackageParser.Package pkg : mPackages.values()) {
6002            try {
6003                updateSharedLibrariesLPw(pkg, null);
6004            } catch (PackageManagerException e) {
6005                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6006            }
6007        }
6008    }
6009
6010    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6011            PackageParser.Package changingPkg) {
6012        ArrayList<PackageParser.Package> res = null;
6013        for (PackageParser.Package pkg : mPackages.values()) {
6014            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6015                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6016                if (res == null) {
6017                    res = new ArrayList<PackageParser.Package>();
6018                }
6019                res.add(pkg);
6020                try {
6021                    updateSharedLibrariesLPw(pkg, changingPkg);
6022                } catch (PackageManagerException e) {
6023                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6024                }
6025            }
6026        }
6027        return res;
6028    }
6029
6030    /**
6031     * Derive the value of the {@code cpuAbiOverride} based on the provided
6032     * value and an optional stored value from the package settings.
6033     */
6034    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6035        String cpuAbiOverride = null;
6036
6037        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6038            cpuAbiOverride = null;
6039        } else if (abiOverride != null) {
6040            cpuAbiOverride = abiOverride;
6041        } else if (settings != null) {
6042            cpuAbiOverride = settings.cpuAbiOverrideString;
6043        }
6044
6045        return cpuAbiOverride;
6046    }
6047
6048    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6049            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6050        boolean success = false;
6051        try {
6052            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6053                    currentTime, user);
6054            success = true;
6055            return res;
6056        } finally {
6057            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6058                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6059            }
6060        }
6061    }
6062
6063    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6064            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6065        final File scanFile = new File(pkg.codePath);
6066        if (pkg.applicationInfo.getCodePath() == null ||
6067                pkg.applicationInfo.getResourcePath() == null) {
6068            // Bail out. The resource and code paths haven't been set.
6069            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6070                    "Code and resource paths haven't been set correctly");
6071        }
6072
6073        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6074            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6075        } else {
6076            // Only allow system apps to be flagged as core apps.
6077            pkg.coreApp = false;
6078        }
6079
6080        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6081            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6082        }
6083
6084        if (mCustomResolverComponentName != null &&
6085                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6086            setUpCustomResolverActivity(pkg);
6087        }
6088
6089        if (pkg.packageName.equals("android")) {
6090            synchronized (mPackages) {
6091                if (mAndroidApplication != null) {
6092                    Slog.w(TAG, "*************************************************");
6093                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6094                    Slog.w(TAG, " file=" + scanFile);
6095                    Slog.w(TAG, "*************************************************");
6096                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6097                            "Core android package being redefined.  Skipping.");
6098                }
6099
6100                // Set up information for our fall-back user intent resolution activity.
6101                mPlatformPackage = pkg;
6102                pkg.mVersionCode = mSdkVersion;
6103                mAndroidApplication = pkg.applicationInfo;
6104
6105                if (!mResolverReplaced) {
6106                    mResolveActivity.applicationInfo = mAndroidApplication;
6107                    mResolveActivity.name = ResolverActivity.class.getName();
6108                    mResolveActivity.packageName = mAndroidApplication.packageName;
6109                    mResolveActivity.processName = "system:ui";
6110                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6111                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6112                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6113                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6114                    mResolveActivity.exported = true;
6115                    mResolveActivity.enabled = true;
6116                    mResolveInfo.activityInfo = mResolveActivity;
6117                    mResolveInfo.priority = 0;
6118                    mResolveInfo.preferredOrder = 0;
6119                    mResolveInfo.match = 0;
6120                    mResolveComponentName = new ComponentName(
6121                            mAndroidApplication.packageName, mResolveActivity.name);
6122                }
6123            }
6124        }
6125
6126        if (DEBUG_PACKAGE_SCANNING) {
6127            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6128                Log.d(TAG, "Scanning package " + pkg.packageName);
6129        }
6130
6131        if (mPackages.containsKey(pkg.packageName)
6132                || mSharedLibraries.containsKey(pkg.packageName)) {
6133            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6134                    "Application package " + pkg.packageName
6135                    + " already installed.  Skipping duplicate.");
6136        }
6137
6138        // If we're only installing presumed-existing packages, require that the
6139        // scanned APK is both already known and at the path previously established
6140        // for it.  Previously unknown packages we pick up normally, but if we have an
6141        // a priori expectation about this package's install presence, enforce it.
6142        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6143            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6144            if (known != null) {
6145                if (DEBUG_PACKAGE_SCANNING) {
6146                    Log.d(TAG, "Examining " + pkg.codePath
6147                            + " and requiring known paths " + known.codePathString
6148                            + " & " + known.resourcePathString);
6149                }
6150                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6151                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6152                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6153                            "Application package " + pkg.packageName
6154                            + " found at " + pkg.applicationInfo.getCodePath()
6155                            + " but expected at " + known.codePathString + "; ignoring.");
6156                }
6157            }
6158        }
6159
6160        // Initialize package source and resource directories
6161        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6162        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6163
6164        SharedUserSetting suid = null;
6165        PackageSetting pkgSetting = null;
6166
6167        if (!isSystemApp(pkg)) {
6168            // Only system apps can use these features.
6169            pkg.mOriginalPackages = null;
6170            pkg.mRealPackage = null;
6171            pkg.mAdoptPermissions = null;
6172        }
6173
6174        // writer
6175        synchronized (mPackages) {
6176            if (pkg.mSharedUserId != null) {
6177                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6178                if (suid == null) {
6179                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6180                            "Creating application package " + pkg.packageName
6181                            + " for shared user failed");
6182                }
6183                if (DEBUG_PACKAGE_SCANNING) {
6184                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6185                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6186                                + "): packages=" + suid.packages);
6187                }
6188            }
6189
6190            // Check if we are renaming from an original package name.
6191            PackageSetting origPackage = null;
6192            String realName = null;
6193            if (pkg.mOriginalPackages != null) {
6194                // This package may need to be renamed to a previously
6195                // installed name.  Let's check on that...
6196                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6197                if (pkg.mOriginalPackages.contains(renamed)) {
6198                    // This package had originally been installed as the
6199                    // original name, and we have already taken care of
6200                    // transitioning to the new one.  Just update the new
6201                    // one to continue using the old name.
6202                    realName = pkg.mRealPackage;
6203                    if (!pkg.packageName.equals(renamed)) {
6204                        // Callers into this function may have already taken
6205                        // care of renaming the package; only do it here if
6206                        // it is not already done.
6207                        pkg.setPackageName(renamed);
6208                    }
6209
6210                } else {
6211                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6212                        if ((origPackage = mSettings.peekPackageLPr(
6213                                pkg.mOriginalPackages.get(i))) != null) {
6214                            // We do have the package already installed under its
6215                            // original name...  should we use it?
6216                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6217                                // New package is not compatible with original.
6218                                origPackage = null;
6219                                continue;
6220                            } else if (origPackage.sharedUser != null) {
6221                                // Make sure uid is compatible between packages.
6222                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6223                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6224                                            + " to " + pkg.packageName + ": old uid "
6225                                            + origPackage.sharedUser.name
6226                                            + " differs from " + pkg.mSharedUserId);
6227                                    origPackage = null;
6228                                    continue;
6229                                }
6230                            } else {
6231                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6232                                        + pkg.packageName + " to old name " + origPackage.name);
6233                            }
6234                            break;
6235                        }
6236                    }
6237                }
6238            }
6239
6240            if (mTransferedPackages.contains(pkg.packageName)) {
6241                Slog.w(TAG, "Package " + pkg.packageName
6242                        + " was transferred to another, but its .apk remains");
6243            }
6244
6245            // Just create the setting, don't add it yet. For already existing packages
6246            // the PkgSetting exists already and doesn't have to be created.
6247            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6248                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6249                    pkg.applicationInfo.primaryCpuAbi,
6250                    pkg.applicationInfo.secondaryCpuAbi,
6251                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6252                    user, false);
6253            if (pkgSetting == null) {
6254                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6255                        "Creating application package " + pkg.packageName + " failed");
6256            }
6257
6258            if (pkgSetting.origPackage != null) {
6259                // If we are first transitioning from an original package,
6260                // fix up the new package's name now.  We need to do this after
6261                // looking up the package under its new name, so getPackageLP
6262                // can take care of fiddling things correctly.
6263                pkg.setPackageName(origPackage.name);
6264
6265                // File a report about this.
6266                String msg = "New package " + pkgSetting.realName
6267                        + " renamed to replace old package " + pkgSetting.name;
6268                reportSettingsProblem(Log.WARN, msg);
6269
6270                // Make a note of it.
6271                mTransferedPackages.add(origPackage.name);
6272
6273                // No longer need to retain this.
6274                pkgSetting.origPackage = null;
6275            }
6276
6277            if (realName != null) {
6278                // Make a note of it.
6279                mTransferedPackages.add(pkg.packageName);
6280            }
6281
6282            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6283                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6284            }
6285
6286            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6287                // Check all shared libraries and map to their actual file path.
6288                // We only do this here for apps not on a system dir, because those
6289                // are the only ones that can fail an install due to this.  We
6290                // will take care of the system apps by updating all of their
6291                // library paths after the scan is done.
6292                updateSharedLibrariesLPw(pkg, null);
6293            }
6294
6295            if (mFoundPolicyFile) {
6296                SELinuxMMAC.assignSeinfoValue(pkg);
6297            }
6298
6299            pkg.applicationInfo.uid = pkgSetting.appId;
6300            pkg.mExtras = pkgSetting;
6301            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6302                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6303                    // We just determined the app is signed correctly, so bring
6304                    // over the latest parsed certs.
6305                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6306                } else {
6307                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6308                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6309                                "Package " + pkg.packageName + " upgrade keys do not match the "
6310                                + "previously installed version");
6311                    } else {
6312                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6313                        String msg = "System package " + pkg.packageName
6314                            + " signature changed; retaining data.";
6315                        reportSettingsProblem(Log.WARN, msg);
6316                    }
6317                }
6318            } else {
6319                try {
6320                    verifySignaturesLP(pkgSetting, pkg);
6321                    // We just determined the app is signed correctly, so bring
6322                    // over the latest parsed certs.
6323                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6324                } catch (PackageManagerException e) {
6325                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6326                        throw e;
6327                    }
6328                    // The signature has changed, but this package is in the system
6329                    // image...  let's recover!
6330                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6331                    // However...  if this package is part of a shared user, but it
6332                    // doesn't match the signature of the shared user, let's fail.
6333                    // What this means is that you can't change the signatures
6334                    // associated with an overall shared user, which doesn't seem all
6335                    // that unreasonable.
6336                    if (pkgSetting.sharedUser != null) {
6337                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6338                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6339                            throw new PackageManagerException(
6340                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6341                                            "Signature mismatch for shared user : "
6342                                            + pkgSetting.sharedUser);
6343                        }
6344                    }
6345                    // File a report about this.
6346                    String msg = "System package " + pkg.packageName
6347                        + " signature changed; retaining data.";
6348                    reportSettingsProblem(Log.WARN, msg);
6349                }
6350            }
6351            // Verify that this new package doesn't have any content providers
6352            // that conflict with existing packages.  Only do this if the
6353            // package isn't already installed, since we don't want to break
6354            // things that are installed.
6355            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6356                final int N = pkg.providers.size();
6357                int i;
6358                for (i=0; i<N; i++) {
6359                    PackageParser.Provider p = pkg.providers.get(i);
6360                    if (p.info.authority != null) {
6361                        String names[] = p.info.authority.split(";");
6362                        for (int j = 0; j < names.length; j++) {
6363                            if (mProvidersByAuthority.containsKey(names[j])) {
6364                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6365                                final String otherPackageName =
6366                                        ((other != null && other.getComponentName() != null) ?
6367                                                other.getComponentName().getPackageName() : "?");
6368                                throw new PackageManagerException(
6369                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6370                                                "Can't install because provider name " + names[j]
6371                                                + " (in package " + pkg.applicationInfo.packageName
6372                                                + ") is already used by " + otherPackageName);
6373                            }
6374                        }
6375                    }
6376                }
6377            }
6378
6379            if (pkg.mAdoptPermissions != null) {
6380                // This package wants to adopt ownership of permissions from
6381                // another package.
6382                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6383                    final String origName = pkg.mAdoptPermissions.get(i);
6384                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6385                    if (orig != null) {
6386                        if (verifyPackageUpdateLPr(orig, pkg)) {
6387                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6388                                    + pkg.packageName);
6389                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6390                        }
6391                    }
6392                }
6393            }
6394        }
6395
6396        final String pkgName = pkg.packageName;
6397
6398        final long scanFileTime = scanFile.lastModified();
6399        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6400        pkg.applicationInfo.processName = fixProcessName(
6401                pkg.applicationInfo.packageName,
6402                pkg.applicationInfo.processName,
6403                pkg.applicationInfo.uid);
6404
6405        File dataPath;
6406        if (mPlatformPackage == pkg) {
6407            // The system package is special.
6408            dataPath = new File(Environment.getDataDirectory(), "system");
6409
6410            pkg.applicationInfo.dataDir = dataPath.getPath();
6411
6412        } else {
6413            // This is a normal package, need to make its data directory.
6414            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6415                    UserHandle.USER_OWNER);
6416
6417            boolean uidError = false;
6418            if (dataPath.exists()) {
6419                int currentUid = 0;
6420                try {
6421                    StructStat stat = Os.stat(dataPath.getPath());
6422                    currentUid = stat.st_uid;
6423                } catch (ErrnoException e) {
6424                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6425                }
6426
6427                // If we have mismatched owners for the data path, we have a problem.
6428                if (currentUid != pkg.applicationInfo.uid) {
6429                    boolean recovered = false;
6430                    if (currentUid == 0) {
6431                        // The directory somehow became owned by root.  Wow.
6432                        // This is probably because the system was stopped while
6433                        // installd was in the middle of messing with its libs
6434                        // directory.  Ask installd to fix that.
6435                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6436                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6437                        if (ret >= 0) {
6438                            recovered = true;
6439                            String msg = "Package " + pkg.packageName
6440                                    + " unexpectedly changed to uid 0; recovered to " +
6441                                    + pkg.applicationInfo.uid;
6442                            reportSettingsProblem(Log.WARN, msg);
6443                        }
6444                    }
6445                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6446                            || (scanFlags&SCAN_BOOTING) != 0)) {
6447                        // If this is a system app, we can at least delete its
6448                        // current data so the application will still work.
6449                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6450                        if (ret >= 0) {
6451                            // TODO: Kill the processes first
6452                            // Old data gone!
6453                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6454                                    ? "System package " : "Third party package ";
6455                            String msg = prefix + pkg.packageName
6456                                    + " has changed from uid: "
6457                                    + currentUid + " to "
6458                                    + pkg.applicationInfo.uid + "; old data erased";
6459                            reportSettingsProblem(Log.WARN, msg);
6460                            recovered = true;
6461
6462                            // And now re-install the app.
6463                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6464                                    pkg.applicationInfo.seinfo);
6465                            if (ret == -1) {
6466                                // Ack should not happen!
6467                                msg = prefix + pkg.packageName
6468                                        + " could not have data directory re-created after delete.";
6469                                reportSettingsProblem(Log.WARN, msg);
6470                                throw new PackageManagerException(
6471                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6472                            }
6473                        }
6474                        if (!recovered) {
6475                            mHasSystemUidErrors = true;
6476                        }
6477                    } else if (!recovered) {
6478                        // If we allow this install to proceed, we will be broken.
6479                        // Abort, abort!
6480                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6481                                "scanPackageLI");
6482                    }
6483                    if (!recovered) {
6484                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6485                            + pkg.applicationInfo.uid + "/fs_"
6486                            + currentUid;
6487                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6488                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6489                        String msg = "Package " + pkg.packageName
6490                                + " has mismatched uid: "
6491                                + currentUid + " on disk, "
6492                                + pkg.applicationInfo.uid + " in settings";
6493                        // writer
6494                        synchronized (mPackages) {
6495                            mSettings.mReadMessages.append(msg);
6496                            mSettings.mReadMessages.append('\n');
6497                            uidError = true;
6498                            if (!pkgSetting.uidError) {
6499                                reportSettingsProblem(Log.ERROR, msg);
6500                            }
6501                        }
6502                    }
6503                }
6504                pkg.applicationInfo.dataDir = dataPath.getPath();
6505                if (mShouldRestoreconData) {
6506                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6507                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6508                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6509                }
6510            } else {
6511                if (DEBUG_PACKAGE_SCANNING) {
6512                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6513                        Log.v(TAG, "Want this data dir: " + dataPath);
6514                }
6515                //invoke installer to do the actual installation
6516                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6517                        pkg.applicationInfo.seinfo);
6518                if (ret < 0) {
6519                    // Error from installer
6520                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6521                            "Unable to create data dirs [errorCode=" + ret + "]");
6522                }
6523
6524                if (dataPath.exists()) {
6525                    pkg.applicationInfo.dataDir = dataPath.getPath();
6526                } else {
6527                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6528                    pkg.applicationInfo.dataDir = null;
6529                }
6530            }
6531
6532            pkgSetting.uidError = uidError;
6533        }
6534
6535        final String path = scanFile.getPath();
6536        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6537
6538        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6539            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6540
6541            // Some system apps still use directory structure for native libraries
6542            // in which case we might end up not detecting abi solely based on apk
6543            // structure. Try to detect abi based on directory structure.
6544            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6545                    pkg.applicationInfo.primaryCpuAbi == null) {
6546                setBundledAppAbisAndRoots(pkg, pkgSetting);
6547                setNativeLibraryPaths(pkg);
6548            }
6549
6550        } else {
6551            if ((scanFlags & SCAN_MOVE) != 0) {
6552                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6553                // but we already have this packages package info in the PackageSetting. We just
6554                // use that and derive the native library path based on the new codepath.
6555                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6556                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6557            }
6558
6559            // Set native library paths again. For moves, the path will be updated based on the
6560            // ABIs we've determined above. For non-moves, the path will be updated based on the
6561            // ABIs we determined during compilation, but the path will depend on the final
6562            // package path (after the rename away from the stage path).
6563            setNativeLibraryPaths(pkg);
6564        }
6565
6566        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6567        final int[] userIds = sUserManager.getUserIds();
6568        synchronized (mInstallLock) {
6569            // Create a native library symlink only if we have native libraries
6570            // and if the native libraries are 32 bit libraries. We do not provide
6571            // this symlink for 64 bit libraries.
6572            if (pkg.applicationInfo.primaryCpuAbi != null &&
6573                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6574                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6575                for (int userId : userIds) {
6576                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6577                            nativeLibPath, userId) < 0) {
6578                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6579                                "Failed linking native library dir (user=" + userId + ")");
6580                    }
6581                }
6582            }
6583        }
6584
6585        // This is a special case for the "system" package, where the ABI is
6586        // dictated by the zygote configuration (and init.rc). We should keep track
6587        // of this ABI so that we can deal with "normal" applications that run under
6588        // the same UID correctly.
6589        if (mPlatformPackage == pkg) {
6590            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6591                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6592        }
6593
6594        // If there's a mismatch between the abi-override in the package setting
6595        // and the abiOverride specified for the install. Warn about this because we
6596        // would've already compiled the app without taking the package setting into
6597        // account.
6598        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6599            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6600                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6601                        " for package: " + pkg.packageName);
6602            }
6603        }
6604
6605        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6606        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6607        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6608
6609        // Copy the derived override back to the parsed package, so that we can
6610        // update the package settings accordingly.
6611        pkg.cpuAbiOverride = cpuAbiOverride;
6612
6613        if (DEBUG_ABI_SELECTION) {
6614            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6615                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6616                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6617        }
6618
6619        // Push the derived path down into PackageSettings so we know what to
6620        // clean up at uninstall time.
6621        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6622
6623        if (DEBUG_ABI_SELECTION) {
6624            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6625                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6626                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6627        }
6628
6629        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6630            // We don't do this here during boot because we can do it all
6631            // at once after scanning all existing packages.
6632            //
6633            // We also do this *before* we perform dexopt on this package, so that
6634            // we can avoid redundant dexopts, and also to make sure we've got the
6635            // code and package path correct.
6636            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6637                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6638        }
6639
6640        if ((scanFlags & SCAN_NO_DEX) == 0) {
6641            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6642                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6643            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6644                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6645            }
6646        }
6647        if (mFactoryTest && pkg.requestedPermissions.contains(
6648                android.Manifest.permission.FACTORY_TEST)) {
6649            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6650        }
6651
6652        ArrayList<PackageParser.Package> clientLibPkgs = null;
6653
6654        // writer
6655        synchronized (mPackages) {
6656            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6657                // Only system apps can add new shared libraries.
6658                if (pkg.libraryNames != null) {
6659                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6660                        String name = pkg.libraryNames.get(i);
6661                        boolean allowed = false;
6662                        if (pkg.isUpdatedSystemApp()) {
6663                            // New library entries can only be added through the
6664                            // system image.  This is important to get rid of a lot
6665                            // of nasty edge cases: for example if we allowed a non-
6666                            // system update of the app to add a library, then uninstalling
6667                            // the update would make the library go away, and assumptions
6668                            // we made such as through app install filtering would now
6669                            // have allowed apps on the device which aren't compatible
6670                            // with it.  Better to just have the restriction here, be
6671                            // conservative, and create many fewer cases that can negatively
6672                            // impact the user experience.
6673                            final PackageSetting sysPs = mSettings
6674                                    .getDisabledSystemPkgLPr(pkg.packageName);
6675                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6676                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6677                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6678                                        allowed = true;
6679                                        allowed = true;
6680                                        break;
6681                                    }
6682                                }
6683                            }
6684                        } else {
6685                            allowed = true;
6686                        }
6687                        if (allowed) {
6688                            if (!mSharedLibraries.containsKey(name)) {
6689                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6690                            } else if (!name.equals(pkg.packageName)) {
6691                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6692                                        + name + " already exists; skipping");
6693                            }
6694                        } else {
6695                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6696                                    + name + " that is not declared on system image; skipping");
6697                        }
6698                    }
6699                    if ((scanFlags&SCAN_BOOTING) == 0) {
6700                        // If we are not booting, we need to update any applications
6701                        // that are clients of our shared library.  If we are booting,
6702                        // this will all be done once the scan is complete.
6703                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6704                    }
6705                }
6706            }
6707        }
6708
6709        // We also need to dexopt any apps that are dependent on this library.  Note that
6710        // if these fail, we should abort the install since installing the library will
6711        // result in some apps being broken.
6712        if (clientLibPkgs != null) {
6713            if ((scanFlags & SCAN_NO_DEX) == 0) {
6714                for (int i = 0; i < clientLibPkgs.size(); i++) {
6715                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6716                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6717                            null /* instruction sets */, forceDex,
6718                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6719                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6720                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6721                                "scanPackageLI failed to dexopt clientLibPkgs");
6722                    }
6723                }
6724            }
6725        }
6726
6727        // Also need to kill any apps that are dependent on the library.
6728        if (clientLibPkgs != null) {
6729            for (int i=0; i<clientLibPkgs.size(); i++) {
6730                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6731                killApplication(clientPkg.applicationInfo.packageName,
6732                        clientPkg.applicationInfo.uid, "update lib");
6733            }
6734        }
6735
6736        // Make sure we're not adding any bogus keyset info
6737        KeySetManagerService ksms = mSettings.mKeySetManagerService;
6738        ksms.assertScannedPackageValid(pkg);
6739
6740        // writer
6741        synchronized (mPackages) {
6742            // We don't expect installation to fail beyond this point
6743
6744            // Add the new setting to mSettings
6745            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6746            // Add the new setting to mPackages
6747            mPackages.put(pkg.applicationInfo.packageName, pkg);
6748            // Make sure we don't accidentally delete its data.
6749            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6750            while (iter.hasNext()) {
6751                PackageCleanItem item = iter.next();
6752                if (pkgName.equals(item.packageName)) {
6753                    iter.remove();
6754                }
6755            }
6756
6757            // Take care of first install / last update times.
6758            if (currentTime != 0) {
6759                if (pkgSetting.firstInstallTime == 0) {
6760                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6761                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6762                    pkgSetting.lastUpdateTime = currentTime;
6763                }
6764            } else if (pkgSetting.firstInstallTime == 0) {
6765                // We need *something*.  Take time time stamp of the file.
6766                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6767            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6768                if (scanFileTime != pkgSetting.timeStamp) {
6769                    // A package on the system image has changed; consider this
6770                    // to be an update.
6771                    pkgSetting.lastUpdateTime = scanFileTime;
6772                }
6773            }
6774
6775            // Add the package's KeySets to the global KeySetManagerService
6776            ksms.addScannedPackageLPw(pkg);
6777
6778            int N = pkg.providers.size();
6779            StringBuilder r = null;
6780            int i;
6781            for (i=0; i<N; i++) {
6782                PackageParser.Provider p = pkg.providers.get(i);
6783                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6784                        p.info.processName, pkg.applicationInfo.uid);
6785                mProviders.addProvider(p);
6786                p.syncable = p.info.isSyncable;
6787                if (p.info.authority != null) {
6788                    String names[] = p.info.authority.split(";");
6789                    p.info.authority = null;
6790                    for (int j = 0; j < names.length; j++) {
6791                        if (j == 1 && p.syncable) {
6792                            // We only want the first authority for a provider to possibly be
6793                            // syncable, so if we already added this provider using a different
6794                            // authority clear the syncable flag. We copy the provider before
6795                            // changing it because the mProviders object contains a reference
6796                            // to a provider that we don't want to change.
6797                            // Only do this for the second authority since the resulting provider
6798                            // object can be the same for all future authorities for this provider.
6799                            p = new PackageParser.Provider(p);
6800                            p.syncable = false;
6801                        }
6802                        if (!mProvidersByAuthority.containsKey(names[j])) {
6803                            mProvidersByAuthority.put(names[j], p);
6804                            if (p.info.authority == null) {
6805                                p.info.authority = names[j];
6806                            } else {
6807                                p.info.authority = p.info.authority + ";" + names[j];
6808                            }
6809                            if (DEBUG_PACKAGE_SCANNING) {
6810                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6811                                    Log.d(TAG, "Registered content provider: " + names[j]
6812                                            + ", className = " + p.info.name + ", isSyncable = "
6813                                            + p.info.isSyncable);
6814                            }
6815                        } else {
6816                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6817                            Slog.w(TAG, "Skipping provider name " + names[j] +
6818                                    " (in package " + pkg.applicationInfo.packageName +
6819                                    "): name already used by "
6820                                    + ((other != null && other.getComponentName() != null)
6821                                            ? other.getComponentName().getPackageName() : "?"));
6822                        }
6823                    }
6824                }
6825                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6826                    if (r == null) {
6827                        r = new StringBuilder(256);
6828                    } else {
6829                        r.append(' ');
6830                    }
6831                    r.append(p.info.name);
6832                }
6833            }
6834            if (r != null) {
6835                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6836            }
6837
6838            N = pkg.services.size();
6839            r = null;
6840            for (i=0; i<N; i++) {
6841                PackageParser.Service s = pkg.services.get(i);
6842                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6843                        s.info.processName, pkg.applicationInfo.uid);
6844                mServices.addService(s);
6845                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6846                    if (r == null) {
6847                        r = new StringBuilder(256);
6848                    } else {
6849                        r.append(' ');
6850                    }
6851                    r.append(s.info.name);
6852                }
6853            }
6854            if (r != null) {
6855                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6856            }
6857
6858            N = pkg.receivers.size();
6859            r = null;
6860            for (i=0; i<N; i++) {
6861                PackageParser.Activity a = pkg.receivers.get(i);
6862                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6863                        a.info.processName, pkg.applicationInfo.uid);
6864                mReceivers.addActivity(a, "receiver");
6865                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6866                    if (r == null) {
6867                        r = new StringBuilder(256);
6868                    } else {
6869                        r.append(' ');
6870                    }
6871                    r.append(a.info.name);
6872                }
6873            }
6874            if (r != null) {
6875                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6876            }
6877
6878            N = pkg.activities.size();
6879            r = null;
6880            for (i=0; i<N; i++) {
6881                PackageParser.Activity a = pkg.activities.get(i);
6882                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6883                        a.info.processName, pkg.applicationInfo.uid);
6884                mActivities.addActivity(a, "activity");
6885                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6886                    if (r == null) {
6887                        r = new StringBuilder(256);
6888                    } else {
6889                        r.append(' ');
6890                    }
6891                    r.append(a.info.name);
6892                }
6893            }
6894            if (r != null) {
6895                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6896            }
6897
6898            N = pkg.permissionGroups.size();
6899            r = null;
6900            for (i=0; i<N; i++) {
6901                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6902                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6903                if (cur == null) {
6904                    mPermissionGroups.put(pg.info.name, pg);
6905                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6906                        if (r == null) {
6907                            r = new StringBuilder(256);
6908                        } else {
6909                            r.append(' ');
6910                        }
6911                        r.append(pg.info.name);
6912                    }
6913                } else {
6914                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6915                            + pg.info.packageName + " ignored: original from "
6916                            + cur.info.packageName);
6917                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6918                        if (r == null) {
6919                            r = new StringBuilder(256);
6920                        } else {
6921                            r.append(' ');
6922                        }
6923                        r.append("DUP:");
6924                        r.append(pg.info.name);
6925                    }
6926                }
6927            }
6928            if (r != null) {
6929                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6930            }
6931
6932            N = pkg.permissions.size();
6933            r = null;
6934            for (i=0; i<N; i++) {
6935                PackageParser.Permission p = pkg.permissions.get(i);
6936
6937                // Now that permission groups have a special meaning, we ignore permission
6938                // groups for legacy apps to prevent unexpected behavior. In particular,
6939                // permissions for one app being granted to someone just becuase they happen
6940                // to be in a group defined by another app (before this had no implications).
6941                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6942                    p.group = mPermissionGroups.get(p.info.group);
6943                    // Warn for a permission in an unknown group.
6944                    if (p.info.group != null && p.group == null) {
6945                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6946                                + p.info.packageName + " in an unknown group " + p.info.group);
6947                    }
6948                }
6949
6950                ArrayMap<String, BasePermission> permissionMap =
6951                        p.tree ? mSettings.mPermissionTrees
6952                                : mSettings.mPermissions;
6953                BasePermission bp = permissionMap.get(p.info.name);
6954
6955                // Allow system apps to redefine non-system permissions
6956                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6957                    final boolean currentOwnerIsSystem = (bp.perm != null
6958                            && isSystemApp(bp.perm.owner));
6959                    if (isSystemApp(p.owner)) {
6960                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6961                            // It's a built-in permission and no owner, take ownership now
6962                            bp.packageSetting = pkgSetting;
6963                            bp.perm = p;
6964                            bp.uid = pkg.applicationInfo.uid;
6965                            bp.sourcePackage = p.info.packageName;
6966                        } else if (!currentOwnerIsSystem) {
6967                            String msg = "New decl " + p.owner + " of permission  "
6968                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6969                            reportSettingsProblem(Log.WARN, msg);
6970                            bp = null;
6971                        }
6972                    }
6973                }
6974
6975                if (bp == null) {
6976                    bp = new BasePermission(p.info.name, p.info.packageName,
6977                            BasePermission.TYPE_NORMAL);
6978                    permissionMap.put(p.info.name, bp);
6979                }
6980
6981                if (bp.perm == null) {
6982                    if (bp.sourcePackage == null
6983                            || bp.sourcePackage.equals(p.info.packageName)) {
6984                        BasePermission tree = findPermissionTreeLP(p.info.name);
6985                        if (tree == null
6986                                || tree.sourcePackage.equals(p.info.packageName)) {
6987                            bp.packageSetting = pkgSetting;
6988                            bp.perm = p;
6989                            bp.uid = pkg.applicationInfo.uid;
6990                            bp.sourcePackage = p.info.packageName;
6991                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6992                                if (r == null) {
6993                                    r = new StringBuilder(256);
6994                                } else {
6995                                    r.append(' ');
6996                                }
6997                                r.append(p.info.name);
6998                            }
6999                        } else {
7000                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7001                                    + p.info.packageName + " ignored: base tree "
7002                                    + tree.name + " is from package "
7003                                    + tree.sourcePackage);
7004                        }
7005                    } else {
7006                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7007                                + p.info.packageName + " ignored: original from "
7008                                + bp.sourcePackage);
7009                    }
7010                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7011                    if (r == null) {
7012                        r = new StringBuilder(256);
7013                    } else {
7014                        r.append(' ');
7015                    }
7016                    r.append("DUP:");
7017                    r.append(p.info.name);
7018                }
7019                if (bp.perm == p) {
7020                    bp.protectionLevel = p.info.protectionLevel;
7021                }
7022            }
7023
7024            if (r != null) {
7025                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7026            }
7027
7028            N = pkg.instrumentation.size();
7029            r = null;
7030            for (i=0; i<N; i++) {
7031                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7032                a.info.packageName = pkg.applicationInfo.packageName;
7033                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7034                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7035                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7036                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7037                a.info.dataDir = pkg.applicationInfo.dataDir;
7038
7039                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7040                // need other information about the application, like the ABI and what not ?
7041                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7042                mInstrumentation.put(a.getComponentName(), a);
7043                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7044                    if (r == null) {
7045                        r = new StringBuilder(256);
7046                    } else {
7047                        r.append(' ');
7048                    }
7049                    r.append(a.info.name);
7050                }
7051            }
7052            if (r != null) {
7053                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7054            }
7055
7056            if (pkg.protectedBroadcasts != null) {
7057                N = pkg.protectedBroadcasts.size();
7058                for (i=0; i<N; i++) {
7059                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7060                }
7061            }
7062
7063            pkgSetting.setTimeStamp(scanFileTime);
7064
7065            // Create idmap files for pairs of (packages, overlay packages).
7066            // Note: "android", ie framework-res.apk, is handled by native layers.
7067            if (pkg.mOverlayTarget != null) {
7068                // This is an overlay package.
7069                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7070                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7071                        mOverlays.put(pkg.mOverlayTarget,
7072                                new ArrayMap<String, PackageParser.Package>());
7073                    }
7074                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7075                    map.put(pkg.packageName, pkg);
7076                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7077                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7078                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7079                                "scanPackageLI failed to createIdmap");
7080                    }
7081                }
7082            } else if (mOverlays.containsKey(pkg.packageName) &&
7083                    !pkg.packageName.equals("android")) {
7084                // This is a regular package, with one or more known overlay packages.
7085                createIdmapsForPackageLI(pkg);
7086            }
7087        }
7088
7089        return pkg;
7090    }
7091
7092    /**
7093     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7094     * is derived purely on the basis of the contents of {@code scanFile} and
7095     * {@code cpuAbiOverride}.
7096     *
7097     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7098     */
7099    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7100                                 String cpuAbiOverride, boolean extractLibs)
7101            throws PackageManagerException {
7102        // TODO: We can probably be smarter about this stuff. For installed apps,
7103        // we can calculate this information at install time once and for all. For
7104        // system apps, we can probably assume that this information doesn't change
7105        // after the first boot scan. As things stand, we do lots of unnecessary work.
7106
7107        // Give ourselves some initial paths; we'll come back for another
7108        // pass once we've determined ABI below.
7109        setNativeLibraryPaths(pkg);
7110
7111        // We would never need to extract libs for forward-locked and external packages,
7112        // since the container service will do it for us. We shouldn't attempt to
7113        // extract libs from system app when it was not updated.
7114        if (pkg.isForwardLocked() || isExternal(pkg) ||
7115            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7116            extractLibs = false;
7117        }
7118
7119        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7120        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7121
7122        NativeLibraryHelper.Handle handle = null;
7123        try {
7124            handle = NativeLibraryHelper.Handle.create(scanFile);
7125            // TODO(multiArch): This can be null for apps that didn't go through the
7126            // usual installation process. We can calculate it again, like we
7127            // do during install time.
7128            //
7129            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7130            // unnecessary.
7131            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7132
7133            // Null out the abis so that they can be recalculated.
7134            pkg.applicationInfo.primaryCpuAbi = null;
7135            pkg.applicationInfo.secondaryCpuAbi = null;
7136            if (isMultiArch(pkg.applicationInfo)) {
7137                // Warn if we've set an abiOverride for multi-lib packages..
7138                // By definition, we need to copy both 32 and 64 bit libraries for
7139                // such packages.
7140                if (pkg.cpuAbiOverride != null
7141                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7142                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7143                }
7144
7145                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7146                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7147                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7148                    if (extractLibs) {
7149                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7150                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7151                                useIsaSpecificSubdirs);
7152                    } else {
7153                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7154                    }
7155                }
7156
7157                maybeThrowExceptionForMultiArchCopy(
7158                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7159
7160                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7161                    if (extractLibs) {
7162                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7163                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7164                                useIsaSpecificSubdirs);
7165                    } else {
7166                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7167                    }
7168                }
7169
7170                maybeThrowExceptionForMultiArchCopy(
7171                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7172
7173                if (abi64 >= 0) {
7174                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7175                }
7176
7177                if (abi32 >= 0) {
7178                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7179                    if (abi64 >= 0) {
7180                        pkg.applicationInfo.secondaryCpuAbi = abi;
7181                    } else {
7182                        pkg.applicationInfo.primaryCpuAbi = abi;
7183                    }
7184                }
7185            } else {
7186                String[] abiList = (cpuAbiOverride != null) ?
7187                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7188
7189                // Enable gross and lame hacks for apps that are built with old
7190                // SDK tools. We must scan their APKs for renderscript bitcode and
7191                // not launch them if it's present. Don't bother checking on devices
7192                // that don't have 64 bit support.
7193                boolean needsRenderScriptOverride = false;
7194                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7195                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7196                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7197                    needsRenderScriptOverride = true;
7198                }
7199
7200                final int copyRet;
7201                if (extractLibs) {
7202                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7203                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7204                } else {
7205                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7206                }
7207
7208                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7209                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7210                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7211                }
7212
7213                if (copyRet >= 0) {
7214                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7215                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7216                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7217                } else if (needsRenderScriptOverride) {
7218                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7219                }
7220            }
7221        } catch (IOException ioe) {
7222            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7223        } finally {
7224            IoUtils.closeQuietly(handle);
7225        }
7226
7227        // Now that we've calculated the ABIs and determined if it's an internal app,
7228        // we will go ahead and populate the nativeLibraryPath.
7229        setNativeLibraryPaths(pkg);
7230    }
7231
7232    /**
7233     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7234     * i.e, so that all packages can be run inside a single process if required.
7235     *
7236     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7237     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7238     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7239     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7240     * updating a package that belongs to a shared user.
7241     *
7242     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7243     * adds unnecessary complexity.
7244     */
7245    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7246            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7247        String requiredInstructionSet = null;
7248        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7249            requiredInstructionSet = VMRuntime.getInstructionSet(
7250                     scannedPackage.applicationInfo.primaryCpuAbi);
7251        }
7252
7253        PackageSetting requirer = null;
7254        for (PackageSetting ps : packagesForUser) {
7255            // If packagesForUser contains scannedPackage, we skip it. This will happen
7256            // when scannedPackage is an update of an existing package. Without this check,
7257            // we will never be able to change the ABI of any package belonging to a shared
7258            // user, even if it's compatible with other packages.
7259            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7260                if (ps.primaryCpuAbiString == null) {
7261                    continue;
7262                }
7263
7264                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7265                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7266                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7267                    // this but there's not much we can do.
7268                    String errorMessage = "Instruction set mismatch, "
7269                            + ((requirer == null) ? "[caller]" : requirer)
7270                            + " requires " + requiredInstructionSet + " whereas " + ps
7271                            + " requires " + instructionSet;
7272                    Slog.w(TAG, errorMessage);
7273                }
7274
7275                if (requiredInstructionSet == null) {
7276                    requiredInstructionSet = instructionSet;
7277                    requirer = ps;
7278                }
7279            }
7280        }
7281
7282        if (requiredInstructionSet != null) {
7283            String adjustedAbi;
7284            if (requirer != null) {
7285                // requirer != null implies that either scannedPackage was null or that scannedPackage
7286                // did not require an ABI, in which case we have to adjust scannedPackage to match
7287                // the ABI of the set (which is the same as requirer's ABI)
7288                adjustedAbi = requirer.primaryCpuAbiString;
7289                if (scannedPackage != null) {
7290                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7291                }
7292            } else {
7293                // requirer == null implies that we're updating all ABIs in the set to
7294                // match scannedPackage.
7295                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7296            }
7297
7298            for (PackageSetting ps : packagesForUser) {
7299                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7300                    if (ps.primaryCpuAbiString != null) {
7301                        continue;
7302                    }
7303
7304                    ps.primaryCpuAbiString = adjustedAbi;
7305                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7306                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7307                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7308
7309                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7310                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7311                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7312                            ps.primaryCpuAbiString = null;
7313                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7314                            return;
7315                        } else {
7316                            mInstaller.rmdex(ps.codePathString,
7317                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7318                        }
7319                    }
7320                }
7321            }
7322        }
7323    }
7324
7325    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7326        synchronized (mPackages) {
7327            mResolverReplaced = true;
7328            // Set up information for custom user intent resolution activity.
7329            mResolveActivity.applicationInfo = pkg.applicationInfo;
7330            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7331            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7332            mResolveActivity.processName = pkg.applicationInfo.packageName;
7333            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7334            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7335                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7336            mResolveActivity.theme = 0;
7337            mResolveActivity.exported = true;
7338            mResolveActivity.enabled = true;
7339            mResolveInfo.activityInfo = mResolveActivity;
7340            mResolveInfo.priority = 0;
7341            mResolveInfo.preferredOrder = 0;
7342            mResolveInfo.match = 0;
7343            mResolveComponentName = mCustomResolverComponentName;
7344            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7345                    mResolveComponentName);
7346        }
7347    }
7348
7349    private static String calculateBundledApkRoot(final String codePathString) {
7350        final File codePath = new File(codePathString);
7351        final File codeRoot;
7352        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7353            codeRoot = Environment.getRootDirectory();
7354        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7355            codeRoot = Environment.getOemDirectory();
7356        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7357            codeRoot = Environment.getVendorDirectory();
7358        } else {
7359            // Unrecognized code path; take its top real segment as the apk root:
7360            // e.g. /something/app/blah.apk => /something
7361            try {
7362                File f = codePath.getCanonicalFile();
7363                File parent = f.getParentFile();    // non-null because codePath is a file
7364                File tmp;
7365                while ((tmp = parent.getParentFile()) != null) {
7366                    f = parent;
7367                    parent = tmp;
7368                }
7369                codeRoot = f;
7370                Slog.w(TAG, "Unrecognized code path "
7371                        + codePath + " - using " + codeRoot);
7372            } catch (IOException e) {
7373                // Can't canonicalize the code path -- shenanigans?
7374                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7375                return Environment.getRootDirectory().getPath();
7376            }
7377        }
7378        return codeRoot.getPath();
7379    }
7380
7381    /**
7382     * Derive and set the location of native libraries for the given package,
7383     * which varies depending on where and how the package was installed.
7384     */
7385    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7386        final ApplicationInfo info = pkg.applicationInfo;
7387        final String codePath = pkg.codePath;
7388        final File codeFile = new File(codePath);
7389        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7390        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7391
7392        info.nativeLibraryRootDir = null;
7393        info.nativeLibraryRootRequiresIsa = false;
7394        info.nativeLibraryDir = null;
7395        info.secondaryNativeLibraryDir = null;
7396
7397        if (isApkFile(codeFile)) {
7398            // Monolithic install
7399            if (bundledApp) {
7400                // If "/system/lib64/apkname" exists, assume that is the per-package
7401                // native library directory to use; otherwise use "/system/lib/apkname".
7402                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7403                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7404                        getPrimaryInstructionSet(info));
7405
7406                // This is a bundled system app so choose the path based on the ABI.
7407                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7408                // is just the default path.
7409                final String apkName = deriveCodePathName(codePath);
7410                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7411                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7412                        apkName).getAbsolutePath();
7413
7414                if (info.secondaryCpuAbi != null) {
7415                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7416                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7417                            secondaryLibDir, apkName).getAbsolutePath();
7418                }
7419            } else if (asecApp) {
7420                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7421                        .getAbsolutePath();
7422            } else {
7423                final String apkName = deriveCodePathName(codePath);
7424                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7425                        .getAbsolutePath();
7426            }
7427
7428            info.nativeLibraryRootRequiresIsa = false;
7429            info.nativeLibraryDir = info.nativeLibraryRootDir;
7430        } else {
7431            // Cluster install
7432            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7433            info.nativeLibraryRootRequiresIsa = true;
7434
7435            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7436                    getPrimaryInstructionSet(info)).getAbsolutePath();
7437
7438            if (info.secondaryCpuAbi != null) {
7439                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7440                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7441            }
7442        }
7443    }
7444
7445    /**
7446     * Calculate the abis and roots for a bundled app. These can uniquely
7447     * be determined from the contents of the system partition, i.e whether
7448     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7449     * of this information, and instead assume that the system was built
7450     * sensibly.
7451     */
7452    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7453                                           PackageSetting pkgSetting) {
7454        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7455
7456        // If "/system/lib64/apkname" exists, assume that is the per-package
7457        // native library directory to use; otherwise use "/system/lib/apkname".
7458        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7459        setBundledAppAbi(pkg, apkRoot, apkName);
7460        // pkgSetting might be null during rescan following uninstall of updates
7461        // to a bundled app, so accommodate that possibility.  The settings in
7462        // that case will be established later from the parsed package.
7463        //
7464        // If the settings aren't null, sync them up with what we've just derived.
7465        // note that apkRoot isn't stored in the package settings.
7466        if (pkgSetting != null) {
7467            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7468            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7469        }
7470    }
7471
7472    /**
7473     * Deduces the ABI of a bundled app and sets the relevant fields on the
7474     * parsed pkg object.
7475     *
7476     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7477     *        under which system libraries are installed.
7478     * @param apkName the name of the installed package.
7479     */
7480    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7481        final File codeFile = new File(pkg.codePath);
7482
7483        final boolean has64BitLibs;
7484        final boolean has32BitLibs;
7485        if (isApkFile(codeFile)) {
7486            // Monolithic install
7487            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7488            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7489        } else {
7490            // Cluster install
7491            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7492            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7493                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7494                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7495                has64BitLibs = (new File(rootDir, isa)).exists();
7496            } else {
7497                has64BitLibs = false;
7498            }
7499            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7500                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7501                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7502                has32BitLibs = (new File(rootDir, isa)).exists();
7503            } else {
7504                has32BitLibs = false;
7505            }
7506        }
7507
7508        if (has64BitLibs && !has32BitLibs) {
7509            // The package has 64 bit libs, but not 32 bit libs. Its primary
7510            // ABI should be 64 bit. We can safely assume here that the bundled
7511            // native libraries correspond to the most preferred ABI in the list.
7512
7513            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7514            pkg.applicationInfo.secondaryCpuAbi = null;
7515        } else if (has32BitLibs && !has64BitLibs) {
7516            // The package has 32 bit libs but not 64 bit libs. Its primary
7517            // ABI should be 32 bit.
7518
7519            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7520            pkg.applicationInfo.secondaryCpuAbi = null;
7521        } else if (has32BitLibs && has64BitLibs) {
7522            // The application has both 64 and 32 bit bundled libraries. We check
7523            // here that the app declares multiArch support, and warn if it doesn't.
7524            //
7525            // We will be lenient here and record both ABIs. The primary will be the
7526            // ABI that's higher on the list, i.e, a device that's configured to prefer
7527            // 64 bit apps will see a 64 bit primary ABI,
7528
7529            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7530                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7531            }
7532
7533            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7534                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7535                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7536            } else {
7537                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7538                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7539            }
7540        } else {
7541            pkg.applicationInfo.primaryCpuAbi = null;
7542            pkg.applicationInfo.secondaryCpuAbi = null;
7543        }
7544    }
7545
7546    private void killApplication(String pkgName, int appId, String reason) {
7547        // Request the ActivityManager to kill the process(only for existing packages)
7548        // so that we do not end up in a confused state while the user is still using the older
7549        // version of the application while the new one gets installed.
7550        IActivityManager am = ActivityManagerNative.getDefault();
7551        if (am != null) {
7552            try {
7553                am.killApplicationWithAppId(pkgName, appId, reason);
7554            } catch (RemoteException e) {
7555            }
7556        }
7557    }
7558
7559    void removePackageLI(PackageSetting ps, boolean chatty) {
7560        if (DEBUG_INSTALL) {
7561            if (chatty)
7562                Log.d(TAG, "Removing package " + ps.name);
7563        }
7564
7565        // writer
7566        synchronized (mPackages) {
7567            mPackages.remove(ps.name);
7568            final PackageParser.Package pkg = ps.pkg;
7569            if (pkg != null) {
7570                cleanPackageDataStructuresLILPw(pkg, chatty);
7571            }
7572        }
7573    }
7574
7575    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7576        if (DEBUG_INSTALL) {
7577            if (chatty)
7578                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7579        }
7580
7581        // writer
7582        synchronized (mPackages) {
7583            mPackages.remove(pkg.applicationInfo.packageName);
7584            cleanPackageDataStructuresLILPw(pkg, chatty);
7585        }
7586    }
7587
7588    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7589        int N = pkg.providers.size();
7590        StringBuilder r = null;
7591        int i;
7592        for (i=0; i<N; i++) {
7593            PackageParser.Provider p = pkg.providers.get(i);
7594            mProviders.removeProvider(p);
7595            if (p.info.authority == null) {
7596
7597                /* There was another ContentProvider with this authority when
7598                 * this app was installed so this authority is null,
7599                 * Ignore it as we don't have to unregister the provider.
7600                 */
7601                continue;
7602            }
7603            String names[] = p.info.authority.split(";");
7604            for (int j = 0; j < names.length; j++) {
7605                if (mProvidersByAuthority.get(names[j]) == p) {
7606                    mProvidersByAuthority.remove(names[j]);
7607                    if (DEBUG_REMOVE) {
7608                        if (chatty)
7609                            Log.d(TAG, "Unregistered content provider: " + names[j]
7610                                    + ", className = " + p.info.name + ", isSyncable = "
7611                                    + p.info.isSyncable);
7612                    }
7613                }
7614            }
7615            if (DEBUG_REMOVE && chatty) {
7616                if (r == null) {
7617                    r = new StringBuilder(256);
7618                } else {
7619                    r.append(' ');
7620                }
7621                r.append(p.info.name);
7622            }
7623        }
7624        if (r != null) {
7625            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7626        }
7627
7628        N = pkg.services.size();
7629        r = null;
7630        for (i=0; i<N; i++) {
7631            PackageParser.Service s = pkg.services.get(i);
7632            mServices.removeService(s);
7633            if (chatty) {
7634                if (r == null) {
7635                    r = new StringBuilder(256);
7636                } else {
7637                    r.append(' ');
7638                }
7639                r.append(s.info.name);
7640            }
7641        }
7642        if (r != null) {
7643            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7644        }
7645
7646        N = pkg.receivers.size();
7647        r = null;
7648        for (i=0; i<N; i++) {
7649            PackageParser.Activity a = pkg.receivers.get(i);
7650            mReceivers.removeActivity(a, "receiver");
7651            if (DEBUG_REMOVE && chatty) {
7652                if (r == null) {
7653                    r = new StringBuilder(256);
7654                } else {
7655                    r.append(' ');
7656                }
7657                r.append(a.info.name);
7658            }
7659        }
7660        if (r != null) {
7661            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7662        }
7663
7664        N = pkg.activities.size();
7665        r = null;
7666        for (i=0; i<N; i++) {
7667            PackageParser.Activity a = pkg.activities.get(i);
7668            mActivities.removeActivity(a, "activity");
7669            if (DEBUG_REMOVE && chatty) {
7670                if (r == null) {
7671                    r = new StringBuilder(256);
7672                } else {
7673                    r.append(' ');
7674                }
7675                r.append(a.info.name);
7676            }
7677        }
7678        if (r != null) {
7679            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7680        }
7681
7682        N = pkg.permissions.size();
7683        r = null;
7684        for (i=0; i<N; i++) {
7685            PackageParser.Permission p = pkg.permissions.get(i);
7686            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7687            if (bp == null) {
7688                bp = mSettings.mPermissionTrees.get(p.info.name);
7689            }
7690            if (bp != null && bp.perm == p) {
7691                bp.perm = null;
7692                if (DEBUG_REMOVE && chatty) {
7693                    if (r == null) {
7694                        r = new StringBuilder(256);
7695                    } else {
7696                        r.append(' ');
7697                    }
7698                    r.append(p.info.name);
7699                }
7700            }
7701            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7702                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7703                if (appOpPerms != null) {
7704                    appOpPerms.remove(pkg.packageName);
7705                }
7706            }
7707        }
7708        if (r != null) {
7709            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7710        }
7711
7712        N = pkg.requestedPermissions.size();
7713        r = null;
7714        for (i=0; i<N; i++) {
7715            String perm = pkg.requestedPermissions.get(i);
7716            BasePermission bp = mSettings.mPermissions.get(perm);
7717            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7718                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7719                if (appOpPerms != null) {
7720                    appOpPerms.remove(pkg.packageName);
7721                    if (appOpPerms.isEmpty()) {
7722                        mAppOpPermissionPackages.remove(perm);
7723                    }
7724                }
7725            }
7726        }
7727        if (r != null) {
7728            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7729        }
7730
7731        N = pkg.instrumentation.size();
7732        r = null;
7733        for (i=0; i<N; i++) {
7734            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7735            mInstrumentation.remove(a.getComponentName());
7736            if (DEBUG_REMOVE && chatty) {
7737                if (r == null) {
7738                    r = new StringBuilder(256);
7739                } else {
7740                    r.append(' ');
7741                }
7742                r.append(a.info.name);
7743            }
7744        }
7745        if (r != null) {
7746            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7747        }
7748
7749        r = null;
7750        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7751            // Only system apps can hold shared libraries.
7752            if (pkg.libraryNames != null) {
7753                for (i=0; i<pkg.libraryNames.size(); i++) {
7754                    String name = pkg.libraryNames.get(i);
7755                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7756                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7757                        mSharedLibraries.remove(name);
7758                        if (DEBUG_REMOVE && chatty) {
7759                            if (r == null) {
7760                                r = new StringBuilder(256);
7761                            } else {
7762                                r.append(' ');
7763                            }
7764                            r.append(name);
7765                        }
7766                    }
7767                }
7768            }
7769        }
7770        if (r != null) {
7771            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7772        }
7773    }
7774
7775    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7776        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7777            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7778                return true;
7779            }
7780        }
7781        return false;
7782    }
7783
7784    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7785    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7786    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7787
7788    private void updatePermissionsLPw(String changingPkg,
7789            PackageParser.Package pkgInfo, int flags) {
7790        // Make sure there are no dangling permission trees.
7791        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7792        while (it.hasNext()) {
7793            final BasePermission bp = it.next();
7794            if (bp.packageSetting == null) {
7795                // We may not yet have parsed the package, so just see if
7796                // we still know about its settings.
7797                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7798            }
7799            if (bp.packageSetting == null) {
7800                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7801                        + " from package " + bp.sourcePackage);
7802                it.remove();
7803            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7804                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7805                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7806                            + " from package " + bp.sourcePackage);
7807                    flags |= UPDATE_PERMISSIONS_ALL;
7808                    it.remove();
7809                }
7810            }
7811        }
7812
7813        // Make sure all dynamic permissions have been assigned to a package,
7814        // and make sure there are no dangling permissions.
7815        it = mSettings.mPermissions.values().iterator();
7816        while (it.hasNext()) {
7817            final BasePermission bp = it.next();
7818            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7819                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7820                        + bp.name + " pkg=" + bp.sourcePackage
7821                        + " info=" + bp.pendingInfo);
7822                if (bp.packageSetting == null && bp.pendingInfo != null) {
7823                    final BasePermission tree = findPermissionTreeLP(bp.name);
7824                    if (tree != null && tree.perm != null) {
7825                        bp.packageSetting = tree.packageSetting;
7826                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7827                                new PermissionInfo(bp.pendingInfo));
7828                        bp.perm.info.packageName = tree.perm.info.packageName;
7829                        bp.perm.info.name = bp.name;
7830                        bp.uid = tree.uid;
7831                    }
7832                }
7833            }
7834            if (bp.packageSetting == null) {
7835                // We may not yet have parsed the package, so just see if
7836                // we still know about its settings.
7837                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7838            }
7839            if (bp.packageSetting == null) {
7840                Slog.w(TAG, "Removing dangling permission: " + bp.name
7841                        + " from package " + bp.sourcePackage);
7842                it.remove();
7843            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7844                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7845                    Slog.i(TAG, "Removing old permission: " + bp.name
7846                            + " from package " + bp.sourcePackage);
7847                    flags |= UPDATE_PERMISSIONS_ALL;
7848                    it.remove();
7849                }
7850            }
7851        }
7852
7853        // Now update the permissions for all packages, in particular
7854        // replace the granted permissions of the system packages.
7855        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7856            for (PackageParser.Package pkg : mPackages.values()) {
7857                if (pkg != pkgInfo) {
7858                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7859                            changingPkg);
7860                }
7861            }
7862        }
7863
7864        if (pkgInfo != null) {
7865            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7866        }
7867    }
7868
7869    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7870            String packageOfInterest) {
7871        // IMPORTANT: There are two types of permissions: install and runtime.
7872        // Install time permissions are granted when the app is installed to
7873        // all device users and users added in the future. Runtime permissions
7874        // are granted at runtime explicitly to specific users. Normal and signature
7875        // protected permissions are install time permissions. Dangerous permissions
7876        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7877        // otherwise they are runtime permissions. This function does not manage
7878        // runtime permissions except for the case an app targeting Lollipop MR1
7879        // being upgraded to target a newer SDK, in which case dangerous permissions
7880        // are transformed from install time to runtime ones.
7881
7882        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7883        if (ps == null) {
7884            return;
7885        }
7886
7887        PermissionsState permissionsState = ps.getPermissionsState();
7888        PermissionsState origPermissions = permissionsState;
7889
7890        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7891
7892        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7893
7894        boolean changedInstallPermission = false;
7895
7896        if (replace) {
7897            ps.installPermissionsFixed = false;
7898            if (!ps.isSharedUser()) {
7899                origPermissions = new PermissionsState(permissionsState);
7900                permissionsState.reset();
7901            }
7902        }
7903
7904        permissionsState.setGlobalGids(mGlobalGids);
7905
7906        final int N = pkg.requestedPermissions.size();
7907        for (int i=0; i<N; i++) {
7908            final String name = pkg.requestedPermissions.get(i);
7909            final BasePermission bp = mSettings.mPermissions.get(name);
7910
7911            if (DEBUG_INSTALL) {
7912                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7913            }
7914
7915            if (bp == null || bp.packageSetting == null) {
7916                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7917                    Slog.w(TAG, "Unknown permission " + name
7918                            + " in package " + pkg.packageName);
7919                }
7920                continue;
7921            }
7922
7923            final String perm = bp.name;
7924            boolean allowedSig = false;
7925            int grant = GRANT_DENIED;
7926
7927            // Keep track of app op permissions.
7928            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7929                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7930                if (pkgs == null) {
7931                    pkgs = new ArraySet<>();
7932                    mAppOpPermissionPackages.put(bp.name, pkgs);
7933                }
7934                pkgs.add(pkg.packageName);
7935            }
7936
7937            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7938            switch (level) {
7939                case PermissionInfo.PROTECTION_NORMAL: {
7940                    // For all apps normal permissions are install time ones.
7941                    grant = GRANT_INSTALL;
7942                } break;
7943
7944                case PermissionInfo.PROTECTION_DANGEROUS: {
7945                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7946                        // For legacy apps dangerous permissions are install time ones.
7947                        grant = GRANT_INSTALL_LEGACY;
7948                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7949                        // For legacy apps that became modern, install becomes runtime.
7950                        grant = GRANT_UPGRADE;
7951                    } else {
7952                        // For modern apps keep runtime permissions unchanged.
7953                        grant = GRANT_RUNTIME;
7954                    }
7955                } break;
7956
7957                case PermissionInfo.PROTECTION_SIGNATURE: {
7958                    // For all apps signature permissions are install time ones.
7959                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7960                    if (allowedSig) {
7961                        grant = GRANT_INSTALL;
7962                    }
7963                } break;
7964            }
7965
7966            if (DEBUG_INSTALL) {
7967                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7968            }
7969
7970            if (grant != GRANT_DENIED) {
7971                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7972                    // If this is an existing, non-system package, then
7973                    // we can't add any new permissions to it.
7974                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7975                        // Except...  if this is a permission that was added
7976                        // to the platform (note: need to only do this when
7977                        // updating the platform).
7978                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7979                            grant = GRANT_DENIED;
7980                        }
7981                    }
7982                }
7983
7984                switch (grant) {
7985                    case GRANT_INSTALL: {
7986                        // Revoke this as runtime permission to handle the case of
7987                        // a runtime permission being downgraded to an install one.
7988                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7989                            if (origPermissions.getRuntimePermissionState(
7990                                    bp.name, userId) != null) {
7991                                // Revoke the runtime permission and clear the flags.
7992                                origPermissions.revokeRuntimePermission(bp, userId);
7993                                origPermissions.updatePermissionFlags(bp, userId,
7994                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
7995                                // If we revoked a permission permission, we have to write.
7996                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7997                                        changedRuntimePermissionUserIds, userId);
7998                            }
7999                        }
8000                        // Grant an install permission.
8001                        if (permissionsState.grantInstallPermission(bp) !=
8002                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8003                            changedInstallPermission = true;
8004                        }
8005                    } break;
8006
8007                    case GRANT_INSTALL_LEGACY: {
8008                        // Grant an install permission.
8009                        if (permissionsState.grantInstallPermission(bp) !=
8010                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8011                            changedInstallPermission = true;
8012                        }
8013                    } break;
8014
8015                    case GRANT_RUNTIME: {
8016                        // Grant previously granted runtime permissions.
8017                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8018                            PermissionState permissionState = origPermissions
8019                                    .getRuntimePermissionState(bp.name, userId);
8020                            final int flags = permissionState != null
8021                                    ? permissionState.getFlags() : 0;
8022                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8023                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8024                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8025                                    // If we cannot put the permission as it was, we have to write.
8026                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8027                                            changedRuntimePermissionUserIds, userId);
8028                                }
8029                            }
8030                            // Propagate the permission flags.
8031                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8032                        }
8033                    } break;
8034
8035                    case GRANT_UPGRADE: {
8036                        // Grant runtime permissions for a previously held install permission.
8037                        PermissionState permissionState = origPermissions
8038                                .getInstallPermissionState(bp.name);
8039                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8040
8041                        if (origPermissions.revokeInstallPermission(bp)
8042                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8043                            // We will be transferring the permission flags, so clear them.
8044                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8045                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8046                            changedInstallPermission = true;
8047                        }
8048
8049                        // If the permission is not to be promoted to runtime we ignore it and
8050                        // also its other flags as they are not applicable to install permissions.
8051                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8052                            for (int userId : currentUserIds) {
8053                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8054                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8055                                    // Transfer the permission flags.
8056                                    permissionsState.updatePermissionFlags(bp, userId,
8057                                            flags, flags);
8058                                    // If we granted the permission, we have to write.
8059                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8060                                            changedRuntimePermissionUserIds, userId);
8061                                }
8062                            }
8063                        }
8064                    } break;
8065
8066                    default: {
8067                        if (packageOfInterest == null
8068                                || packageOfInterest.equals(pkg.packageName)) {
8069                            Slog.w(TAG, "Not granting permission " + perm
8070                                    + " to package " + pkg.packageName
8071                                    + " because it was previously installed without");
8072                        }
8073                    } break;
8074                }
8075            } else {
8076                if (permissionsState.revokeInstallPermission(bp) !=
8077                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8078                    // Also drop the permission flags.
8079                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8080                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8081                    changedInstallPermission = true;
8082                    Slog.i(TAG, "Un-granting permission " + perm
8083                            + " from package " + pkg.packageName
8084                            + " (protectionLevel=" + bp.protectionLevel
8085                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8086                            + ")");
8087                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8088                    // Don't print warning for app op permissions, since it is fine for them
8089                    // not to be granted, there is a UI for the user to decide.
8090                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8091                        Slog.w(TAG, "Not granting permission " + perm
8092                                + " to package " + pkg.packageName
8093                                + " (protectionLevel=" + bp.protectionLevel
8094                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8095                                + ")");
8096                    }
8097                }
8098            }
8099        }
8100
8101        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8102                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8103            // This is the first that we have heard about this package, so the
8104            // permissions we have now selected are fixed until explicitly
8105            // changed.
8106            ps.installPermissionsFixed = true;
8107        }
8108
8109        // Persist the runtime permissions state for users with changes.
8110        for (int userId : changedRuntimePermissionUserIds) {
8111            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8112        }
8113    }
8114
8115    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8116        boolean allowed = false;
8117        final int NP = PackageParser.NEW_PERMISSIONS.length;
8118        for (int ip=0; ip<NP; ip++) {
8119            final PackageParser.NewPermissionInfo npi
8120                    = PackageParser.NEW_PERMISSIONS[ip];
8121            if (npi.name.equals(perm)
8122                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8123                allowed = true;
8124                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8125                        + pkg.packageName);
8126                break;
8127            }
8128        }
8129        return allowed;
8130    }
8131
8132    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8133            BasePermission bp, PermissionsState origPermissions) {
8134        boolean allowed;
8135        allowed = (compareSignatures(
8136                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8137                        == PackageManager.SIGNATURE_MATCH)
8138                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8139                        == PackageManager.SIGNATURE_MATCH);
8140        if (!allowed && (bp.protectionLevel
8141                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8142            if (isSystemApp(pkg)) {
8143                // For updated system applications, a system permission
8144                // is granted only if it had been defined by the original application.
8145                if (pkg.isUpdatedSystemApp()) {
8146                    final PackageSetting sysPs = mSettings
8147                            .getDisabledSystemPkgLPr(pkg.packageName);
8148                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8149                        // If the original was granted this permission, we take
8150                        // that grant decision as read and propagate it to the
8151                        // update.
8152                        if (sysPs.isPrivileged()) {
8153                            allowed = true;
8154                        }
8155                    } else {
8156                        // The system apk may have been updated with an older
8157                        // version of the one on the data partition, but which
8158                        // granted a new system permission that it didn't have
8159                        // before.  In this case we do want to allow the app to
8160                        // now get the new permission if the ancestral apk is
8161                        // privileged to get it.
8162                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8163                            for (int j=0;
8164                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8165                                if (perm.equals(
8166                                        sysPs.pkg.requestedPermissions.get(j))) {
8167                                    allowed = true;
8168                                    break;
8169                                }
8170                            }
8171                        }
8172                    }
8173                } else {
8174                    allowed = isPrivilegedApp(pkg);
8175                }
8176            }
8177        }
8178        if (!allowed && (bp.protectionLevel
8179                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8180            // For development permissions, a development permission
8181            // is granted only if it was already granted.
8182            allowed = origPermissions.hasInstallPermission(perm);
8183        }
8184        return allowed;
8185    }
8186
8187    final class ActivityIntentResolver
8188            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8189        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8190                boolean defaultOnly, int userId) {
8191            if (!sUserManager.exists(userId)) return null;
8192            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8193            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8194        }
8195
8196        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8197                int userId) {
8198            if (!sUserManager.exists(userId)) return null;
8199            mFlags = flags;
8200            return super.queryIntent(intent, resolvedType,
8201                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8202        }
8203
8204        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8205                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8206            if (!sUserManager.exists(userId)) return null;
8207            if (packageActivities == null) {
8208                return null;
8209            }
8210            mFlags = flags;
8211            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8212            final int N = packageActivities.size();
8213            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8214                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8215
8216            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8217            for (int i = 0; i < N; ++i) {
8218                intentFilters = packageActivities.get(i).intents;
8219                if (intentFilters != null && intentFilters.size() > 0) {
8220                    PackageParser.ActivityIntentInfo[] array =
8221                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8222                    intentFilters.toArray(array);
8223                    listCut.add(array);
8224                }
8225            }
8226            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8227        }
8228
8229        public final void addActivity(PackageParser.Activity a, String type) {
8230            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8231            mActivities.put(a.getComponentName(), a);
8232            if (DEBUG_SHOW_INFO)
8233                Log.v(
8234                TAG, "  " + type + " " +
8235                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8236            if (DEBUG_SHOW_INFO)
8237                Log.v(TAG, "    Class=" + a.info.name);
8238            final int NI = a.intents.size();
8239            for (int j=0; j<NI; j++) {
8240                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8241                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8242                    intent.setPriority(0);
8243                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8244                            + a.className + " with priority > 0, forcing to 0");
8245                }
8246                if (DEBUG_SHOW_INFO) {
8247                    Log.v(TAG, "    IntentFilter:");
8248                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8249                }
8250                if (!intent.debugCheck()) {
8251                    Log.w(TAG, "==> For Activity " + a.info.name);
8252                }
8253                addFilter(intent);
8254            }
8255        }
8256
8257        public final void removeActivity(PackageParser.Activity a, String type) {
8258            mActivities.remove(a.getComponentName());
8259            if (DEBUG_SHOW_INFO) {
8260                Log.v(TAG, "  " + type + " "
8261                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8262                                : a.info.name) + ":");
8263                Log.v(TAG, "    Class=" + a.info.name);
8264            }
8265            final int NI = a.intents.size();
8266            for (int j=0; j<NI; j++) {
8267                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8268                if (DEBUG_SHOW_INFO) {
8269                    Log.v(TAG, "    IntentFilter:");
8270                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8271                }
8272                removeFilter(intent);
8273            }
8274        }
8275
8276        @Override
8277        protected boolean allowFilterResult(
8278                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8279            ActivityInfo filterAi = filter.activity.info;
8280            for (int i=dest.size()-1; i>=0; i--) {
8281                ActivityInfo destAi = dest.get(i).activityInfo;
8282                if (destAi.name == filterAi.name
8283                        && destAi.packageName == filterAi.packageName) {
8284                    return false;
8285                }
8286            }
8287            return true;
8288        }
8289
8290        @Override
8291        protected ActivityIntentInfo[] newArray(int size) {
8292            return new ActivityIntentInfo[size];
8293        }
8294
8295        @Override
8296        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8297            if (!sUserManager.exists(userId)) return true;
8298            PackageParser.Package p = filter.activity.owner;
8299            if (p != null) {
8300                PackageSetting ps = (PackageSetting)p.mExtras;
8301                if (ps != null) {
8302                    // System apps are never considered stopped for purposes of
8303                    // filtering, because there may be no way for the user to
8304                    // actually re-launch them.
8305                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8306                            && ps.getStopped(userId);
8307                }
8308            }
8309            return false;
8310        }
8311
8312        @Override
8313        protected boolean isPackageForFilter(String packageName,
8314                PackageParser.ActivityIntentInfo info) {
8315            return packageName.equals(info.activity.owner.packageName);
8316        }
8317
8318        @Override
8319        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8320                int match, int userId) {
8321            if (!sUserManager.exists(userId)) return null;
8322            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8323                return null;
8324            }
8325            final PackageParser.Activity activity = info.activity;
8326            if (mSafeMode && (activity.info.applicationInfo.flags
8327                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8328                return null;
8329            }
8330            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8331            if (ps == null) {
8332                return null;
8333            }
8334            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8335                    ps.readUserState(userId), userId);
8336            if (ai == null) {
8337                return null;
8338            }
8339            final ResolveInfo res = new ResolveInfo();
8340            res.activityInfo = ai;
8341            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8342                res.filter = info;
8343            }
8344            if (info != null) {
8345                res.handleAllWebDataURI = info.handleAllWebDataURI();
8346            }
8347            res.priority = info.getPriority();
8348            res.preferredOrder = activity.owner.mPreferredOrder;
8349            //System.out.println("Result: " + res.activityInfo.className +
8350            //                   " = " + res.priority);
8351            res.match = match;
8352            res.isDefault = info.hasDefault;
8353            res.labelRes = info.labelRes;
8354            res.nonLocalizedLabel = info.nonLocalizedLabel;
8355            if (userNeedsBadging(userId)) {
8356                res.noResourceId = true;
8357            } else {
8358                res.icon = info.icon;
8359            }
8360            res.iconResourceId = info.icon;
8361            res.system = res.activityInfo.applicationInfo.isSystemApp();
8362            return res;
8363        }
8364
8365        @Override
8366        protected void sortResults(List<ResolveInfo> results) {
8367            Collections.sort(results, mResolvePrioritySorter);
8368        }
8369
8370        @Override
8371        protected void dumpFilter(PrintWriter out, String prefix,
8372                PackageParser.ActivityIntentInfo filter) {
8373            out.print(prefix); out.print(
8374                    Integer.toHexString(System.identityHashCode(filter.activity)));
8375                    out.print(' ');
8376                    filter.activity.printComponentShortName(out);
8377                    out.print(" filter ");
8378                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8379        }
8380
8381        @Override
8382        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8383            return filter.activity;
8384        }
8385
8386        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8387            PackageParser.Activity activity = (PackageParser.Activity)label;
8388            out.print(prefix); out.print(
8389                    Integer.toHexString(System.identityHashCode(activity)));
8390                    out.print(' ');
8391                    activity.printComponentShortName(out);
8392            if (count > 1) {
8393                out.print(" ("); out.print(count); out.print(" filters)");
8394            }
8395            out.println();
8396        }
8397
8398//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8399//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8400//            final List<ResolveInfo> retList = Lists.newArrayList();
8401//            while (i.hasNext()) {
8402//                final ResolveInfo resolveInfo = i.next();
8403//                if (isEnabledLP(resolveInfo.activityInfo)) {
8404//                    retList.add(resolveInfo);
8405//                }
8406//            }
8407//            return retList;
8408//        }
8409
8410        // Keys are String (activity class name), values are Activity.
8411        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8412                = new ArrayMap<ComponentName, PackageParser.Activity>();
8413        private int mFlags;
8414    }
8415
8416    private final class ServiceIntentResolver
8417            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8418        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8419                boolean defaultOnly, int userId) {
8420            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8421            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8422        }
8423
8424        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8425                int userId) {
8426            if (!sUserManager.exists(userId)) return null;
8427            mFlags = flags;
8428            return super.queryIntent(intent, resolvedType,
8429                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8430        }
8431
8432        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8433                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8434            if (!sUserManager.exists(userId)) return null;
8435            if (packageServices == null) {
8436                return null;
8437            }
8438            mFlags = flags;
8439            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8440            final int N = packageServices.size();
8441            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8442                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8443
8444            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8445            for (int i = 0; i < N; ++i) {
8446                intentFilters = packageServices.get(i).intents;
8447                if (intentFilters != null && intentFilters.size() > 0) {
8448                    PackageParser.ServiceIntentInfo[] array =
8449                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8450                    intentFilters.toArray(array);
8451                    listCut.add(array);
8452                }
8453            }
8454            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8455        }
8456
8457        public final void addService(PackageParser.Service s) {
8458            mServices.put(s.getComponentName(), s);
8459            if (DEBUG_SHOW_INFO) {
8460                Log.v(TAG, "  "
8461                        + (s.info.nonLocalizedLabel != null
8462                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8463                Log.v(TAG, "    Class=" + s.info.name);
8464            }
8465            final int NI = s.intents.size();
8466            int j;
8467            for (j=0; j<NI; j++) {
8468                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8469                if (DEBUG_SHOW_INFO) {
8470                    Log.v(TAG, "    IntentFilter:");
8471                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8472                }
8473                if (!intent.debugCheck()) {
8474                    Log.w(TAG, "==> For Service " + s.info.name);
8475                }
8476                addFilter(intent);
8477            }
8478        }
8479
8480        public final void removeService(PackageParser.Service s) {
8481            mServices.remove(s.getComponentName());
8482            if (DEBUG_SHOW_INFO) {
8483                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8484                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8485                Log.v(TAG, "    Class=" + s.info.name);
8486            }
8487            final int NI = s.intents.size();
8488            int j;
8489            for (j=0; j<NI; j++) {
8490                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8491                if (DEBUG_SHOW_INFO) {
8492                    Log.v(TAG, "    IntentFilter:");
8493                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8494                }
8495                removeFilter(intent);
8496            }
8497        }
8498
8499        @Override
8500        protected boolean allowFilterResult(
8501                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8502            ServiceInfo filterSi = filter.service.info;
8503            for (int i=dest.size()-1; i>=0; i--) {
8504                ServiceInfo destAi = dest.get(i).serviceInfo;
8505                if (destAi.name == filterSi.name
8506                        && destAi.packageName == filterSi.packageName) {
8507                    return false;
8508                }
8509            }
8510            return true;
8511        }
8512
8513        @Override
8514        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8515            return new PackageParser.ServiceIntentInfo[size];
8516        }
8517
8518        @Override
8519        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8520            if (!sUserManager.exists(userId)) return true;
8521            PackageParser.Package p = filter.service.owner;
8522            if (p != null) {
8523                PackageSetting ps = (PackageSetting)p.mExtras;
8524                if (ps != null) {
8525                    // System apps are never considered stopped for purposes of
8526                    // filtering, because there may be no way for the user to
8527                    // actually re-launch them.
8528                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8529                            && ps.getStopped(userId);
8530                }
8531            }
8532            return false;
8533        }
8534
8535        @Override
8536        protected boolean isPackageForFilter(String packageName,
8537                PackageParser.ServiceIntentInfo info) {
8538            return packageName.equals(info.service.owner.packageName);
8539        }
8540
8541        @Override
8542        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8543                int match, int userId) {
8544            if (!sUserManager.exists(userId)) return null;
8545            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8546            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8547                return null;
8548            }
8549            final PackageParser.Service service = info.service;
8550            if (mSafeMode && (service.info.applicationInfo.flags
8551                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8552                return null;
8553            }
8554            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8555            if (ps == null) {
8556                return null;
8557            }
8558            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8559                    ps.readUserState(userId), userId);
8560            if (si == null) {
8561                return null;
8562            }
8563            final ResolveInfo res = new ResolveInfo();
8564            res.serviceInfo = si;
8565            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8566                res.filter = filter;
8567            }
8568            res.priority = info.getPriority();
8569            res.preferredOrder = service.owner.mPreferredOrder;
8570            res.match = match;
8571            res.isDefault = info.hasDefault;
8572            res.labelRes = info.labelRes;
8573            res.nonLocalizedLabel = info.nonLocalizedLabel;
8574            res.icon = info.icon;
8575            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8576            return res;
8577        }
8578
8579        @Override
8580        protected void sortResults(List<ResolveInfo> results) {
8581            Collections.sort(results, mResolvePrioritySorter);
8582        }
8583
8584        @Override
8585        protected void dumpFilter(PrintWriter out, String prefix,
8586                PackageParser.ServiceIntentInfo filter) {
8587            out.print(prefix); out.print(
8588                    Integer.toHexString(System.identityHashCode(filter.service)));
8589                    out.print(' ');
8590                    filter.service.printComponentShortName(out);
8591                    out.print(" filter ");
8592                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8593        }
8594
8595        @Override
8596        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8597            return filter.service;
8598        }
8599
8600        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8601            PackageParser.Service service = (PackageParser.Service)label;
8602            out.print(prefix); out.print(
8603                    Integer.toHexString(System.identityHashCode(service)));
8604                    out.print(' ');
8605                    service.printComponentShortName(out);
8606            if (count > 1) {
8607                out.print(" ("); out.print(count); out.print(" filters)");
8608            }
8609            out.println();
8610        }
8611
8612//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8613//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8614//            final List<ResolveInfo> retList = Lists.newArrayList();
8615//            while (i.hasNext()) {
8616//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8617//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8618//                    retList.add(resolveInfo);
8619//                }
8620//            }
8621//            return retList;
8622//        }
8623
8624        // Keys are String (activity class name), values are Activity.
8625        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8626                = new ArrayMap<ComponentName, PackageParser.Service>();
8627        private int mFlags;
8628    };
8629
8630    private final class ProviderIntentResolver
8631            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8632        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8633                boolean defaultOnly, int userId) {
8634            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8635            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8636        }
8637
8638        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8639                int userId) {
8640            if (!sUserManager.exists(userId))
8641                return null;
8642            mFlags = flags;
8643            return super.queryIntent(intent, resolvedType,
8644                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8645        }
8646
8647        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8648                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8649            if (!sUserManager.exists(userId))
8650                return null;
8651            if (packageProviders == null) {
8652                return null;
8653            }
8654            mFlags = flags;
8655            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8656            final int N = packageProviders.size();
8657            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8658                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8659
8660            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8661            for (int i = 0; i < N; ++i) {
8662                intentFilters = packageProviders.get(i).intents;
8663                if (intentFilters != null && intentFilters.size() > 0) {
8664                    PackageParser.ProviderIntentInfo[] array =
8665                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8666                    intentFilters.toArray(array);
8667                    listCut.add(array);
8668                }
8669            }
8670            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8671        }
8672
8673        public final void addProvider(PackageParser.Provider p) {
8674            if (mProviders.containsKey(p.getComponentName())) {
8675                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8676                return;
8677            }
8678
8679            mProviders.put(p.getComponentName(), p);
8680            if (DEBUG_SHOW_INFO) {
8681                Log.v(TAG, "  "
8682                        + (p.info.nonLocalizedLabel != null
8683                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8684                Log.v(TAG, "    Class=" + p.info.name);
8685            }
8686            final int NI = p.intents.size();
8687            int j;
8688            for (j = 0; j < NI; j++) {
8689                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8690                if (DEBUG_SHOW_INFO) {
8691                    Log.v(TAG, "    IntentFilter:");
8692                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8693                }
8694                if (!intent.debugCheck()) {
8695                    Log.w(TAG, "==> For Provider " + p.info.name);
8696                }
8697                addFilter(intent);
8698            }
8699        }
8700
8701        public final void removeProvider(PackageParser.Provider p) {
8702            mProviders.remove(p.getComponentName());
8703            if (DEBUG_SHOW_INFO) {
8704                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8705                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8706                Log.v(TAG, "    Class=" + p.info.name);
8707            }
8708            final int NI = p.intents.size();
8709            int j;
8710            for (j = 0; j < NI; j++) {
8711                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8712                if (DEBUG_SHOW_INFO) {
8713                    Log.v(TAG, "    IntentFilter:");
8714                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8715                }
8716                removeFilter(intent);
8717            }
8718        }
8719
8720        @Override
8721        protected boolean allowFilterResult(
8722                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8723            ProviderInfo filterPi = filter.provider.info;
8724            for (int i = dest.size() - 1; i >= 0; i--) {
8725                ProviderInfo destPi = dest.get(i).providerInfo;
8726                if (destPi.name == filterPi.name
8727                        && destPi.packageName == filterPi.packageName) {
8728                    return false;
8729                }
8730            }
8731            return true;
8732        }
8733
8734        @Override
8735        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8736            return new PackageParser.ProviderIntentInfo[size];
8737        }
8738
8739        @Override
8740        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8741            if (!sUserManager.exists(userId))
8742                return true;
8743            PackageParser.Package p = filter.provider.owner;
8744            if (p != null) {
8745                PackageSetting ps = (PackageSetting) p.mExtras;
8746                if (ps != null) {
8747                    // System apps are never considered stopped for purposes of
8748                    // filtering, because there may be no way for the user to
8749                    // actually re-launch them.
8750                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8751                            && ps.getStopped(userId);
8752                }
8753            }
8754            return false;
8755        }
8756
8757        @Override
8758        protected boolean isPackageForFilter(String packageName,
8759                PackageParser.ProviderIntentInfo info) {
8760            return packageName.equals(info.provider.owner.packageName);
8761        }
8762
8763        @Override
8764        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8765                int match, int userId) {
8766            if (!sUserManager.exists(userId))
8767                return null;
8768            final PackageParser.ProviderIntentInfo info = filter;
8769            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8770                return null;
8771            }
8772            final PackageParser.Provider provider = info.provider;
8773            if (mSafeMode && (provider.info.applicationInfo.flags
8774                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8775                return null;
8776            }
8777            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8778            if (ps == null) {
8779                return null;
8780            }
8781            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8782                    ps.readUserState(userId), userId);
8783            if (pi == null) {
8784                return null;
8785            }
8786            final ResolveInfo res = new ResolveInfo();
8787            res.providerInfo = pi;
8788            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8789                res.filter = filter;
8790            }
8791            res.priority = info.getPriority();
8792            res.preferredOrder = provider.owner.mPreferredOrder;
8793            res.match = match;
8794            res.isDefault = info.hasDefault;
8795            res.labelRes = info.labelRes;
8796            res.nonLocalizedLabel = info.nonLocalizedLabel;
8797            res.icon = info.icon;
8798            res.system = res.providerInfo.applicationInfo.isSystemApp();
8799            return res;
8800        }
8801
8802        @Override
8803        protected void sortResults(List<ResolveInfo> results) {
8804            Collections.sort(results, mResolvePrioritySorter);
8805        }
8806
8807        @Override
8808        protected void dumpFilter(PrintWriter out, String prefix,
8809                PackageParser.ProviderIntentInfo filter) {
8810            out.print(prefix);
8811            out.print(
8812                    Integer.toHexString(System.identityHashCode(filter.provider)));
8813            out.print(' ');
8814            filter.provider.printComponentShortName(out);
8815            out.print(" filter ");
8816            out.println(Integer.toHexString(System.identityHashCode(filter)));
8817        }
8818
8819        @Override
8820        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8821            return filter.provider;
8822        }
8823
8824        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8825            PackageParser.Provider provider = (PackageParser.Provider)label;
8826            out.print(prefix); out.print(
8827                    Integer.toHexString(System.identityHashCode(provider)));
8828                    out.print(' ');
8829                    provider.printComponentShortName(out);
8830            if (count > 1) {
8831                out.print(" ("); out.print(count); out.print(" filters)");
8832            }
8833            out.println();
8834        }
8835
8836        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8837                = new ArrayMap<ComponentName, PackageParser.Provider>();
8838        private int mFlags;
8839    };
8840
8841    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8842            new Comparator<ResolveInfo>() {
8843        public int compare(ResolveInfo r1, ResolveInfo r2) {
8844            int v1 = r1.priority;
8845            int v2 = r2.priority;
8846            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8847            if (v1 != v2) {
8848                return (v1 > v2) ? -1 : 1;
8849            }
8850            v1 = r1.preferredOrder;
8851            v2 = r2.preferredOrder;
8852            if (v1 != v2) {
8853                return (v1 > v2) ? -1 : 1;
8854            }
8855            if (r1.isDefault != r2.isDefault) {
8856                return r1.isDefault ? -1 : 1;
8857            }
8858            v1 = r1.match;
8859            v2 = r2.match;
8860            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8861            if (v1 != v2) {
8862                return (v1 > v2) ? -1 : 1;
8863            }
8864            if (r1.system != r2.system) {
8865                return r1.system ? -1 : 1;
8866            }
8867            return 0;
8868        }
8869    };
8870
8871    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8872            new Comparator<ProviderInfo>() {
8873        public int compare(ProviderInfo p1, ProviderInfo p2) {
8874            final int v1 = p1.initOrder;
8875            final int v2 = p2.initOrder;
8876            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8877        }
8878    };
8879
8880    final void sendPackageBroadcast(final String action, final String pkg,
8881            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8882            final int[] userIds) {
8883        mHandler.post(new Runnable() {
8884            @Override
8885            public void run() {
8886                try {
8887                    final IActivityManager am = ActivityManagerNative.getDefault();
8888                    if (am == null) return;
8889                    final int[] resolvedUserIds;
8890                    if (userIds == null) {
8891                        resolvedUserIds = am.getRunningUserIds();
8892                    } else {
8893                        resolvedUserIds = userIds;
8894                    }
8895                    for (int id : resolvedUserIds) {
8896                        final Intent intent = new Intent(action,
8897                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8898                        if (extras != null) {
8899                            intent.putExtras(extras);
8900                        }
8901                        if (targetPkg != null) {
8902                            intent.setPackage(targetPkg);
8903                        }
8904                        // Modify the UID when posting to other users
8905                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8906                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8907                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8908                            intent.putExtra(Intent.EXTRA_UID, uid);
8909                        }
8910                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8911                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8912                        if (DEBUG_BROADCASTS) {
8913                            RuntimeException here = new RuntimeException("here");
8914                            here.fillInStackTrace();
8915                            Slog.d(TAG, "Sending to user " + id + ": "
8916                                    + intent.toShortString(false, true, false, false)
8917                                    + " " + intent.getExtras(), here);
8918                        }
8919                        am.broadcastIntent(null, intent, null, finishedReceiver,
8920                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8921                                null, finishedReceiver != null, false, id);
8922                    }
8923                } catch (RemoteException ex) {
8924                }
8925            }
8926        });
8927    }
8928
8929    /**
8930     * Check if the external storage media is available. This is true if there
8931     * is a mounted external storage medium or if the external storage is
8932     * emulated.
8933     */
8934    private boolean isExternalMediaAvailable() {
8935        return mMediaMounted || Environment.isExternalStorageEmulated();
8936    }
8937
8938    @Override
8939    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8940        // writer
8941        synchronized (mPackages) {
8942            if (!isExternalMediaAvailable()) {
8943                // If the external storage is no longer mounted at this point,
8944                // the caller may not have been able to delete all of this
8945                // packages files and can not delete any more.  Bail.
8946                return null;
8947            }
8948            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8949            if (lastPackage != null) {
8950                pkgs.remove(lastPackage);
8951            }
8952            if (pkgs.size() > 0) {
8953                return pkgs.get(0);
8954            }
8955        }
8956        return null;
8957    }
8958
8959    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8960        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8961                userId, andCode ? 1 : 0, packageName);
8962        if (mSystemReady) {
8963            msg.sendToTarget();
8964        } else {
8965            if (mPostSystemReadyMessages == null) {
8966                mPostSystemReadyMessages = new ArrayList<>();
8967            }
8968            mPostSystemReadyMessages.add(msg);
8969        }
8970    }
8971
8972    void startCleaningPackages() {
8973        // reader
8974        synchronized (mPackages) {
8975            if (!isExternalMediaAvailable()) {
8976                return;
8977            }
8978            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8979                return;
8980            }
8981        }
8982        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8983        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8984        IActivityManager am = ActivityManagerNative.getDefault();
8985        if (am != null) {
8986            try {
8987                am.startService(null, intent, null, UserHandle.USER_OWNER);
8988            } catch (RemoteException e) {
8989            }
8990        }
8991    }
8992
8993    @Override
8994    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8995            int installFlags, String installerPackageName, VerificationParams verificationParams,
8996            String packageAbiOverride) {
8997        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8998                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8999    }
9000
9001    @Override
9002    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9003            int installFlags, String installerPackageName, VerificationParams verificationParams,
9004            String packageAbiOverride, int userId) {
9005        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9006
9007        final int callingUid = Binder.getCallingUid();
9008        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9009
9010        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9011            try {
9012                if (observer != null) {
9013                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9014                }
9015            } catch (RemoteException re) {
9016            }
9017            return;
9018        }
9019
9020        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9021            installFlags |= PackageManager.INSTALL_FROM_ADB;
9022
9023        } else {
9024            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9025            // about installerPackageName.
9026
9027            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9028            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9029        }
9030
9031        UserHandle user;
9032        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9033            user = UserHandle.ALL;
9034        } else {
9035            user = new UserHandle(userId);
9036        }
9037
9038        // Only system components can circumvent runtime permissions when installing.
9039        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9040                && mContext.checkCallingOrSelfPermission(Manifest.permission
9041                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9042            throw new SecurityException("You need the "
9043                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9044                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9045        }
9046
9047        verificationParams.setInstallerUid(callingUid);
9048
9049        final File originFile = new File(originPath);
9050        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9051
9052        final Message msg = mHandler.obtainMessage(INIT_COPY);
9053        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9054                null, verificationParams, user, packageAbiOverride);
9055        mHandler.sendMessage(msg);
9056    }
9057
9058    void installStage(String packageName, File stagedDir, String stagedCid,
9059            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9060            String installerPackageName, int installerUid, UserHandle user) {
9061        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9062                params.referrerUri, installerUid, null);
9063
9064        final OriginInfo origin;
9065        if (stagedDir != null) {
9066            origin = OriginInfo.fromStagedFile(stagedDir);
9067        } else {
9068            origin = OriginInfo.fromStagedContainer(stagedCid);
9069        }
9070
9071        final Message msg = mHandler.obtainMessage(INIT_COPY);
9072        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9073                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9074        mHandler.sendMessage(msg);
9075    }
9076
9077    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9078        Bundle extras = new Bundle(1);
9079        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9080
9081        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9082                packageName, extras, null, null, new int[] {userId});
9083        try {
9084            IActivityManager am = ActivityManagerNative.getDefault();
9085            final boolean isSystem =
9086                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9087            if (isSystem && am.isUserRunning(userId, false)) {
9088                // The just-installed/enabled app is bundled on the system, so presumed
9089                // to be able to run automatically without needing an explicit launch.
9090                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9091                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9092                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9093                        .setPackage(packageName);
9094                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9095                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9096            }
9097        } catch (RemoteException e) {
9098            // shouldn't happen
9099            Slog.w(TAG, "Unable to bootstrap installed package", e);
9100        }
9101    }
9102
9103    @Override
9104    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9105            int userId) {
9106        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9107        PackageSetting pkgSetting;
9108        final int uid = Binder.getCallingUid();
9109        enforceCrossUserPermission(uid, userId, true, true,
9110                "setApplicationHiddenSetting for user " + userId);
9111
9112        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9113            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9114            return false;
9115        }
9116
9117        long callingId = Binder.clearCallingIdentity();
9118        try {
9119            boolean sendAdded = false;
9120            boolean sendRemoved = false;
9121            // writer
9122            synchronized (mPackages) {
9123                pkgSetting = mSettings.mPackages.get(packageName);
9124                if (pkgSetting == null) {
9125                    return false;
9126                }
9127                if (pkgSetting.getHidden(userId) != hidden) {
9128                    pkgSetting.setHidden(hidden, userId);
9129                    mSettings.writePackageRestrictionsLPr(userId);
9130                    if (hidden) {
9131                        sendRemoved = true;
9132                    } else {
9133                        sendAdded = true;
9134                    }
9135                }
9136            }
9137            if (sendAdded) {
9138                sendPackageAddedForUser(packageName, pkgSetting, userId);
9139                return true;
9140            }
9141            if (sendRemoved) {
9142                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9143                        "hiding pkg");
9144                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9145            }
9146        } finally {
9147            Binder.restoreCallingIdentity(callingId);
9148        }
9149        return false;
9150    }
9151
9152    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9153            int userId) {
9154        final PackageRemovedInfo info = new PackageRemovedInfo();
9155        info.removedPackage = packageName;
9156        info.removedUsers = new int[] {userId};
9157        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9158        info.sendBroadcast(false, false, false);
9159    }
9160
9161    /**
9162     * Returns true if application is not found or there was an error. Otherwise it returns
9163     * the hidden state of the package for the given user.
9164     */
9165    @Override
9166    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9167        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9168        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9169                false, "getApplicationHidden for user " + userId);
9170        PackageSetting pkgSetting;
9171        long callingId = Binder.clearCallingIdentity();
9172        try {
9173            // writer
9174            synchronized (mPackages) {
9175                pkgSetting = mSettings.mPackages.get(packageName);
9176                if (pkgSetting == null) {
9177                    return true;
9178                }
9179                return pkgSetting.getHidden(userId);
9180            }
9181        } finally {
9182            Binder.restoreCallingIdentity(callingId);
9183        }
9184    }
9185
9186    /**
9187     * @hide
9188     */
9189    @Override
9190    public int installExistingPackageAsUser(String packageName, int userId) {
9191        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9192                null);
9193        PackageSetting pkgSetting;
9194        final int uid = Binder.getCallingUid();
9195        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9196                + userId);
9197        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9198            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9199        }
9200
9201        long callingId = Binder.clearCallingIdentity();
9202        try {
9203            boolean sendAdded = false;
9204
9205            // writer
9206            synchronized (mPackages) {
9207                pkgSetting = mSettings.mPackages.get(packageName);
9208                if (pkgSetting == null) {
9209                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9210                }
9211                if (!pkgSetting.getInstalled(userId)) {
9212                    pkgSetting.setInstalled(true, userId);
9213                    pkgSetting.setHidden(false, userId);
9214                    mSettings.writePackageRestrictionsLPr(userId);
9215                    sendAdded = true;
9216                }
9217            }
9218
9219            if (sendAdded) {
9220                sendPackageAddedForUser(packageName, pkgSetting, userId);
9221            }
9222        } finally {
9223            Binder.restoreCallingIdentity(callingId);
9224        }
9225
9226        return PackageManager.INSTALL_SUCCEEDED;
9227    }
9228
9229    boolean isUserRestricted(int userId, String restrictionKey) {
9230        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9231        if (restrictions.getBoolean(restrictionKey, false)) {
9232            Log.w(TAG, "User is restricted: " + restrictionKey);
9233            return true;
9234        }
9235        return false;
9236    }
9237
9238    @Override
9239    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9240        mContext.enforceCallingOrSelfPermission(
9241                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9242                "Only package verification agents can verify applications");
9243
9244        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9245        final PackageVerificationResponse response = new PackageVerificationResponse(
9246                verificationCode, Binder.getCallingUid());
9247        msg.arg1 = id;
9248        msg.obj = response;
9249        mHandler.sendMessage(msg);
9250    }
9251
9252    @Override
9253    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9254            long millisecondsToDelay) {
9255        mContext.enforceCallingOrSelfPermission(
9256                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9257                "Only package verification agents can extend verification timeouts");
9258
9259        final PackageVerificationState state = mPendingVerification.get(id);
9260        final PackageVerificationResponse response = new PackageVerificationResponse(
9261                verificationCodeAtTimeout, Binder.getCallingUid());
9262
9263        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9264            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9265        }
9266        if (millisecondsToDelay < 0) {
9267            millisecondsToDelay = 0;
9268        }
9269        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9270                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9271            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9272        }
9273
9274        if ((state != null) && !state.timeoutExtended()) {
9275            state.extendTimeout();
9276
9277            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9278            msg.arg1 = id;
9279            msg.obj = response;
9280            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9281        }
9282    }
9283
9284    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9285            int verificationCode, UserHandle user) {
9286        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9287        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9288        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9289        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9290        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9291
9292        mContext.sendBroadcastAsUser(intent, user,
9293                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9294    }
9295
9296    private ComponentName matchComponentForVerifier(String packageName,
9297            List<ResolveInfo> receivers) {
9298        ActivityInfo targetReceiver = null;
9299
9300        final int NR = receivers.size();
9301        for (int i = 0; i < NR; i++) {
9302            final ResolveInfo info = receivers.get(i);
9303            if (info.activityInfo == null) {
9304                continue;
9305            }
9306
9307            if (packageName.equals(info.activityInfo.packageName)) {
9308                targetReceiver = info.activityInfo;
9309                break;
9310            }
9311        }
9312
9313        if (targetReceiver == null) {
9314            return null;
9315        }
9316
9317        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9318    }
9319
9320    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9321            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9322        if (pkgInfo.verifiers.length == 0) {
9323            return null;
9324        }
9325
9326        final int N = pkgInfo.verifiers.length;
9327        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9328        for (int i = 0; i < N; i++) {
9329            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9330
9331            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9332                    receivers);
9333            if (comp == null) {
9334                continue;
9335            }
9336
9337            final int verifierUid = getUidForVerifier(verifierInfo);
9338            if (verifierUid == -1) {
9339                continue;
9340            }
9341
9342            if (DEBUG_VERIFY) {
9343                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9344                        + " with the correct signature");
9345            }
9346            sufficientVerifiers.add(comp);
9347            verificationState.addSufficientVerifier(verifierUid);
9348        }
9349
9350        return sufficientVerifiers;
9351    }
9352
9353    private int getUidForVerifier(VerifierInfo verifierInfo) {
9354        synchronized (mPackages) {
9355            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9356            if (pkg == null) {
9357                return -1;
9358            } else if (pkg.mSignatures.length != 1) {
9359                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9360                        + " has more than one signature; ignoring");
9361                return -1;
9362            }
9363
9364            /*
9365             * If the public key of the package's signature does not match
9366             * our expected public key, then this is a different package and
9367             * we should skip.
9368             */
9369
9370            final byte[] expectedPublicKey;
9371            try {
9372                final Signature verifierSig = pkg.mSignatures[0];
9373                final PublicKey publicKey = verifierSig.getPublicKey();
9374                expectedPublicKey = publicKey.getEncoded();
9375            } catch (CertificateException e) {
9376                return -1;
9377            }
9378
9379            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9380
9381            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9382                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9383                        + " does not have the expected public key; ignoring");
9384                return -1;
9385            }
9386
9387            return pkg.applicationInfo.uid;
9388        }
9389    }
9390
9391    @Override
9392    public void finishPackageInstall(int token) {
9393        enforceSystemOrRoot("Only the system is allowed to finish installs");
9394
9395        if (DEBUG_INSTALL) {
9396            Slog.v(TAG, "BM finishing package install for " + token);
9397        }
9398
9399        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9400        mHandler.sendMessage(msg);
9401    }
9402
9403    /**
9404     * Get the verification agent timeout.
9405     *
9406     * @return verification timeout in milliseconds
9407     */
9408    private long getVerificationTimeout() {
9409        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9410                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9411                DEFAULT_VERIFICATION_TIMEOUT);
9412    }
9413
9414    /**
9415     * Get the default verification agent response code.
9416     *
9417     * @return default verification response code
9418     */
9419    private int getDefaultVerificationResponse() {
9420        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9421                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9422                DEFAULT_VERIFICATION_RESPONSE);
9423    }
9424
9425    /**
9426     * Check whether or not package verification has been enabled.
9427     *
9428     * @return true if verification should be performed
9429     */
9430    private boolean isVerificationEnabled(int userId, int installFlags) {
9431        if (!DEFAULT_VERIFY_ENABLE) {
9432            return false;
9433        }
9434
9435        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9436
9437        // Check if installing from ADB
9438        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9439            // Do not run verification in a test harness environment
9440            if (ActivityManager.isRunningInTestHarness()) {
9441                return false;
9442            }
9443            if (ensureVerifyAppsEnabled) {
9444                return true;
9445            }
9446            // Check if the developer does not want package verification for ADB installs
9447            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9448                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9449                return false;
9450            }
9451        }
9452
9453        if (ensureVerifyAppsEnabled) {
9454            return true;
9455        }
9456
9457        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9458                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9459    }
9460
9461    @Override
9462    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9463            throws RemoteException {
9464        mContext.enforceCallingOrSelfPermission(
9465                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9466                "Only intentfilter verification agents can verify applications");
9467
9468        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9469        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9470                Binder.getCallingUid(), verificationCode, failedDomains);
9471        msg.arg1 = id;
9472        msg.obj = response;
9473        mHandler.sendMessage(msg);
9474    }
9475
9476    @Override
9477    public int getIntentVerificationStatus(String packageName, int userId) {
9478        synchronized (mPackages) {
9479            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9480        }
9481    }
9482
9483    @Override
9484    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9485        boolean result = false;
9486        synchronized (mPackages) {
9487            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9488        }
9489        if (result) {
9490            scheduleWritePackageRestrictionsLocked(userId);
9491        }
9492        return result;
9493    }
9494
9495    @Override
9496    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9497        synchronized (mPackages) {
9498            return mSettings.getIntentFilterVerificationsLPr(packageName);
9499        }
9500    }
9501
9502    @Override
9503    public List<IntentFilter> getAllIntentFilters(String packageName) {
9504        if (TextUtils.isEmpty(packageName)) {
9505            return Collections.<IntentFilter>emptyList();
9506        }
9507        synchronized (mPackages) {
9508            PackageParser.Package pkg = mPackages.get(packageName);
9509            if (pkg == null || pkg.activities == null) {
9510                return Collections.<IntentFilter>emptyList();
9511            }
9512            final int count = pkg.activities.size();
9513            ArrayList<IntentFilter> result = new ArrayList<>();
9514            for (int n=0; n<count; n++) {
9515                PackageParser.Activity activity = pkg.activities.get(n);
9516                if (activity.intents != null || activity.intents.size() > 0) {
9517                    result.addAll(activity.intents);
9518                }
9519            }
9520            return result;
9521        }
9522    }
9523
9524    @Override
9525    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9526        synchronized (mPackages) {
9527            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9528            if (packageName != null) {
9529                result |= updateIntentVerificationStatus(packageName,
9530                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9531                        UserHandle.myUserId());
9532            }
9533            return result;
9534        }
9535    }
9536
9537    @Override
9538    public String getDefaultBrowserPackageName(int userId) {
9539        synchronized (mPackages) {
9540            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9541        }
9542    }
9543
9544    /**
9545     * Get the "allow unknown sources" setting.
9546     *
9547     * @return the current "allow unknown sources" setting
9548     */
9549    private int getUnknownSourcesSettings() {
9550        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9551                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9552                -1);
9553    }
9554
9555    @Override
9556    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9557        final int uid = Binder.getCallingUid();
9558        // writer
9559        synchronized (mPackages) {
9560            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9561            if (targetPackageSetting == null) {
9562                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9563            }
9564
9565            PackageSetting installerPackageSetting;
9566            if (installerPackageName != null) {
9567                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9568                if (installerPackageSetting == null) {
9569                    throw new IllegalArgumentException("Unknown installer package: "
9570                            + installerPackageName);
9571                }
9572            } else {
9573                installerPackageSetting = null;
9574            }
9575
9576            Signature[] callerSignature;
9577            Object obj = mSettings.getUserIdLPr(uid);
9578            if (obj != null) {
9579                if (obj instanceof SharedUserSetting) {
9580                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9581                } else if (obj instanceof PackageSetting) {
9582                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9583                } else {
9584                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9585                }
9586            } else {
9587                throw new SecurityException("Unknown calling uid " + uid);
9588            }
9589
9590            // Verify: can't set installerPackageName to a package that is
9591            // not signed with the same cert as the caller.
9592            if (installerPackageSetting != null) {
9593                if (compareSignatures(callerSignature,
9594                        installerPackageSetting.signatures.mSignatures)
9595                        != PackageManager.SIGNATURE_MATCH) {
9596                    throw new SecurityException(
9597                            "Caller does not have same cert as new installer package "
9598                            + installerPackageName);
9599                }
9600            }
9601
9602            // Verify: if target already has an installer package, it must
9603            // be signed with the same cert as the caller.
9604            if (targetPackageSetting.installerPackageName != null) {
9605                PackageSetting setting = mSettings.mPackages.get(
9606                        targetPackageSetting.installerPackageName);
9607                // If the currently set package isn't valid, then it's always
9608                // okay to change it.
9609                if (setting != null) {
9610                    if (compareSignatures(callerSignature,
9611                            setting.signatures.mSignatures)
9612                            != PackageManager.SIGNATURE_MATCH) {
9613                        throw new SecurityException(
9614                                "Caller does not have same cert as old installer package "
9615                                + targetPackageSetting.installerPackageName);
9616                    }
9617                }
9618            }
9619
9620            // Okay!
9621            targetPackageSetting.installerPackageName = installerPackageName;
9622            scheduleWriteSettingsLocked();
9623        }
9624    }
9625
9626    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9627        // Queue up an async operation since the package installation may take a little while.
9628        mHandler.post(new Runnable() {
9629            public void run() {
9630                mHandler.removeCallbacks(this);
9631                 // Result object to be returned
9632                PackageInstalledInfo res = new PackageInstalledInfo();
9633                res.returnCode = currentStatus;
9634                res.uid = -1;
9635                res.pkg = null;
9636                res.removedInfo = new PackageRemovedInfo();
9637                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9638                    args.doPreInstall(res.returnCode);
9639                    synchronized (mInstallLock) {
9640                        installPackageLI(args, res);
9641                    }
9642                    args.doPostInstall(res.returnCode, res.uid);
9643                }
9644
9645                // A restore should be performed at this point if (a) the install
9646                // succeeded, (b) the operation is not an update, and (c) the new
9647                // package has not opted out of backup participation.
9648                final boolean update = res.removedInfo.removedPackage != null;
9649                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9650                boolean doRestore = !update
9651                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9652
9653                // Set up the post-install work request bookkeeping.  This will be used
9654                // and cleaned up by the post-install event handling regardless of whether
9655                // there's a restore pass performed.  Token values are >= 1.
9656                int token;
9657                if (mNextInstallToken < 0) mNextInstallToken = 1;
9658                token = mNextInstallToken++;
9659
9660                PostInstallData data = new PostInstallData(args, res);
9661                mRunningInstalls.put(token, data);
9662                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9663
9664                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9665                    // Pass responsibility to the Backup Manager.  It will perform a
9666                    // restore if appropriate, then pass responsibility back to the
9667                    // Package Manager to run the post-install observer callbacks
9668                    // and broadcasts.
9669                    IBackupManager bm = IBackupManager.Stub.asInterface(
9670                            ServiceManager.getService(Context.BACKUP_SERVICE));
9671                    if (bm != null) {
9672                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9673                                + " to BM for possible restore");
9674                        try {
9675                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9676                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9677                            } else {
9678                                doRestore = false;
9679                            }
9680                        } catch (RemoteException e) {
9681                            // can't happen; the backup manager is local
9682                        } catch (Exception e) {
9683                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9684                            doRestore = false;
9685                        }
9686                    } else {
9687                        Slog.e(TAG, "Backup Manager not found!");
9688                        doRestore = false;
9689                    }
9690                }
9691
9692                if (!doRestore) {
9693                    // No restore possible, or the Backup Manager was mysteriously not
9694                    // available -- just fire the post-install work request directly.
9695                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9696                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9697                    mHandler.sendMessage(msg);
9698                }
9699            }
9700        });
9701    }
9702
9703    private abstract class HandlerParams {
9704        private static final int MAX_RETRIES = 4;
9705
9706        /**
9707         * Number of times startCopy() has been attempted and had a non-fatal
9708         * error.
9709         */
9710        private int mRetries = 0;
9711
9712        /** User handle for the user requesting the information or installation. */
9713        private final UserHandle mUser;
9714
9715        HandlerParams(UserHandle user) {
9716            mUser = user;
9717        }
9718
9719        UserHandle getUser() {
9720            return mUser;
9721        }
9722
9723        final boolean startCopy() {
9724            boolean res;
9725            try {
9726                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9727
9728                if (++mRetries > MAX_RETRIES) {
9729                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9730                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9731                    handleServiceError();
9732                    return false;
9733                } else {
9734                    handleStartCopy();
9735                    res = true;
9736                }
9737            } catch (RemoteException e) {
9738                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9739                mHandler.sendEmptyMessage(MCS_RECONNECT);
9740                res = false;
9741            }
9742            handleReturnCode();
9743            return res;
9744        }
9745
9746        final void serviceError() {
9747            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9748            handleServiceError();
9749            handleReturnCode();
9750        }
9751
9752        abstract void handleStartCopy() throws RemoteException;
9753        abstract void handleServiceError();
9754        abstract void handleReturnCode();
9755    }
9756
9757    class MeasureParams extends HandlerParams {
9758        private final PackageStats mStats;
9759        private boolean mSuccess;
9760
9761        private final IPackageStatsObserver mObserver;
9762
9763        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9764            super(new UserHandle(stats.userHandle));
9765            mObserver = observer;
9766            mStats = stats;
9767        }
9768
9769        @Override
9770        public String toString() {
9771            return "MeasureParams{"
9772                + Integer.toHexString(System.identityHashCode(this))
9773                + " " + mStats.packageName + "}";
9774        }
9775
9776        @Override
9777        void handleStartCopy() throws RemoteException {
9778            synchronized (mInstallLock) {
9779                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9780            }
9781
9782            if (mSuccess) {
9783                final boolean mounted;
9784                if (Environment.isExternalStorageEmulated()) {
9785                    mounted = true;
9786                } else {
9787                    final String status = Environment.getExternalStorageState();
9788                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9789                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9790                }
9791
9792                if (mounted) {
9793                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9794
9795                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9796                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9797
9798                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9799                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9800
9801                    // Always subtract cache size, since it's a subdirectory
9802                    mStats.externalDataSize -= mStats.externalCacheSize;
9803
9804                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9805                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9806
9807                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9808                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9809                }
9810            }
9811        }
9812
9813        @Override
9814        void handleReturnCode() {
9815            if (mObserver != null) {
9816                try {
9817                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9818                } catch (RemoteException e) {
9819                    Slog.i(TAG, "Observer no longer exists.");
9820                }
9821            }
9822        }
9823
9824        @Override
9825        void handleServiceError() {
9826            Slog.e(TAG, "Could not measure application " + mStats.packageName
9827                            + " external storage");
9828        }
9829    }
9830
9831    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9832            throws RemoteException {
9833        long result = 0;
9834        for (File path : paths) {
9835            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9836        }
9837        return result;
9838    }
9839
9840    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9841        for (File path : paths) {
9842            try {
9843                mcs.clearDirectory(path.getAbsolutePath());
9844            } catch (RemoteException e) {
9845            }
9846        }
9847    }
9848
9849    static class OriginInfo {
9850        /**
9851         * Location where install is coming from, before it has been
9852         * copied/renamed into place. This could be a single monolithic APK
9853         * file, or a cluster directory. This location may be untrusted.
9854         */
9855        final File file;
9856        final String cid;
9857
9858        /**
9859         * Flag indicating that {@link #file} or {@link #cid} has already been
9860         * staged, meaning downstream users don't need to defensively copy the
9861         * contents.
9862         */
9863        final boolean staged;
9864
9865        /**
9866         * Flag indicating that {@link #file} or {@link #cid} is an already
9867         * installed app that is being moved.
9868         */
9869        final boolean existing;
9870
9871        final String resolvedPath;
9872        final File resolvedFile;
9873
9874        static OriginInfo fromNothing() {
9875            return new OriginInfo(null, null, false, false);
9876        }
9877
9878        static OriginInfo fromUntrustedFile(File file) {
9879            return new OriginInfo(file, null, false, false);
9880        }
9881
9882        static OriginInfo fromExistingFile(File file) {
9883            return new OriginInfo(file, null, false, true);
9884        }
9885
9886        static OriginInfo fromStagedFile(File file) {
9887            return new OriginInfo(file, null, true, false);
9888        }
9889
9890        static OriginInfo fromStagedContainer(String cid) {
9891            return new OriginInfo(null, cid, true, false);
9892        }
9893
9894        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9895            this.file = file;
9896            this.cid = cid;
9897            this.staged = staged;
9898            this.existing = existing;
9899
9900            if (cid != null) {
9901                resolvedPath = PackageHelper.getSdDir(cid);
9902                resolvedFile = new File(resolvedPath);
9903            } else if (file != null) {
9904                resolvedPath = file.getAbsolutePath();
9905                resolvedFile = file;
9906            } else {
9907                resolvedPath = null;
9908                resolvedFile = null;
9909            }
9910        }
9911    }
9912
9913    class MoveInfo {
9914        final int moveId;
9915        final String fromUuid;
9916        final String toUuid;
9917        final String packageName;
9918        final String dataAppName;
9919        final int appId;
9920        final String seinfo;
9921
9922        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9923                String dataAppName, int appId, String seinfo) {
9924            this.moveId = moveId;
9925            this.fromUuid = fromUuid;
9926            this.toUuid = toUuid;
9927            this.packageName = packageName;
9928            this.dataAppName = dataAppName;
9929            this.appId = appId;
9930            this.seinfo = seinfo;
9931        }
9932    }
9933
9934    class InstallParams extends HandlerParams {
9935        final OriginInfo origin;
9936        final MoveInfo move;
9937        final IPackageInstallObserver2 observer;
9938        int installFlags;
9939        final String installerPackageName;
9940        final String volumeUuid;
9941        final VerificationParams verificationParams;
9942        private InstallArgs mArgs;
9943        private int mRet;
9944        final String packageAbiOverride;
9945
9946        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
9947                int installFlags, String installerPackageName, String volumeUuid,
9948                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9949            super(user);
9950            this.origin = origin;
9951            this.move = move;
9952            this.observer = observer;
9953            this.installFlags = installFlags;
9954            this.installerPackageName = installerPackageName;
9955            this.volumeUuid = volumeUuid;
9956            this.verificationParams = verificationParams;
9957            this.packageAbiOverride = packageAbiOverride;
9958        }
9959
9960        @Override
9961        public String toString() {
9962            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9963                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9964        }
9965
9966        public ManifestDigest getManifestDigest() {
9967            if (verificationParams == null) {
9968                return null;
9969            }
9970            return verificationParams.getManifestDigest();
9971        }
9972
9973        private int installLocationPolicy(PackageInfoLite pkgLite) {
9974            String packageName = pkgLite.packageName;
9975            int installLocation = pkgLite.installLocation;
9976            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9977            // reader
9978            synchronized (mPackages) {
9979                PackageParser.Package pkg = mPackages.get(packageName);
9980                if (pkg != null) {
9981                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9982                        // Check for downgrading.
9983                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9984                            try {
9985                                checkDowngrade(pkg, pkgLite);
9986                            } catch (PackageManagerException e) {
9987                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9988                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9989                            }
9990                        }
9991                        // Check for updated system application.
9992                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9993                            if (onSd) {
9994                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9995                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9996                            }
9997                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9998                        } else {
9999                            if (onSd) {
10000                                // Install flag overrides everything.
10001                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10002                            }
10003                            // If current upgrade specifies particular preference
10004                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10005                                // Application explicitly specified internal.
10006                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10007                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10008                                // App explictly prefers external. Let policy decide
10009                            } else {
10010                                // Prefer previous location
10011                                if (isExternal(pkg)) {
10012                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10013                                }
10014                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10015                            }
10016                        }
10017                    } else {
10018                        // Invalid install. Return error code
10019                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10020                    }
10021                }
10022            }
10023            // All the special cases have been taken care of.
10024            // Return result based on recommended install location.
10025            if (onSd) {
10026                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10027            }
10028            return pkgLite.recommendedInstallLocation;
10029        }
10030
10031        /*
10032         * Invoke remote method to get package information and install
10033         * location values. Override install location based on default
10034         * policy if needed and then create install arguments based
10035         * on the install location.
10036         */
10037        public void handleStartCopy() throws RemoteException {
10038            int ret = PackageManager.INSTALL_SUCCEEDED;
10039
10040            // If we're already staged, we've firmly committed to an install location
10041            if (origin.staged) {
10042                if (origin.file != null) {
10043                    installFlags |= PackageManager.INSTALL_INTERNAL;
10044                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10045                } else if (origin.cid != null) {
10046                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10047                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10048                } else {
10049                    throw new IllegalStateException("Invalid stage location");
10050                }
10051            }
10052
10053            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10054            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10055
10056            PackageInfoLite pkgLite = null;
10057
10058            if (onInt && onSd) {
10059                // Check if both bits are set.
10060                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10061                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10062            } else {
10063                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10064                        packageAbiOverride);
10065
10066                /*
10067                 * If we have too little free space, try to free cache
10068                 * before giving up.
10069                 */
10070                if (!origin.staged && pkgLite.recommendedInstallLocation
10071                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10072                    // TODO: focus freeing disk space on the target device
10073                    final StorageManager storage = StorageManager.from(mContext);
10074                    final long lowThreshold = storage.getStorageLowBytes(
10075                            Environment.getDataDirectory());
10076
10077                    final long sizeBytes = mContainerService.calculateInstalledSize(
10078                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10079
10080                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10081                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10082                                installFlags, packageAbiOverride);
10083                    }
10084
10085                    /*
10086                     * The cache free must have deleted the file we
10087                     * downloaded to install.
10088                     *
10089                     * TODO: fix the "freeCache" call to not delete
10090                     *       the file we care about.
10091                     */
10092                    if (pkgLite.recommendedInstallLocation
10093                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10094                        pkgLite.recommendedInstallLocation
10095                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10096                    }
10097                }
10098            }
10099
10100            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10101                int loc = pkgLite.recommendedInstallLocation;
10102                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10103                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10104                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10105                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10106                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10107                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10108                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10109                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10110                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10111                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10112                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10113                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10114                } else {
10115                    // Override with defaults if needed.
10116                    loc = installLocationPolicy(pkgLite);
10117                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10118                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10119                    } else if (!onSd && !onInt) {
10120                        // Override install location with flags
10121                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10122                            // Set the flag to install on external media.
10123                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10124                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10125                        } else {
10126                            // Make sure the flag for installing on external
10127                            // media is unset
10128                            installFlags |= PackageManager.INSTALL_INTERNAL;
10129                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10130                        }
10131                    }
10132                }
10133            }
10134
10135            final InstallArgs args = createInstallArgs(this);
10136            mArgs = args;
10137
10138            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10139                 /*
10140                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10141                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10142                 */
10143                int userIdentifier = getUser().getIdentifier();
10144                if (userIdentifier == UserHandle.USER_ALL
10145                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10146                    userIdentifier = UserHandle.USER_OWNER;
10147                }
10148
10149                /*
10150                 * Determine if we have any installed package verifiers. If we
10151                 * do, then we'll defer to them to verify the packages.
10152                 */
10153                final int requiredUid = mRequiredVerifierPackage == null ? -1
10154                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10155                if (!origin.existing && requiredUid != -1
10156                        && isVerificationEnabled(userIdentifier, installFlags)) {
10157                    final Intent verification = new Intent(
10158                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10159                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10160                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10161                            PACKAGE_MIME_TYPE);
10162                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10163
10164                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10165                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10166                            0 /* TODO: Which userId? */);
10167
10168                    if (DEBUG_VERIFY) {
10169                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10170                                + verification.toString() + " with " + pkgLite.verifiers.length
10171                                + " optional verifiers");
10172                    }
10173
10174                    final int verificationId = mPendingVerificationToken++;
10175
10176                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10177
10178                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10179                            installerPackageName);
10180
10181                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10182                            installFlags);
10183
10184                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10185                            pkgLite.packageName);
10186
10187                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10188                            pkgLite.versionCode);
10189
10190                    if (verificationParams != null) {
10191                        if (verificationParams.getVerificationURI() != null) {
10192                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10193                                 verificationParams.getVerificationURI());
10194                        }
10195                        if (verificationParams.getOriginatingURI() != null) {
10196                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10197                                  verificationParams.getOriginatingURI());
10198                        }
10199                        if (verificationParams.getReferrer() != null) {
10200                            verification.putExtra(Intent.EXTRA_REFERRER,
10201                                  verificationParams.getReferrer());
10202                        }
10203                        if (verificationParams.getOriginatingUid() >= 0) {
10204                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10205                                  verificationParams.getOriginatingUid());
10206                        }
10207                        if (verificationParams.getInstallerUid() >= 0) {
10208                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10209                                  verificationParams.getInstallerUid());
10210                        }
10211                    }
10212
10213                    final PackageVerificationState verificationState = new PackageVerificationState(
10214                            requiredUid, args);
10215
10216                    mPendingVerification.append(verificationId, verificationState);
10217
10218                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10219                            receivers, verificationState);
10220
10221                    /*
10222                     * If any sufficient verifiers were listed in the package
10223                     * manifest, attempt to ask them.
10224                     */
10225                    if (sufficientVerifiers != null) {
10226                        final int N = sufficientVerifiers.size();
10227                        if (N == 0) {
10228                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10229                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10230                        } else {
10231                            for (int i = 0; i < N; i++) {
10232                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10233
10234                                final Intent sufficientIntent = new Intent(verification);
10235                                sufficientIntent.setComponent(verifierComponent);
10236
10237                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10238                            }
10239                        }
10240                    }
10241
10242                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10243                            mRequiredVerifierPackage, receivers);
10244                    if (ret == PackageManager.INSTALL_SUCCEEDED
10245                            && mRequiredVerifierPackage != null) {
10246                        /*
10247                         * Send the intent to the required verification agent,
10248                         * but only start the verification timeout after the
10249                         * target BroadcastReceivers have run.
10250                         */
10251                        verification.setComponent(requiredVerifierComponent);
10252                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10253                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10254                                new BroadcastReceiver() {
10255                                    @Override
10256                                    public void onReceive(Context context, Intent intent) {
10257                                        final Message msg = mHandler
10258                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10259                                        msg.arg1 = verificationId;
10260                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10261                                    }
10262                                }, null, 0, null, null);
10263
10264                        /*
10265                         * We don't want the copy to proceed until verification
10266                         * succeeds, so null out this field.
10267                         */
10268                        mArgs = null;
10269                    }
10270                } else {
10271                    /*
10272                     * No package verification is enabled, so immediately start
10273                     * the remote call to initiate copy using temporary file.
10274                     */
10275                    ret = args.copyApk(mContainerService, true);
10276                }
10277            }
10278
10279            mRet = ret;
10280        }
10281
10282        @Override
10283        void handleReturnCode() {
10284            // If mArgs is null, then MCS couldn't be reached. When it
10285            // reconnects, it will try again to install. At that point, this
10286            // will succeed.
10287            if (mArgs != null) {
10288                processPendingInstall(mArgs, mRet);
10289            }
10290        }
10291
10292        @Override
10293        void handleServiceError() {
10294            mArgs = createInstallArgs(this);
10295            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10296        }
10297
10298        public boolean isForwardLocked() {
10299            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10300        }
10301    }
10302
10303    /**
10304     * Used during creation of InstallArgs
10305     *
10306     * @param installFlags package installation flags
10307     * @return true if should be installed on external storage
10308     */
10309    private static boolean installOnExternalAsec(int installFlags) {
10310        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10311            return false;
10312        }
10313        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10314            return true;
10315        }
10316        return false;
10317    }
10318
10319    /**
10320     * Used during creation of InstallArgs
10321     *
10322     * @param installFlags package installation flags
10323     * @return true if should be installed as forward locked
10324     */
10325    private static boolean installForwardLocked(int installFlags) {
10326        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10327    }
10328
10329    private InstallArgs createInstallArgs(InstallParams params) {
10330        if (params.move != null) {
10331            return new MoveInstallArgs(params);
10332        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10333            return new AsecInstallArgs(params);
10334        } else {
10335            return new FileInstallArgs(params);
10336        }
10337    }
10338
10339    /**
10340     * Create args that describe an existing installed package. Typically used
10341     * when cleaning up old installs, or used as a move source.
10342     */
10343    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10344            String resourcePath, String[] instructionSets) {
10345        final boolean isInAsec;
10346        if (installOnExternalAsec(installFlags)) {
10347            /* Apps on SD card are always in ASEC containers. */
10348            isInAsec = true;
10349        } else if (installForwardLocked(installFlags)
10350                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10351            /*
10352             * Forward-locked apps are only in ASEC containers if they're the
10353             * new style
10354             */
10355            isInAsec = true;
10356        } else {
10357            isInAsec = false;
10358        }
10359
10360        if (isInAsec) {
10361            return new AsecInstallArgs(codePath, instructionSets,
10362                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10363        } else {
10364            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10365        }
10366    }
10367
10368    static abstract class InstallArgs {
10369        /** @see InstallParams#origin */
10370        final OriginInfo origin;
10371        /** @see InstallParams#move */
10372        final MoveInfo move;
10373
10374        final IPackageInstallObserver2 observer;
10375        // Always refers to PackageManager flags only
10376        final int installFlags;
10377        final String installerPackageName;
10378        final String volumeUuid;
10379        final ManifestDigest manifestDigest;
10380        final UserHandle user;
10381        final String abiOverride;
10382
10383        // The list of instruction sets supported by this app. This is currently
10384        // only used during the rmdex() phase to clean up resources. We can get rid of this
10385        // if we move dex files under the common app path.
10386        /* nullable */ String[] instructionSets;
10387
10388        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10389                int installFlags, String installerPackageName, String volumeUuid,
10390                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10391                String abiOverride) {
10392            this.origin = origin;
10393            this.move = move;
10394            this.installFlags = installFlags;
10395            this.observer = observer;
10396            this.installerPackageName = installerPackageName;
10397            this.volumeUuid = volumeUuid;
10398            this.manifestDigest = manifestDigest;
10399            this.user = user;
10400            this.instructionSets = instructionSets;
10401            this.abiOverride = abiOverride;
10402        }
10403
10404        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10405        abstract int doPreInstall(int status);
10406
10407        /**
10408         * Rename package into final resting place. All paths on the given
10409         * scanned package should be updated to reflect the rename.
10410         */
10411        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10412        abstract int doPostInstall(int status, int uid);
10413
10414        /** @see PackageSettingBase#codePathString */
10415        abstract String getCodePath();
10416        /** @see PackageSettingBase#resourcePathString */
10417        abstract String getResourcePath();
10418
10419        // Need installer lock especially for dex file removal.
10420        abstract void cleanUpResourcesLI();
10421        abstract boolean doPostDeleteLI(boolean delete);
10422
10423        /**
10424         * Called before the source arguments are copied. This is used mostly
10425         * for MoveParams when it needs to read the source file to put it in the
10426         * destination.
10427         */
10428        int doPreCopy() {
10429            return PackageManager.INSTALL_SUCCEEDED;
10430        }
10431
10432        /**
10433         * Called after the source arguments are copied. This is used mostly for
10434         * MoveParams when it needs to read the source file to put it in the
10435         * destination.
10436         *
10437         * @return
10438         */
10439        int doPostCopy(int uid) {
10440            return PackageManager.INSTALL_SUCCEEDED;
10441        }
10442
10443        protected boolean isFwdLocked() {
10444            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10445        }
10446
10447        protected boolean isExternalAsec() {
10448            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10449        }
10450
10451        UserHandle getUser() {
10452            return user;
10453        }
10454    }
10455
10456    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10457        if (!allCodePaths.isEmpty()) {
10458            if (instructionSets == null) {
10459                throw new IllegalStateException("instructionSet == null");
10460            }
10461            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10462            for (String codePath : allCodePaths) {
10463                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10464                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10465                    if (retCode < 0) {
10466                        Slog.w(TAG, "Couldn't remove dex file for package: "
10467                                + " at location " + codePath + ", retcode=" + retCode);
10468                        // we don't consider this to be a failure of the core package deletion
10469                    }
10470                }
10471            }
10472        }
10473    }
10474
10475    /**
10476     * Logic to handle installation of non-ASEC applications, including copying
10477     * and renaming logic.
10478     */
10479    class FileInstallArgs extends InstallArgs {
10480        private File codeFile;
10481        private File resourceFile;
10482
10483        // Example topology:
10484        // /data/app/com.example/base.apk
10485        // /data/app/com.example/split_foo.apk
10486        // /data/app/com.example/lib/arm/libfoo.so
10487        // /data/app/com.example/lib/arm64/libfoo.so
10488        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10489
10490        /** New install */
10491        FileInstallArgs(InstallParams params) {
10492            super(params.origin, params.move, params.observer, params.installFlags,
10493                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10494                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10495            if (isFwdLocked()) {
10496                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10497            }
10498        }
10499
10500        /** Existing install */
10501        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10502            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10503                    null);
10504            this.codeFile = (codePath != null) ? new File(codePath) : null;
10505            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10506        }
10507
10508        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10509            if (origin.staged) {
10510                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10511                codeFile = origin.file;
10512                resourceFile = origin.file;
10513                return PackageManager.INSTALL_SUCCEEDED;
10514            }
10515
10516            try {
10517                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10518                codeFile = tempDir;
10519                resourceFile = tempDir;
10520            } catch (IOException e) {
10521                Slog.w(TAG, "Failed to create copy file: " + e);
10522                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10523            }
10524
10525            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10526                @Override
10527                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10528                    if (!FileUtils.isValidExtFilename(name)) {
10529                        throw new IllegalArgumentException("Invalid filename: " + name);
10530                    }
10531                    try {
10532                        final File file = new File(codeFile, name);
10533                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10534                                O_RDWR | O_CREAT, 0644);
10535                        Os.chmod(file.getAbsolutePath(), 0644);
10536                        return new ParcelFileDescriptor(fd);
10537                    } catch (ErrnoException e) {
10538                        throw new RemoteException("Failed to open: " + e.getMessage());
10539                    }
10540                }
10541            };
10542
10543            int ret = PackageManager.INSTALL_SUCCEEDED;
10544            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10545            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10546                Slog.e(TAG, "Failed to copy package");
10547                return ret;
10548            }
10549
10550            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10551            NativeLibraryHelper.Handle handle = null;
10552            try {
10553                handle = NativeLibraryHelper.Handle.create(codeFile);
10554                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10555                        abiOverride);
10556            } catch (IOException e) {
10557                Slog.e(TAG, "Copying native libraries failed", e);
10558                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10559            } finally {
10560                IoUtils.closeQuietly(handle);
10561            }
10562
10563            return ret;
10564        }
10565
10566        int doPreInstall(int status) {
10567            if (status != PackageManager.INSTALL_SUCCEEDED) {
10568                cleanUp();
10569            }
10570            return status;
10571        }
10572
10573        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10574            if (status != PackageManager.INSTALL_SUCCEEDED) {
10575                cleanUp();
10576                return false;
10577            }
10578
10579            final File targetDir = codeFile.getParentFile();
10580            final File beforeCodeFile = codeFile;
10581            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10582
10583            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10584            try {
10585                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10586            } catch (ErrnoException e) {
10587                Slog.w(TAG, "Failed to rename", e);
10588                return false;
10589            }
10590
10591            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10592                Slog.w(TAG, "Failed to restorecon");
10593                return false;
10594            }
10595
10596            // Reflect the rename internally
10597            codeFile = afterCodeFile;
10598            resourceFile = afterCodeFile;
10599
10600            // Reflect the rename in scanned details
10601            pkg.codePath = afterCodeFile.getAbsolutePath();
10602            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10603                    pkg.baseCodePath);
10604            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10605                    pkg.splitCodePaths);
10606
10607            // Reflect the rename in app info
10608            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10609            pkg.applicationInfo.setCodePath(pkg.codePath);
10610            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10611            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10612            pkg.applicationInfo.setResourcePath(pkg.codePath);
10613            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10614            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10615
10616            return true;
10617        }
10618
10619        int doPostInstall(int status, int uid) {
10620            if (status != PackageManager.INSTALL_SUCCEEDED) {
10621                cleanUp();
10622            }
10623            return status;
10624        }
10625
10626        @Override
10627        String getCodePath() {
10628            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10629        }
10630
10631        @Override
10632        String getResourcePath() {
10633            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10634        }
10635
10636        private boolean cleanUp() {
10637            if (codeFile == null || !codeFile.exists()) {
10638                return false;
10639            }
10640
10641            if (codeFile.isDirectory()) {
10642                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10643            } else {
10644                codeFile.delete();
10645            }
10646
10647            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10648                resourceFile.delete();
10649            }
10650
10651            return true;
10652        }
10653
10654        void cleanUpResourcesLI() {
10655            // Try enumerating all code paths before deleting
10656            List<String> allCodePaths = Collections.EMPTY_LIST;
10657            if (codeFile != null && codeFile.exists()) {
10658                try {
10659                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10660                    allCodePaths = pkg.getAllCodePaths();
10661                } catch (PackageParserException e) {
10662                    // Ignored; we tried our best
10663                }
10664            }
10665
10666            cleanUp();
10667            removeDexFiles(allCodePaths, instructionSets);
10668        }
10669
10670        boolean doPostDeleteLI(boolean delete) {
10671            // XXX err, shouldn't we respect the delete flag?
10672            cleanUpResourcesLI();
10673            return true;
10674        }
10675    }
10676
10677    private boolean isAsecExternal(String cid) {
10678        final String asecPath = PackageHelper.getSdFilesystem(cid);
10679        return !asecPath.startsWith(mAsecInternalPath);
10680    }
10681
10682    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10683            PackageManagerException {
10684        if (copyRet < 0) {
10685            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10686                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10687                throw new PackageManagerException(copyRet, message);
10688            }
10689        }
10690    }
10691
10692    /**
10693     * Extract the MountService "container ID" from the full code path of an
10694     * .apk.
10695     */
10696    static String cidFromCodePath(String fullCodePath) {
10697        int eidx = fullCodePath.lastIndexOf("/");
10698        String subStr1 = fullCodePath.substring(0, eidx);
10699        int sidx = subStr1.lastIndexOf("/");
10700        return subStr1.substring(sidx+1, eidx);
10701    }
10702
10703    /**
10704     * Logic to handle installation of ASEC applications, including copying and
10705     * renaming logic.
10706     */
10707    class AsecInstallArgs extends InstallArgs {
10708        static final String RES_FILE_NAME = "pkg.apk";
10709        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10710
10711        String cid;
10712        String packagePath;
10713        String resourcePath;
10714
10715        /** New install */
10716        AsecInstallArgs(InstallParams params) {
10717            super(params.origin, params.move, params.observer, params.installFlags,
10718                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10719                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10720        }
10721
10722        /** Existing install */
10723        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10724                        boolean isExternal, boolean isForwardLocked) {
10725            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10726                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10727                    instructionSets, null);
10728            // Hackily pretend we're still looking at a full code path
10729            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10730                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10731            }
10732
10733            // Extract cid from fullCodePath
10734            int eidx = fullCodePath.lastIndexOf("/");
10735            String subStr1 = fullCodePath.substring(0, eidx);
10736            int sidx = subStr1.lastIndexOf("/");
10737            cid = subStr1.substring(sidx+1, eidx);
10738            setMountPath(subStr1);
10739        }
10740
10741        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10742            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10743                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10744                    instructionSets, null);
10745            this.cid = cid;
10746            setMountPath(PackageHelper.getSdDir(cid));
10747        }
10748
10749        void createCopyFile() {
10750            cid = mInstallerService.allocateExternalStageCidLegacy();
10751        }
10752
10753        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10754            if (origin.staged) {
10755                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
10756                cid = origin.cid;
10757                setMountPath(PackageHelper.getSdDir(cid));
10758                return PackageManager.INSTALL_SUCCEEDED;
10759            }
10760
10761            if (temp) {
10762                createCopyFile();
10763            } else {
10764                /*
10765                 * Pre-emptively destroy the container since it's destroyed if
10766                 * copying fails due to it existing anyway.
10767                 */
10768                PackageHelper.destroySdDir(cid);
10769            }
10770
10771            final String newMountPath = imcs.copyPackageToContainer(
10772                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10773                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10774
10775            if (newMountPath != null) {
10776                setMountPath(newMountPath);
10777                return PackageManager.INSTALL_SUCCEEDED;
10778            } else {
10779                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10780            }
10781        }
10782
10783        @Override
10784        String getCodePath() {
10785            return packagePath;
10786        }
10787
10788        @Override
10789        String getResourcePath() {
10790            return resourcePath;
10791        }
10792
10793        int doPreInstall(int status) {
10794            if (status != PackageManager.INSTALL_SUCCEEDED) {
10795                // Destroy container
10796                PackageHelper.destroySdDir(cid);
10797            } else {
10798                boolean mounted = PackageHelper.isContainerMounted(cid);
10799                if (!mounted) {
10800                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10801                            Process.SYSTEM_UID);
10802                    if (newMountPath != null) {
10803                        setMountPath(newMountPath);
10804                    } else {
10805                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10806                    }
10807                }
10808            }
10809            return status;
10810        }
10811
10812        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10813            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10814            String newMountPath = null;
10815            if (PackageHelper.isContainerMounted(cid)) {
10816                // Unmount the container
10817                if (!PackageHelper.unMountSdDir(cid)) {
10818                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10819                    return false;
10820                }
10821            }
10822            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10823                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10824                        " which might be stale. Will try to clean up.");
10825                // Clean up the stale container and proceed to recreate.
10826                if (!PackageHelper.destroySdDir(newCacheId)) {
10827                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10828                    return false;
10829                }
10830                // Successfully cleaned up stale container. Try to rename again.
10831                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10832                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10833                            + " inspite of cleaning it up.");
10834                    return false;
10835                }
10836            }
10837            if (!PackageHelper.isContainerMounted(newCacheId)) {
10838                Slog.w(TAG, "Mounting container " + newCacheId);
10839                newMountPath = PackageHelper.mountSdDir(newCacheId,
10840                        getEncryptKey(), Process.SYSTEM_UID);
10841            } else {
10842                newMountPath = PackageHelper.getSdDir(newCacheId);
10843            }
10844            if (newMountPath == null) {
10845                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10846                return false;
10847            }
10848            Log.i(TAG, "Succesfully renamed " + cid +
10849                    " to " + newCacheId +
10850                    " at new path: " + newMountPath);
10851            cid = newCacheId;
10852
10853            final File beforeCodeFile = new File(packagePath);
10854            setMountPath(newMountPath);
10855            final File afterCodeFile = new File(packagePath);
10856
10857            // Reflect the rename in scanned details
10858            pkg.codePath = afterCodeFile.getAbsolutePath();
10859            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10860                    pkg.baseCodePath);
10861            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10862                    pkg.splitCodePaths);
10863
10864            // Reflect the rename in app info
10865            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10866            pkg.applicationInfo.setCodePath(pkg.codePath);
10867            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10868            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10869            pkg.applicationInfo.setResourcePath(pkg.codePath);
10870            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10871            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10872
10873            return true;
10874        }
10875
10876        private void setMountPath(String mountPath) {
10877            final File mountFile = new File(mountPath);
10878
10879            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10880            if (monolithicFile.exists()) {
10881                packagePath = monolithicFile.getAbsolutePath();
10882                if (isFwdLocked()) {
10883                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10884                } else {
10885                    resourcePath = packagePath;
10886                }
10887            } else {
10888                packagePath = mountFile.getAbsolutePath();
10889                resourcePath = packagePath;
10890            }
10891        }
10892
10893        int doPostInstall(int status, int uid) {
10894            if (status != PackageManager.INSTALL_SUCCEEDED) {
10895                cleanUp();
10896            } else {
10897                final int groupOwner;
10898                final String protectedFile;
10899                if (isFwdLocked()) {
10900                    groupOwner = UserHandle.getSharedAppGid(uid);
10901                    protectedFile = RES_FILE_NAME;
10902                } else {
10903                    groupOwner = -1;
10904                    protectedFile = null;
10905                }
10906
10907                if (uid < Process.FIRST_APPLICATION_UID
10908                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10909                    Slog.e(TAG, "Failed to finalize " + cid);
10910                    PackageHelper.destroySdDir(cid);
10911                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10912                }
10913
10914                boolean mounted = PackageHelper.isContainerMounted(cid);
10915                if (!mounted) {
10916                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10917                }
10918            }
10919            return status;
10920        }
10921
10922        private void cleanUp() {
10923            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10924
10925            // Destroy secure container
10926            PackageHelper.destroySdDir(cid);
10927        }
10928
10929        private List<String> getAllCodePaths() {
10930            final File codeFile = new File(getCodePath());
10931            if (codeFile != null && codeFile.exists()) {
10932                try {
10933                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10934                    return pkg.getAllCodePaths();
10935                } catch (PackageParserException e) {
10936                    // Ignored; we tried our best
10937                }
10938            }
10939            return Collections.EMPTY_LIST;
10940        }
10941
10942        void cleanUpResourcesLI() {
10943            // Enumerate all code paths before deleting
10944            cleanUpResourcesLI(getAllCodePaths());
10945        }
10946
10947        private void cleanUpResourcesLI(List<String> allCodePaths) {
10948            cleanUp();
10949            removeDexFiles(allCodePaths, instructionSets);
10950        }
10951
10952        String getPackageName() {
10953            return getAsecPackageName(cid);
10954        }
10955
10956        boolean doPostDeleteLI(boolean delete) {
10957            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10958            final List<String> allCodePaths = getAllCodePaths();
10959            boolean mounted = PackageHelper.isContainerMounted(cid);
10960            if (mounted) {
10961                // Unmount first
10962                if (PackageHelper.unMountSdDir(cid)) {
10963                    mounted = false;
10964                }
10965            }
10966            if (!mounted && delete) {
10967                cleanUpResourcesLI(allCodePaths);
10968            }
10969            return !mounted;
10970        }
10971
10972        @Override
10973        int doPreCopy() {
10974            if (isFwdLocked()) {
10975                if (!PackageHelper.fixSdPermissions(cid,
10976                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10977                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10978                }
10979            }
10980
10981            return PackageManager.INSTALL_SUCCEEDED;
10982        }
10983
10984        @Override
10985        int doPostCopy(int uid) {
10986            if (isFwdLocked()) {
10987                if (uid < Process.FIRST_APPLICATION_UID
10988                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10989                                RES_FILE_NAME)) {
10990                    Slog.e(TAG, "Failed to finalize " + cid);
10991                    PackageHelper.destroySdDir(cid);
10992                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10993                }
10994            }
10995
10996            return PackageManager.INSTALL_SUCCEEDED;
10997        }
10998    }
10999
11000    /**
11001     * Logic to handle movement of existing installed applications.
11002     */
11003    class MoveInstallArgs extends InstallArgs {
11004        private File codeFile;
11005        private File resourceFile;
11006
11007        /** New install */
11008        MoveInstallArgs(InstallParams params) {
11009            super(params.origin, params.move, params.observer, params.installFlags,
11010                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11011                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11012        }
11013
11014        int copyApk(IMediaContainerService imcs, boolean temp) {
11015            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11016                    + move.fromUuid + " to " + move.toUuid);
11017            synchronized (mInstaller) {
11018                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11019                        move.dataAppName, move.appId, move.seinfo) != 0) {
11020                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11021                }
11022            }
11023
11024            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11025            resourceFile = codeFile;
11026            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11027
11028            return PackageManager.INSTALL_SUCCEEDED;
11029        }
11030
11031        int doPreInstall(int status) {
11032            if (status != PackageManager.INSTALL_SUCCEEDED) {
11033                cleanUp();
11034            }
11035            return status;
11036        }
11037
11038        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11039            if (status != PackageManager.INSTALL_SUCCEEDED) {
11040                cleanUp();
11041                return false;
11042            }
11043
11044            // Reflect the move in app info
11045            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11046            pkg.applicationInfo.setCodePath(pkg.codePath);
11047            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11048            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11049            pkg.applicationInfo.setResourcePath(pkg.codePath);
11050            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11051            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11052
11053            return true;
11054        }
11055
11056        int doPostInstall(int status, int uid) {
11057            if (status != PackageManager.INSTALL_SUCCEEDED) {
11058                cleanUp();
11059            }
11060            return status;
11061        }
11062
11063        @Override
11064        String getCodePath() {
11065            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11066        }
11067
11068        @Override
11069        String getResourcePath() {
11070            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11071        }
11072
11073        private boolean cleanUp() {
11074            if (codeFile == null || !codeFile.exists()) {
11075                return false;
11076            }
11077
11078            if (codeFile.isDirectory()) {
11079                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11080            } else {
11081                codeFile.delete();
11082            }
11083
11084            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11085                resourceFile.delete();
11086            }
11087
11088            return true;
11089        }
11090
11091        void cleanUpResourcesLI() {
11092            cleanUp();
11093        }
11094
11095        boolean doPostDeleteLI(boolean delete) {
11096            // XXX err, shouldn't we respect the delete flag?
11097            cleanUpResourcesLI();
11098            return true;
11099        }
11100    }
11101
11102    static String getAsecPackageName(String packageCid) {
11103        int idx = packageCid.lastIndexOf("-");
11104        if (idx == -1) {
11105            return packageCid;
11106        }
11107        return packageCid.substring(0, idx);
11108    }
11109
11110    // Utility method used to create code paths based on package name and available index.
11111    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11112        String idxStr = "";
11113        int idx = 1;
11114        // Fall back to default value of idx=1 if prefix is not
11115        // part of oldCodePath
11116        if (oldCodePath != null) {
11117            String subStr = oldCodePath;
11118            // Drop the suffix right away
11119            if (suffix != null && subStr.endsWith(suffix)) {
11120                subStr = subStr.substring(0, subStr.length() - suffix.length());
11121            }
11122            // If oldCodePath already contains prefix find out the
11123            // ending index to either increment or decrement.
11124            int sidx = subStr.lastIndexOf(prefix);
11125            if (sidx != -1) {
11126                subStr = subStr.substring(sidx + prefix.length());
11127                if (subStr != null) {
11128                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11129                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11130                    }
11131                    try {
11132                        idx = Integer.parseInt(subStr);
11133                        if (idx <= 1) {
11134                            idx++;
11135                        } else {
11136                            idx--;
11137                        }
11138                    } catch(NumberFormatException e) {
11139                    }
11140                }
11141            }
11142        }
11143        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11144        return prefix + idxStr;
11145    }
11146
11147    private File getNextCodePath(File targetDir, String packageName) {
11148        int suffix = 1;
11149        File result;
11150        do {
11151            result = new File(targetDir, packageName + "-" + suffix);
11152            suffix++;
11153        } while (result.exists());
11154        return result;
11155    }
11156
11157    // Utility method that returns the relative package path with respect
11158    // to the installation directory. Like say for /data/data/com.test-1.apk
11159    // string com.test-1 is returned.
11160    static String deriveCodePathName(String codePath) {
11161        if (codePath == null) {
11162            return null;
11163        }
11164        final File codeFile = new File(codePath);
11165        final String name = codeFile.getName();
11166        if (codeFile.isDirectory()) {
11167            return name;
11168        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11169            final int lastDot = name.lastIndexOf('.');
11170            return name.substring(0, lastDot);
11171        } else {
11172            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11173            return null;
11174        }
11175    }
11176
11177    class PackageInstalledInfo {
11178        String name;
11179        int uid;
11180        // The set of users that originally had this package installed.
11181        int[] origUsers;
11182        // The set of users that now have this package installed.
11183        int[] newUsers;
11184        PackageParser.Package pkg;
11185        int returnCode;
11186        String returnMsg;
11187        PackageRemovedInfo removedInfo;
11188
11189        public void setError(int code, String msg) {
11190            returnCode = code;
11191            returnMsg = msg;
11192            Slog.w(TAG, msg);
11193        }
11194
11195        public void setError(String msg, PackageParserException e) {
11196            returnCode = e.error;
11197            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11198            Slog.w(TAG, msg, e);
11199        }
11200
11201        public void setError(String msg, PackageManagerException e) {
11202            returnCode = e.error;
11203            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11204            Slog.w(TAG, msg, e);
11205        }
11206
11207        // In some error cases we want to convey more info back to the observer
11208        String origPackage;
11209        String origPermission;
11210    }
11211
11212    /*
11213     * Install a non-existing package.
11214     */
11215    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11216            UserHandle user, String installerPackageName, String volumeUuid,
11217            PackageInstalledInfo res) {
11218        // Remember this for later, in case we need to rollback this install
11219        String pkgName = pkg.packageName;
11220
11221        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11222        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11223                UserHandle.USER_OWNER).exists();
11224        synchronized(mPackages) {
11225            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11226                // A package with the same name is already installed, though
11227                // it has been renamed to an older name.  The package we
11228                // are trying to install should be installed as an update to
11229                // the existing one, but that has not been requested, so bail.
11230                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11231                        + " without first uninstalling package running as "
11232                        + mSettings.mRenamedPackages.get(pkgName));
11233                return;
11234            }
11235            if (mPackages.containsKey(pkgName)) {
11236                // Don't allow installation over an existing package with the same name.
11237                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11238                        + " without first uninstalling.");
11239                return;
11240            }
11241        }
11242
11243        try {
11244            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11245                    System.currentTimeMillis(), user);
11246
11247            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11248            // delete the partially installed application. the data directory will have to be
11249            // restored if it was already existing
11250            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11251                // remove package from internal structures.  Note that we want deletePackageX to
11252                // delete the package data and cache directories that it created in
11253                // scanPackageLocked, unless those directories existed before we even tried to
11254                // install.
11255                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11256                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11257                                res.removedInfo, true);
11258            }
11259
11260        } catch (PackageManagerException e) {
11261            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11262        }
11263    }
11264
11265    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11266        // Can't rotate keys during boot or if sharedUser.
11267        if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null
11268                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11269            return false;
11270        }
11271        // app is using upgradeKeySets; make sure all are valid
11272        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11273        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11274        for (int i = 0; i < upgradeKeySets.length; i++) {
11275            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11276                Slog.wtf(TAG, "Package "
11277                         + (oldPs.name != null ? oldPs.name : "<null>")
11278                         + " contains upgrade-key-set reference to unknown key-set: "
11279                         + upgradeKeySets[i]
11280                         + " reverting to signatures check.");
11281                return false;
11282            }
11283        }
11284        return true;
11285    }
11286
11287    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11288        // Upgrade keysets are being used.  Determine if new package has a superset of the
11289        // required keys.
11290        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11291        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11292        for (int i = 0; i < upgradeKeySets.length; i++) {
11293            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11294            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11295                return true;
11296            }
11297        }
11298        return false;
11299    }
11300
11301    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11302            UserHandle user, String installerPackageName, String volumeUuid,
11303            PackageInstalledInfo res) {
11304        final PackageParser.Package oldPackage;
11305        final String pkgName = pkg.packageName;
11306        final int[] allUsers;
11307        final boolean[] perUserInstalled;
11308        final boolean weFroze;
11309
11310        // First find the old package info and check signatures
11311        synchronized(mPackages) {
11312            oldPackage = mPackages.get(pkgName);
11313            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11314            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11315            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11316                if(!checkUpgradeKeySetLP(ps, pkg)) {
11317                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11318                            "New package not signed by keys specified by upgrade-keysets: "
11319                            + pkgName);
11320                    return;
11321                }
11322            } else {
11323                // default to original signature matching
11324                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11325                    != PackageManager.SIGNATURE_MATCH) {
11326                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11327                            "New package has a different signature: " + pkgName);
11328                    return;
11329                }
11330            }
11331
11332            // In case of rollback, remember per-user/profile install state
11333            allUsers = sUserManager.getUserIds();
11334            perUserInstalled = new boolean[allUsers.length];
11335            for (int i = 0; i < allUsers.length; i++) {
11336                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11337            }
11338
11339            // Mark the app as frozen to prevent launching during the upgrade
11340            // process, and then kill all running instances
11341            if (!ps.frozen) {
11342                ps.frozen = true;
11343                weFroze = true;
11344            } else {
11345                weFroze = false;
11346            }
11347        }
11348
11349        // Now that we're guarded by frozen state, kill app during upgrade
11350        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11351
11352        try {
11353            boolean sysPkg = (isSystemApp(oldPackage));
11354            if (sysPkg) {
11355                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11356                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11357            } else {
11358                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11359                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11360            }
11361        } finally {
11362            // Regardless of success or failure of upgrade steps above, always
11363            // unfreeze the package if we froze it
11364            if (weFroze) {
11365                unfreezePackage(pkgName);
11366            }
11367        }
11368    }
11369
11370    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11371            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11372            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11373            String volumeUuid, PackageInstalledInfo res) {
11374        String pkgName = deletedPackage.packageName;
11375        boolean deletedPkg = true;
11376        boolean updatedSettings = false;
11377
11378        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11379                + deletedPackage);
11380        long origUpdateTime;
11381        if (pkg.mExtras != null) {
11382            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11383        } else {
11384            origUpdateTime = 0;
11385        }
11386
11387        // First delete the existing package while retaining the data directory
11388        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11389                res.removedInfo, true)) {
11390            // If the existing package wasn't successfully deleted
11391            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11392            deletedPkg = false;
11393        } else {
11394            // Successfully deleted the old package; proceed with replace.
11395
11396            // If deleted package lived in a container, give users a chance to
11397            // relinquish resources before killing.
11398            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11399                if (DEBUG_INSTALL) {
11400                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11401                }
11402                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11403                final ArrayList<String> pkgList = new ArrayList<String>(1);
11404                pkgList.add(deletedPackage.applicationInfo.packageName);
11405                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11406            }
11407
11408            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11409            try {
11410                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11411                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11412                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11413                        perUserInstalled, res, user);
11414                updatedSettings = true;
11415            } catch (PackageManagerException e) {
11416                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11417            }
11418        }
11419
11420        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11421            // remove package from internal structures.  Note that we want deletePackageX to
11422            // delete the package data and cache directories that it created in
11423            // scanPackageLocked, unless those directories existed before we even tried to
11424            // install.
11425            if(updatedSettings) {
11426                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11427                deletePackageLI(
11428                        pkgName, null, true, allUsers, perUserInstalled,
11429                        PackageManager.DELETE_KEEP_DATA,
11430                                res.removedInfo, true);
11431            }
11432            // Since we failed to install the new package we need to restore the old
11433            // package that we deleted.
11434            if (deletedPkg) {
11435                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11436                File restoreFile = new File(deletedPackage.codePath);
11437                // Parse old package
11438                boolean oldExternal = isExternal(deletedPackage);
11439                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11440                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11441                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11442                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11443                try {
11444                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11445                } catch (PackageManagerException e) {
11446                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11447                            + e.getMessage());
11448                    return;
11449                }
11450                // Restore of old package succeeded. Update permissions.
11451                // writer
11452                synchronized (mPackages) {
11453                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11454                            UPDATE_PERMISSIONS_ALL);
11455                    // can downgrade to reader
11456                    mSettings.writeLPr();
11457                }
11458                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11459            }
11460        }
11461    }
11462
11463    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11464            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11465            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11466            String volumeUuid, PackageInstalledInfo res) {
11467        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11468                + ", old=" + deletedPackage);
11469        boolean disabledSystem = false;
11470        boolean updatedSettings = false;
11471        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11472        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11473                != 0) {
11474            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11475        }
11476        String packageName = deletedPackage.packageName;
11477        if (packageName == null) {
11478            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11479                    "Attempt to delete null packageName.");
11480            return;
11481        }
11482        PackageParser.Package oldPkg;
11483        PackageSetting oldPkgSetting;
11484        // reader
11485        synchronized (mPackages) {
11486            oldPkg = mPackages.get(packageName);
11487            oldPkgSetting = mSettings.mPackages.get(packageName);
11488            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11489                    (oldPkgSetting == null)) {
11490                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11491                        "Couldn't find package:" + packageName + " information");
11492                return;
11493            }
11494        }
11495
11496        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11497        res.removedInfo.removedPackage = packageName;
11498        // Remove existing system package
11499        removePackageLI(oldPkgSetting, true);
11500        // writer
11501        synchronized (mPackages) {
11502            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11503            if (!disabledSystem && deletedPackage != null) {
11504                // We didn't need to disable the .apk as a current system package,
11505                // which means we are replacing another update that is already
11506                // installed.  We need to make sure to delete the older one's .apk.
11507                res.removedInfo.args = createInstallArgsForExisting(0,
11508                        deletedPackage.applicationInfo.getCodePath(),
11509                        deletedPackage.applicationInfo.getResourcePath(),
11510                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11511            } else {
11512                res.removedInfo.args = null;
11513            }
11514        }
11515
11516        // Successfully disabled the old package. Now proceed with re-installation
11517        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11518
11519        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11520        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11521
11522        PackageParser.Package newPackage = null;
11523        try {
11524            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11525            if (newPackage.mExtras != null) {
11526                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11527                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11528                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11529
11530                // is the update attempting to change shared user? that isn't going to work...
11531                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11532                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11533                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11534                            + " to " + newPkgSetting.sharedUser);
11535                    updatedSettings = true;
11536                }
11537            }
11538
11539            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11540                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11541                        perUserInstalled, res, user);
11542                updatedSettings = true;
11543            }
11544
11545        } catch (PackageManagerException e) {
11546            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11547        }
11548
11549        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11550            // Re installation failed. Restore old information
11551            // Remove new pkg information
11552            if (newPackage != null) {
11553                removeInstalledPackageLI(newPackage, true);
11554            }
11555            // Add back the old system package
11556            try {
11557                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11558            } catch (PackageManagerException e) {
11559                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11560            }
11561            // Restore the old system information in Settings
11562            synchronized (mPackages) {
11563                if (disabledSystem) {
11564                    mSettings.enableSystemPackageLPw(packageName);
11565                }
11566                if (updatedSettings) {
11567                    mSettings.setInstallerPackageName(packageName,
11568                            oldPkgSetting.installerPackageName);
11569                }
11570                mSettings.writeLPr();
11571            }
11572        }
11573    }
11574
11575    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11576            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11577            UserHandle user) {
11578        String pkgName = newPackage.packageName;
11579        synchronized (mPackages) {
11580            //write settings. the installStatus will be incomplete at this stage.
11581            //note that the new package setting would have already been
11582            //added to mPackages. It hasn't been persisted yet.
11583            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11584            mSettings.writeLPr();
11585        }
11586
11587        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11588
11589        synchronized (mPackages) {
11590            updatePermissionsLPw(newPackage.packageName, newPackage,
11591                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11592                            ? UPDATE_PERMISSIONS_ALL : 0));
11593            // For system-bundled packages, we assume that installing an upgraded version
11594            // of the package implies that the user actually wants to run that new code,
11595            // so we enable the package.
11596            PackageSetting ps = mSettings.mPackages.get(pkgName);
11597            if (ps != null) {
11598                if (isSystemApp(newPackage)) {
11599                    // NB: implicit assumption that system package upgrades apply to all users
11600                    if (DEBUG_INSTALL) {
11601                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11602                    }
11603                    if (res.origUsers != null) {
11604                        for (int userHandle : res.origUsers) {
11605                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11606                                    userHandle, installerPackageName);
11607                        }
11608                    }
11609                    // Also convey the prior install/uninstall state
11610                    if (allUsers != null && perUserInstalled != null) {
11611                        for (int i = 0; i < allUsers.length; i++) {
11612                            if (DEBUG_INSTALL) {
11613                                Slog.d(TAG, "    user " + allUsers[i]
11614                                        + " => " + perUserInstalled[i]);
11615                            }
11616                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11617                        }
11618                        // these install state changes will be persisted in the
11619                        // upcoming call to mSettings.writeLPr().
11620                    }
11621                }
11622                // It's implied that when a user requests installation, they want the app to be
11623                // installed and enabled.
11624                int userId = user.getIdentifier();
11625                if (userId != UserHandle.USER_ALL) {
11626                    ps.setInstalled(true, userId);
11627                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11628                }
11629            }
11630            res.name = pkgName;
11631            res.uid = newPackage.applicationInfo.uid;
11632            res.pkg = newPackage;
11633            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11634            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11635            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11636            //to update install status
11637            mSettings.writeLPr();
11638        }
11639    }
11640
11641    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11642        final int installFlags = args.installFlags;
11643        final String installerPackageName = args.installerPackageName;
11644        final String volumeUuid = args.volumeUuid;
11645        final File tmpPackageFile = new File(args.getCodePath());
11646        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11647        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11648                || (args.volumeUuid != null));
11649        boolean replace = false;
11650        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11651        // Result object to be returned
11652        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11653
11654        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11655        // Retrieve PackageSettings and parse package
11656        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11657                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11658                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11659        PackageParser pp = new PackageParser();
11660        pp.setSeparateProcesses(mSeparateProcesses);
11661        pp.setDisplayMetrics(mMetrics);
11662
11663        final PackageParser.Package pkg;
11664        try {
11665            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11666        } catch (PackageParserException e) {
11667            res.setError("Failed parse during installPackageLI", e);
11668            return;
11669        }
11670
11671        // Mark that we have an install time CPU ABI override.
11672        pkg.cpuAbiOverride = args.abiOverride;
11673
11674        String pkgName = res.name = pkg.packageName;
11675        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11676            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11677                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11678                return;
11679            }
11680        }
11681
11682        try {
11683            pp.collectCertificates(pkg, parseFlags);
11684            pp.collectManifestDigest(pkg);
11685        } catch (PackageParserException e) {
11686            res.setError("Failed collect during installPackageLI", e);
11687            return;
11688        }
11689
11690        /* If the installer passed in a manifest digest, compare it now. */
11691        if (args.manifestDigest != null) {
11692            if (DEBUG_INSTALL) {
11693                final String parsedManifest = pkg.manifestDigest == null ? "null"
11694                        : pkg.manifestDigest.toString();
11695                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11696                        + parsedManifest);
11697            }
11698
11699            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11700                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11701                return;
11702            }
11703        } else if (DEBUG_INSTALL) {
11704            final String parsedManifest = pkg.manifestDigest == null
11705                    ? "null" : pkg.manifestDigest.toString();
11706            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11707        }
11708
11709        // Get rid of all references to package scan path via parser.
11710        pp = null;
11711        String oldCodePath = null;
11712        boolean systemApp = false;
11713        synchronized (mPackages) {
11714            // Check if installing already existing package
11715            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11716                String oldName = mSettings.mRenamedPackages.get(pkgName);
11717                if (pkg.mOriginalPackages != null
11718                        && pkg.mOriginalPackages.contains(oldName)
11719                        && mPackages.containsKey(oldName)) {
11720                    // This package is derived from an original package,
11721                    // and this device has been updating from that original
11722                    // name.  We must continue using the original name, so
11723                    // rename the new package here.
11724                    pkg.setPackageName(oldName);
11725                    pkgName = pkg.packageName;
11726                    replace = true;
11727                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11728                            + oldName + " pkgName=" + pkgName);
11729                } else if (mPackages.containsKey(pkgName)) {
11730                    // This package, under its official name, already exists
11731                    // on the device; we should replace it.
11732                    replace = true;
11733                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11734                }
11735
11736                // Prevent apps opting out from runtime permissions
11737                if (replace) {
11738                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11739                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11740                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11741                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11742                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11743                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11744                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11745                                        + " doesn't support runtime permissions but the old"
11746                                        + " target SDK " + oldTargetSdk + " does.");
11747                        return;
11748                    }
11749                }
11750            }
11751
11752            PackageSetting ps = mSettings.mPackages.get(pkgName);
11753            if (ps != null) {
11754                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11755
11756                // Quick sanity check that we're signed correctly if updating;
11757                // we'll check this again later when scanning, but we want to
11758                // bail early here before tripping over redefined permissions.
11759                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11760                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11761                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11762                                + pkg.packageName + " upgrade keys do not match the "
11763                                + "previously installed version");
11764                        return;
11765                    }
11766                } else {
11767                    try {
11768                        verifySignaturesLP(ps, pkg);
11769                    } catch (PackageManagerException e) {
11770                        res.setError(e.error, e.getMessage());
11771                        return;
11772                    }
11773                }
11774
11775                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11776                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11777                    systemApp = (ps.pkg.applicationInfo.flags &
11778                            ApplicationInfo.FLAG_SYSTEM) != 0;
11779                }
11780                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11781            }
11782
11783            // Check whether the newly-scanned package wants to define an already-defined perm
11784            int N = pkg.permissions.size();
11785            for (int i = N-1; i >= 0; i--) {
11786                PackageParser.Permission perm = pkg.permissions.get(i);
11787                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11788                if (bp != null) {
11789                    // If the defining package is signed with our cert, it's okay.  This
11790                    // also includes the "updating the same package" case, of course.
11791                    // "updating same package" could also involve key-rotation.
11792                    final boolean sigsOk;
11793                    if (bp.sourcePackage.equals(pkg.packageName)
11794                            && (bp.packageSetting instanceof PackageSetting)
11795                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
11796                                    scanFlags))) {
11797                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11798                    } else {
11799                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11800                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11801                    }
11802                    if (!sigsOk) {
11803                        // If the owning package is the system itself, we log but allow
11804                        // install to proceed; we fail the install on all other permission
11805                        // redefinitions.
11806                        if (!bp.sourcePackage.equals("android")) {
11807                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11808                                    + pkg.packageName + " attempting to redeclare permission "
11809                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11810                            res.origPermission = perm.info.name;
11811                            res.origPackage = bp.sourcePackage;
11812                            return;
11813                        } else {
11814                            Slog.w(TAG, "Package " + pkg.packageName
11815                                    + " attempting to redeclare system permission "
11816                                    + perm.info.name + "; ignoring new declaration");
11817                            pkg.permissions.remove(i);
11818                        }
11819                    }
11820                }
11821            }
11822
11823        }
11824
11825        if (systemApp && onExternal) {
11826            // Disable updates to system apps on sdcard
11827            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11828                    "Cannot install updates to system apps on sdcard");
11829            return;
11830        }
11831
11832        if (args.move != null) {
11833            // We did an in-place move, so dex is ready to roll
11834            scanFlags |= SCAN_NO_DEX;
11835            scanFlags |= SCAN_MOVE;
11836        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11837            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11838            scanFlags |= SCAN_NO_DEX;
11839
11840            try {
11841                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
11842                        true /* extract libs */);
11843            } catch (PackageManagerException pme) {
11844                Slog.e(TAG, "Error deriving application ABI", pme);
11845                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
11846                return;
11847            }
11848
11849            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11850            int result = mPackageDexOptimizer
11851                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
11852                            false /* defer */, false /* inclDependencies */);
11853            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11854                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11855                return;
11856            }
11857        }
11858
11859        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11860            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11861            return;
11862        }
11863
11864        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11865
11866        if (replace) {
11867            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11868                    installerPackageName, volumeUuid, res);
11869        } else {
11870            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11871                    args.user, installerPackageName, volumeUuid, res);
11872        }
11873        synchronized (mPackages) {
11874            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11875            if (ps != null) {
11876                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11877            }
11878        }
11879    }
11880
11881    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11882        if (mIntentFilterVerifierComponent == null) {
11883            Slog.w(TAG, "No IntentFilter verification will not be done as "
11884                    + "there is no IntentFilterVerifier available!");
11885            return;
11886        }
11887
11888        final int verifierUid = getPackageUid(
11889                mIntentFilterVerifierComponent.getPackageName(),
11890                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11891
11892        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11893        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11894        msg.obj = pkg;
11895        msg.arg1 = userId;
11896        msg.arg2 = verifierUid;
11897
11898        mHandler.sendMessage(msg);
11899    }
11900
11901    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11902            PackageParser.Package pkg) {
11903        int size = pkg.activities.size();
11904        if (size == 0) {
11905            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11906                    "No activity, so no need to verify any IntentFilter!");
11907            return;
11908        }
11909
11910        final boolean hasDomainURLs = hasDomainURLs(pkg);
11911        if (!hasDomainURLs) {
11912            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11913                    "No domain URLs, so no need to verify any IntentFilter!");
11914            return;
11915        }
11916
11917        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
11918                + " if any IntentFilter from the " + size
11919                + " Activities needs verification ...");
11920
11921        final int verificationId = mIntentFilterVerificationToken++;
11922        int count = 0;
11923        final String packageName = pkg.packageName;
11924        boolean needToVerify = false;
11925
11926        synchronized (mPackages) {
11927            // If any filters need to be verified, then all need to be.
11928            for (PackageParser.Activity a : pkg.activities) {
11929                for (ActivityIntentInfo filter : a.intents) {
11930                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
11931                        if (DEBUG_DOMAIN_VERIFICATION) {
11932                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
11933                        }
11934                        needToVerify = true;
11935                        break;
11936                    }
11937                }
11938            }
11939            if (needToVerify) {
11940                for (PackageParser.Activity a : pkg.activities) {
11941                    for (ActivityIntentInfo filter : a.intents) {
11942                        boolean needsFilterVerification = filter.hasWebDataURI();
11943                        if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11944                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11945                                    "Verification needed for IntentFilter:" + filter.toString());
11946                            mIntentFilterVerifier.addOneIntentFilterVerification(
11947                                    verifierUid, userId, verificationId, filter, packageName);
11948                            count++;
11949                        }
11950                    }
11951                }
11952            }
11953        }
11954
11955        if (count > 0) {
11956            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
11957                    + " IntentFilter verification" + (count > 1 ? "s" : "")
11958                    +  " for userId:" + userId);
11959            mIntentFilterVerifier.startVerifications(userId);
11960        } else {
11961            if (DEBUG_DOMAIN_VERIFICATION) {
11962                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
11963            }
11964        }
11965    }
11966
11967    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11968        final ComponentName cn  = filter.activity.getComponentName();
11969        final String packageName = cn.getPackageName();
11970
11971        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11972                packageName);
11973        if (ivi == null) {
11974            return true;
11975        }
11976        int status = ivi.getStatus();
11977        switch (status) {
11978            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11979            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11980                return true;
11981
11982            default:
11983                // Nothing to do
11984                return false;
11985        }
11986    }
11987
11988    private static boolean isMultiArch(PackageSetting ps) {
11989        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11990    }
11991
11992    private static boolean isMultiArch(ApplicationInfo info) {
11993        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11994    }
11995
11996    private static boolean isExternal(PackageParser.Package pkg) {
11997        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11998    }
11999
12000    private static boolean isExternal(PackageSetting ps) {
12001        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12002    }
12003
12004    private static boolean isExternal(ApplicationInfo info) {
12005        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12006    }
12007
12008    private static boolean isSystemApp(PackageParser.Package pkg) {
12009        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12010    }
12011
12012    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12013        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12014    }
12015
12016    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12017        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12018    }
12019
12020    private static boolean isSystemApp(PackageSetting ps) {
12021        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12022    }
12023
12024    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12025        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12026    }
12027
12028    private int packageFlagsToInstallFlags(PackageSetting ps) {
12029        int installFlags = 0;
12030        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12031            // This existing package was an external ASEC install when we have
12032            // the external flag without a UUID
12033            installFlags |= PackageManager.INSTALL_EXTERNAL;
12034        }
12035        if (ps.isForwardLocked()) {
12036            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12037        }
12038        return installFlags;
12039    }
12040
12041    private void deleteTempPackageFiles() {
12042        final FilenameFilter filter = new FilenameFilter() {
12043            public boolean accept(File dir, String name) {
12044                return name.startsWith("vmdl") && name.endsWith(".tmp");
12045            }
12046        };
12047        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12048            file.delete();
12049        }
12050    }
12051
12052    @Override
12053    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12054            int flags) {
12055        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12056                flags);
12057    }
12058
12059    @Override
12060    public void deletePackage(final String packageName,
12061            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12062        mContext.enforceCallingOrSelfPermission(
12063                android.Manifest.permission.DELETE_PACKAGES, null);
12064        final int uid = Binder.getCallingUid();
12065        if (UserHandle.getUserId(uid) != userId) {
12066            mContext.enforceCallingPermission(
12067                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12068                    "deletePackage for user " + userId);
12069        }
12070        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12071            try {
12072                observer.onPackageDeleted(packageName,
12073                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12074            } catch (RemoteException re) {
12075            }
12076            return;
12077        }
12078
12079        boolean uninstallBlocked = false;
12080        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12081            int[] users = sUserManager.getUserIds();
12082            for (int i = 0; i < users.length; ++i) {
12083                if (getBlockUninstallForUser(packageName, users[i])) {
12084                    uninstallBlocked = true;
12085                    break;
12086                }
12087            }
12088        } else {
12089            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12090        }
12091        if (uninstallBlocked) {
12092            try {
12093                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12094                        null);
12095            } catch (RemoteException re) {
12096            }
12097            return;
12098        }
12099
12100        if (DEBUG_REMOVE) {
12101            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12102        }
12103        // Queue up an async operation since the package deletion may take a little while.
12104        mHandler.post(new Runnable() {
12105            public void run() {
12106                mHandler.removeCallbacks(this);
12107                final int returnCode = deletePackageX(packageName, userId, flags);
12108                if (observer != null) {
12109                    try {
12110                        observer.onPackageDeleted(packageName, returnCode, null);
12111                    } catch (RemoteException e) {
12112                        Log.i(TAG, "Observer no longer exists.");
12113                    } //end catch
12114                } //end if
12115            } //end run
12116        });
12117    }
12118
12119    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12120        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12121                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12122        try {
12123            if (dpm != null) {
12124                if (dpm.isDeviceOwner(packageName)) {
12125                    return true;
12126                }
12127                int[] users;
12128                if (userId == UserHandle.USER_ALL) {
12129                    users = sUserManager.getUserIds();
12130                } else {
12131                    users = new int[]{userId};
12132                }
12133                for (int i = 0; i < users.length; ++i) {
12134                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12135                        return true;
12136                    }
12137                }
12138            }
12139        } catch (RemoteException e) {
12140        }
12141        return false;
12142    }
12143
12144    /**
12145     *  This method is an internal method that could be get invoked either
12146     *  to delete an installed package or to clean up a failed installation.
12147     *  After deleting an installed package, a broadcast is sent to notify any
12148     *  listeners that the package has been installed. For cleaning up a failed
12149     *  installation, the broadcast is not necessary since the package's
12150     *  installation wouldn't have sent the initial broadcast either
12151     *  The key steps in deleting a package are
12152     *  deleting the package information in internal structures like mPackages,
12153     *  deleting the packages base directories through installd
12154     *  updating mSettings to reflect current status
12155     *  persisting settings for later use
12156     *  sending a broadcast if necessary
12157     */
12158    private int deletePackageX(String packageName, int userId, int flags) {
12159        final PackageRemovedInfo info = new PackageRemovedInfo();
12160        final boolean res;
12161
12162        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12163                ? UserHandle.ALL : new UserHandle(userId);
12164
12165        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12166            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12167            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12168        }
12169
12170        boolean removedForAllUsers = false;
12171        boolean systemUpdate = false;
12172
12173        // for the uninstall-updates case and restricted profiles, remember the per-
12174        // userhandle installed state
12175        int[] allUsers;
12176        boolean[] perUserInstalled;
12177        synchronized (mPackages) {
12178            PackageSetting ps = mSettings.mPackages.get(packageName);
12179            allUsers = sUserManager.getUserIds();
12180            perUserInstalled = new boolean[allUsers.length];
12181            for (int i = 0; i < allUsers.length; i++) {
12182                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12183            }
12184        }
12185
12186        synchronized (mInstallLock) {
12187            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12188            res = deletePackageLI(packageName, removeForUser,
12189                    true, allUsers, perUserInstalled,
12190                    flags | REMOVE_CHATTY, info, true);
12191            systemUpdate = info.isRemovedPackageSystemUpdate;
12192            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12193                removedForAllUsers = true;
12194            }
12195            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12196                    + " removedForAllUsers=" + removedForAllUsers);
12197        }
12198
12199        if (res) {
12200            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12201
12202            // If the removed package was a system update, the old system package
12203            // was re-enabled; we need to broadcast this information
12204            if (systemUpdate) {
12205                Bundle extras = new Bundle(1);
12206                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12207                        ? info.removedAppId : info.uid);
12208                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12209
12210                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12211                        extras, null, null, null);
12212                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12213                        extras, null, null, null);
12214                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12215                        null, packageName, null, null);
12216            }
12217        }
12218        // Force a gc here.
12219        Runtime.getRuntime().gc();
12220        // Delete the resources here after sending the broadcast to let
12221        // other processes clean up before deleting resources.
12222        if (info.args != null) {
12223            synchronized (mInstallLock) {
12224                info.args.doPostDeleteLI(true);
12225            }
12226        }
12227
12228        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12229    }
12230
12231    class PackageRemovedInfo {
12232        String removedPackage;
12233        int uid = -1;
12234        int removedAppId = -1;
12235        int[] removedUsers = null;
12236        boolean isRemovedPackageSystemUpdate = false;
12237        // Clean up resources deleted packages.
12238        InstallArgs args = null;
12239
12240        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12241            Bundle extras = new Bundle(1);
12242            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12243            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12244            if (replacing) {
12245                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12246            }
12247            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12248            if (removedPackage != null) {
12249                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12250                        extras, null, null, removedUsers);
12251                if (fullRemove && !replacing) {
12252                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12253                            extras, null, null, removedUsers);
12254                }
12255            }
12256            if (removedAppId >= 0) {
12257                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12258                        removedUsers);
12259            }
12260        }
12261    }
12262
12263    /*
12264     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12265     * flag is not set, the data directory is removed as well.
12266     * make sure this flag is set for partially installed apps. If not its meaningless to
12267     * delete a partially installed application.
12268     */
12269    private void removePackageDataLI(PackageSetting ps,
12270            int[] allUserHandles, boolean[] perUserInstalled,
12271            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12272        String packageName = ps.name;
12273        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12274        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12275        // Retrieve object to delete permissions for shared user later on
12276        final PackageSetting deletedPs;
12277        // reader
12278        synchronized (mPackages) {
12279            deletedPs = mSettings.mPackages.get(packageName);
12280            if (outInfo != null) {
12281                outInfo.removedPackage = packageName;
12282                outInfo.removedUsers = deletedPs != null
12283                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12284                        : null;
12285            }
12286        }
12287        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12288            removeDataDirsLI(ps.volumeUuid, packageName);
12289            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12290        }
12291        // writer
12292        synchronized (mPackages) {
12293            if (deletedPs != null) {
12294                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12295                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12296                    clearDefaultBrowserIfNeeded(packageName);
12297                    if (outInfo != null) {
12298                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12299                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12300                    }
12301                    updatePermissionsLPw(deletedPs.name, null, 0);
12302                    if (deletedPs.sharedUser != null) {
12303                        // Remove permissions associated with package. Since runtime
12304                        // permissions are per user we have to kill the removed package
12305                        // or packages running under the shared user of the removed
12306                        // package if revoking the permissions requested only by the removed
12307                        // package is successful and this causes a change in gids.
12308                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12309                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12310                                    userId);
12311                            if (userIdToKill == UserHandle.USER_ALL
12312                                    || userIdToKill >= UserHandle.USER_OWNER) {
12313                                // If gids changed for this user, kill all affected packages.
12314                                mHandler.post(new Runnable() {
12315                                    @Override
12316                                    public void run() {
12317                                        // This has to happen with no lock held.
12318                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12319                                                KILL_APP_REASON_GIDS_CHANGED);
12320                                    }
12321                                });
12322                            break;
12323                            }
12324                        }
12325                    }
12326                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12327                }
12328                // make sure to preserve per-user disabled state if this removal was just
12329                // a downgrade of a system app to the factory package
12330                if (allUserHandles != null && perUserInstalled != null) {
12331                    if (DEBUG_REMOVE) {
12332                        Slog.d(TAG, "Propagating install state across downgrade");
12333                    }
12334                    for (int i = 0; i < allUserHandles.length; i++) {
12335                        if (DEBUG_REMOVE) {
12336                            Slog.d(TAG, "    user " + allUserHandles[i]
12337                                    + " => " + perUserInstalled[i]);
12338                        }
12339                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12340                    }
12341                }
12342            }
12343            // can downgrade to reader
12344            if (writeSettings) {
12345                // Save settings now
12346                mSettings.writeLPr();
12347            }
12348        }
12349        if (outInfo != null) {
12350            // A user ID was deleted here. Go through all users and remove it
12351            // from KeyStore.
12352            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12353        }
12354    }
12355
12356    static boolean locationIsPrivileged(File path) {
12357        try {
12358            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12359                    .getCanonicalPath();
12360            return path.getCanonicalPath().startsWith(privilegedAppDir);
12361        } catch (IOException e) {
12362            Slog.e(TAG, "Unable to access code path " + path);
12363        }
12364        return false;
12365    }
12366
12367    /*
12368     * Tries to delete system package.
12369     */
12370    private boolean deleteSystemPackageLI(PackageSetting newPs,
12371            int[] allUserHandles, boolean[] perUserInstalled,
12372            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12373        final boolean applyUserRestrictions
12374                = (allUserHandles != null) && (perUserInstalled != null);
12375        PackageSetting disabledPs = null;
12376        // Confirm if the system package has been updated
12377        // An updated system app can be deleted. This will also have to restore
12378        // the system pkg from system partition
12379        // reader
12380        synchronized (mPackages) {
12381            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12382        }
12383        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12384                + " disabledPs=" + disabledPs);
12385        if (disabledPs == null) {
12386            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12387            return false;
12388        } else if (DEBUG_REMOVE) {
12389            Slog.d(TAG, "Deleting system pkg from data partition");
12390        }
12391        if (DEBUG_REMOVE) {
12392            if (applyUserRestrictions) {
12393                Slog.d(TAG, "Remembering install states:");
12394                for (int i = 0; i < allUserHandles.length; i++) {
12395                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12396                }
12397            }
12398        }
12399        // Delete the updated package
12400        outInfo.isRemovedPackageSystemUpdate = true;
12401        if (disabledPs.versionCode < newPs.versionCode) {
12402            // Delete data for downgrades
12403            flags &= ~PackageManager.DELETE_KEEP_DATA;
12404        } else {
12405            // Preserve data by setting flag
12406            flags |= PackageManager.DELETE_KEEP_DATA;
12407        }
12408        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12409                allUserHandles, perUserInstalled, outInfo, writeSettings);
12410        if (!ret) {
12411            return false;
12412        }
12413        // writer
12414        synchronized (mPackages) {
12415            // Reinstate the old system package
12416            mSettings.enableSystemPackageLPw(newPs.name);
12417            // Remove any native libraries from the upgraded package.
12418            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12419        }
12420        // Install the system package
12421        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12422        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12423        if (locationIsPrivileged(disabledPs.codePath)) {
12424            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12425        }
12426
12427        final PackageParser.Package newPkg;
12428        try {
12429            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12430        } catch (PackageManagerException e) {
12431            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12432            return false;
12433        }
12434
12435        // writer
12436        synchronized (mPackages) {
12437            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12438            updatePermissionsLPw(newPkg.packageName, newPkg,
12439                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12440            if (applyUserRestrictions) {
12441                if (DEBUG_REMOVE) {
12442                    Slog.d(TAG, "Propagating install state across reinstall");
12443                }
12444                for (int i = 0; i < allUserHandles.length; i++) {
12445                    if (DEBUG_REMOVE) {
12446                        Slog.d(TAG, "    user " + allUserHandles[i]
12447                                + " => " + perUserInstalled[i]);
12448                    }
12449                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12450                }
12451                // Regardless of writeSettings we need to ensure that this restriction
12452                // state propagation is persisted
12453                mSettings.writeAllUsersPackageRestrictionsLPr();
12454            }
12455            // can downgrade to reader here
12456            if (writeSettings) {
12457                mSettings.writeLPr();
12458            }
12459        }
12460        return true;
12461    }
12462
12463    private boolean deleteInstalledPackageLI(PackageSetting ps,
12464            boolean deleteCodeAndResources, int flags,
12465            int[] allUserHandles, boolean[] perUserInstalled,
12466            PackageRemovedInfo outInfo, boolean writeSettings) {
12467        if (outInfo != null) {
12468            outInfo.uid = ps.appId;
12469        }
12470
12471        // Delete package data from internal structures and also remove data if flag is set
12472        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12473
12474        // Delete application code and resources
12475        if (deleteCodeAndResources && (outInfo != null)) {
12476            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12477                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12478            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12479        }
12480        return true;
12481    }
12482
12483    @Override
12484    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12485            int userId) {
12486        mContext.enforceCallingOrSelfPermission(
12487                android.Manifest.permission.DELETE_PACKAGES, null);
12488        synchronized (mPackages) {
12489            PackageSetting ps = mSettings.mPackages.get(packageName);
12490            if (ps == null) {
12491                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12492                return false;
12493            }
12494            if (!ps.getInstalled(userId)) {
12495                // Can't block uninstall for an app that is not installed or enabled.
12496                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12497                return false;
12498            }
12499            ps.setBlockUninstall(blockUninstall, userId);
12500            mSettings.writePackageRestrictionsLPr(userId);
12501        }
12502        return true;
12503    }
12504
12505    @Override
12506    public boolean getBlockUninstallForUser(String packageName, int userId) {
12507        synchronized (mPackages) {
12508            PackageSetting ps = mSettings.mPackages.get(packageName);
12509            if (ps == null) {
12510                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12511                return false;
12512            }
12513            return ps.getBlockUninstall(userId);
12514        }
12515    }
12516
12517    /*
12518     * This method handles package deletion in general
12519     */
12520    private boolean deletePackageLI(String packageName, UserHandle user,
12521            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12522            int flags, PackageRemovedInfo outInfo,
12523            boolean writeSettings) {
12524        if (packageName == null) {
12525            Slog.w(TAG, "Attempt to delete null packageName.");
12526            return false;
12527        }
12528        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12529        PackageSetting ps;
12530        boolean dataOnly = false;
12531        int removeUser = -1;
12532        int appId = -1;
12533        synchronized (mPackages) {
12534            ps = mSettings.mPackages.get(packageName);
12535            if (ps == null) {
12536                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12537                return false;
12538            }
12539            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12540                    && user.getIdentifier() != UserHandle.USER_ALL) {
12541                // The caller is asking that the package only be deleted for a single
12542                // user.  To do this, we just mark its uninstalled state and delete
12543                // its data.  If this is a system app, we only allow this to happen if
12544                // they have set the special DELETE_SYSTEM_APP which requests different
12545                // semantics than normal for uninstalling system apps.
12546                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12547                ps.setUserState(user.getIdentifier(),
12548                        COMPONENT_ENABLED_STATE_DEFAULT,
12549                        false, //installed
12550                        true,  //stopped
12551                        true,  //notLaunched
12552                        false, //hidden
12553                        null, null, null,
12554                        false, // blockUninstall
12555                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12556                if (!isSystemApp(ps)) {
12557                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12558                        // Other user still have this package installed, so all
12559                        // we need to do is clear this user's data and save that
12560                        // it is uninstalled.
12561                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12562                        removeUser = user.getIdentifier();
12563                        appId = ps.appId;
12564                        scheduleWritePackageRestrictionsLocked(removeUser);
12565                    } else {
12566                        // We need to set it back to 'installed' so the uninstall
12567                        // broadcasts will be sent correctly.
12568                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12569                        ps.setInstalled(true, user.getIdentifier());
12570                    }
12571                } else {
12572                    // This is a system app, so we assume that the
12573                    // other users still have this package installed, so all
12574                    // we need to do is clear this user's data and save that
12575                    // it is uninstalled.
12576                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12577                    removeUser = user.getIdentifier();
12578                    appId = ps.appId;
12579                    scheduleWritePackageRestrictionsLocked(removeUser);
12580                }
12581            }
12582        }
12583
12584        if (removeUser >= 0) {
12585            // From above, we determined that we are deleting this only
12586            // for a single user.  Continue the work here.
12587            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12588            if (outInfo != null) {
12589                outInfo.removedPackage = packageName;
12590                outInfo.removedAppId = appId;
12591                outInfo.removedUsers = new int[] {removeUser};
12592            }
12593            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12594            removeKeystoreDataIfNeeded(removeUser, appId);
12595            schedulePackageCleaning(packageName, removeUser, false);
12596            synchronized (mPackages) {
12597                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12598                    scheduleWritePackageRestrictionsLocked(removeUser);
12599                }
12600                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12601                        removeUser);
12602            }
12603            return true;
12604        }
12605
12606        if (dataOnly) {
12607            // Delete application data first
12608            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12609            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12610            return true;
12611        }
12612
12613        boolean ret = false;
12614        if (isSystemApp(ps)) {
12615            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12616            // When an updated system application is deleted we delete the existing resources as well and
12617            // fall back to existing code in system partition
12618            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12619                    flags, outInfo, writeSettings);
12620        } else {
12621            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12622            // Kill application pre-emptively especially for apps on sd.
12623            killApplication(packageName, ps.appId, "uninstall pkg");
12624            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12625                    allUserHandles, perUserInstalled,
12626                    outInfo, writeSettings);
12627        }
12628
12629        return ret;
12630    }
12631
12632    private final class ClearStorageConnection implements ServiceConnection {
12633        IMediaContainerService mContainerService;
12634
12635        @Override
12636        public void onServiceConnected(ComponentName name, IBinder service) {
12637            synchronized (this) {
12638                mContainerService = IMediaContainerService.Stub.asInterface(service);
12639                notifyAll();
12640            }
12641        }
12642
12643        @Override
12644        public void onServiceDisconnected(ComponentName name) {
12645        }
12646    }
12647
12648    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12649        final boolean mounted;
12650        if (Environment.isExternalStorageEmulated()) {
12651            mounted = true;
12652        } else {
12653            final String status = Environment.getExternalStorageState();
12654
12655            mounted = status.equals(Environment.MEDIA_MOUNTED)
12656                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12657        }
12658
12659        if (!mounted) {
12660            return;
12661        }
12662
12663        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12664        int[] users;
12665        if (userId == UserHandle.USER_ALL) {
12666            users = sUserManager.getUserIds();
12667        } else {
12668            users = new int[] { userId };
12669        }
12670        final ClearStorageConnection conn = new ClearStorageConnection();
12671        if (mContext.bindServiceAsUser(
12672                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12673            try {
12674                for (int curUser : users) {
12675                    long timeout = SystemClock.uptimeMillis() + 5000;
12676                    synchronized (conn) {
12677                        long now = SystemClock.uptimeMillis();
12678                        while (conn.mContainerService == null && now < timeout) {
12679                            try {
12680                                conn.wait(timeout - now);
12681                            } catch (InterruptedException e) {
12682                            }
12683                        }
12684                    }
12685                    if (conn.mContainerService == null) {
12686                        return;
12687                    }
12688
12689                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12690                    clearDirectory(conn.mContainerService,
12691                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12692                    if (allData) {
12693                        clearDirectory(conn.mContainerService,
12694                                userEnv.buildExternalStorageAppDataDirs(packageName));
12695                        clearDirectory(conn.mContainerService,
12696                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12697                    }
12698                }
12699            } finally {
12700                mContext.unbindService(conn);
12701            }
12702        }
12703    }
12704
12705    @Override
12706    public void clearApplicationUserData(final String packageName,
12707            final IPackageDataObserver observer, final int userId) {
12708        mContext.enforceCallingOrSelfPermission(
12709                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12710        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12711        // Queue up an async operation since the package deletion may take a little while.
12712        mHandler.post(new Runnable() {
12713            public void run() {
12714                mHandler.removeCallbacks(this);
12715                final boolean succeeded;
12716                synchronized (mInstallLock) {
12717                    succeeded = clearApplicationUserDataLI(packageName, userId);
12718                }
12719                clearExternalStorageDataSync(packageName, userId, true);
12720                if (succeeded) {
12721                    // invoke DeviceStorageMonitor's update method to clear any notifications
12722                    DeviceStorageMonitorInternal
12723                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12724                    if (dsm != null) {
12725                        dsm.checkMemory();
12726                    }
12727                }
12728                if(observer != null) {
12729                    try {
12730                        observer.onRemoveCompleted(packageName, succeeded);
12731                    } catch (RemoteException e) {
12732                        Log.i(TAG, "Observer no longer exists.");
12733                    }
12734                } //end if observer
12735            } //end run
12736        });
12737    }
12738
12739    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12740        if (packageName == null) {
12741            Slog.w(TAG, "Attempt to delete null packageName.");
12742            return false;
12743        }
12744
12745        // Try finding details about the requested package
12746        PackageParser.Package pkg;
12747        synchronized (mPackages) {
12748            pkg = mPackages.get(packageName);
12749            if (pkg == null) {
12750                final PackageSetting ps = mSettings.mPackages.get(packageName);
12751                if (ps != null) {
12752                    pkg = ps.pkg;
12753                }
12754            }
12755
12756            if (pkg == null) {
12757                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12758                return false;
12759            }
12760
12761            PackageSetting ps = (PackageSetting) pkg.mExtras;
12762            PermissionsState permissionsState = ps.getPermissionsState();
12763            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
12764        }
12765
12766        // Always delete data directories for package, even if we found no other
12767        // record of app. This helps users recover from UID mismatches without
12768        // resorting to a full data wipe.
12769        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12770        if (retCode < 0) {
12771            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12772            return false;
12773        }
12774
12775        final int appId = pkg.applicationInfo.uid;
12776        removeKeystoreDataIfNeeded(userId, appId);
12777
12778        // Create a native library symlink only if we have native libraries
12779        // and if the native libraries are 32 bit libraries. We do not provide
12780        // this symlink for 64 bit libraries.
12781        if (pkg.applicationInfo.primaryCpuAbi != null &&
12782                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12783            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12784            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12785                    nativeLibPath, userId) < 0) {
12786                Slog.w(TAG, "Failed linking native library dir");
12787                return false;
12788            }
12789        }
12790
12791        return true;
12792    }
12793
12794
12795    /**
12796     * Revokes granted runtime permissions and clears resettable flags
12797     * which are flags that can be set by a user interaction.
12798     *
12799     * @param permissionsState The permission state to reset.
12800     * @param userId The device user for which to do a reset.
12801     */
12802    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
12803            PermissionsState permissionsState, int userId) {
12804        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
12805                | PackageManager.FLAG_PERMISSION_USER_FIXED
12806                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12807
12808        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
12809    }
12810
12811    /**
12812     * Revokes granted runtime permissions and clears all flags.
12813     *
12814     * @param permissionsState The permission state to reset.
12815     * @param userId The device user for which to do a reset.
12816     */
12817    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
12818            PermissionsState permissionsState, int userId) {
12819        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
12820                PackageManager.MASK_PERMISSION_FLAGS);
12821    }
12822
12823    /**
12824     * Revokes granted runtime permissions and clears certain flags.
12825     *
12826     * @param permissionsState The permission state to reset.
12827     * @param userId The device user for which to do a reset.
12828     * @param flags The flags that is going to be reset.
12829     */
12830    private void revokeRuntimePermissionsAndClearFlagsLocked(
12831            PermissionsState permissionsState, int userId, int flags) {
12832        boolean needsWrite = false;
12833
12834        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
12835            BasePermission bp = mSettings.mPermissions.get(state.getName());
12836            if (bp != null) {
12837                permissionsState.revokeRuntimePermission(bp, userId);
12838                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
12839                needsWrite = true;
12840            }
12841        }
12842
12843        // Ensure default permissions are never cleared.
12844        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
12845
12846        if (needsWrite) {
12847            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
12848        }
12849    }
12850
12851    /**
12852     * Remove entries from the keystore daemon. Will only remove it if the
12853     * {@code appId} is valid.
12854     */
12855    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12856        if (appId < 0) {
12857            return;
12858        }
12859
12860        final KeyStore keyStore = KeyStore.getInstance();
12861        if (keyStore != null) {
12862            if (userId == UserHandle.USER_ALL) {
12863                for (final int individual : sUserManager.getUserIds()) {
12864                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12865                }
12866            } else {
12867                keyStore.clearUid(UserHandle.getUid(userId, appId));
12868            }
12869        } else {
12870            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12871        }
12872    }
12873
12874    @Override
12875    public void deleteApplicationCacheFiles(final String packageName,
12876            final IPackageDataObserver observer) {
12877        mContext.enforceCallingOrSelfPermission(
12878                android.Manifest.permission.DELETE_CACHE_FILES, null);
12879        // Queue up an async operation since the package deletion may take a little while.
12880        final int userId = UserHandle.getCallingUserId();
12881        mHandler.post(new Runnable() {
12882            public void run() {
12883                mHandler.removeCallbacks(this);
12884                final boolean succeded;
12885                synchronized (mInstallLock) {
12886                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12887                }
12888                clearExternalStorageDataSync(packageName, userId, false);
12889                if (observer != null) {
12890                    try {
12891                        observer.onRemoveCompleted(packageName, succeded);
12892                    } catch (RemoteException e) {
12893                        Log.i(TAG, "Observer no longer exists.");
12894                    }
12895                } //end if observer
12896            } //end run
12897        });
12898    }
12899
12900    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12901        if (packageName == null) {
12902            Slog.w(TAG, "Attempt to delete null packageName.");
12903            return false;
12904        }
12905        PackageParser.Package p;
12906        synchronized (mPackages) {
12907            p = mPackages.get(packageName);
12908        }
12909        if (p == null) {
12910            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12911            return false;
12912        }
12913        final ApplicationInfo applicationInfo = p.applicationInfo;
12914        if (applicationInfo == null) {
12915            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12916            return false;
12917        }
12918        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12919        if (retCode < 0) {
12920            Slog.w(TAG, "Couldn't remove cache files for package: "
12921                       + packageName + " u" + userId);
12922            return false;
12923        }
12924        return true;
12925    }
12926
12927    @Override
12928    public void getPackageSizeInfo(final String packageName, int userHandle,
12929            final IPackageStatsObserver observer) {
12930        mContext.enforceCallingOrSelfPermission(
12931                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12932        if (packageName == null) {
12933            throw new IllegalArgumentException("Attempt to get size of null packageName");
12934        }
12935
12936        PackageStats stats = new PackageStats(packageName, userHandle);
12937
12938        /*
12939         * Queue up an async operation since the package measurement may take a
12940         * little while.
12941         */
12942        Message msg = mHandler.obtainMessage(INIT_COPY);
12943        msg.obj = new MeasureParams(stats, observer);
12944        mHandler.sendMessage(msg);
12945    }
12946
12947    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12948            PackageStats pStats) {
12949        if (packageName == null) {
12950            Slog.w(TAG, "Attempt to get size of null packageName.");
12951            return false;
12952        }
12953        PackageParser.Package p;
12954        boolean dataOnly = false;
12955        String libDirRoot = null;
12956        String asecPath = null;
12957        PackageSetting ps = null;
12958        synchronized (mPackages) {
12959            p = mPackages.get(packageName);
12960            ps = mSettings.mPackages.get(packageName);
12961            if(p == null) {
12962                dataOnly = true;
12963                if((ps == null) || (ps.pkg == null)) {
12964                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12965                    return false;
12966                }
12967                p = ps.pkg;
12968            }
12969            if (ps != null) {
12970                libDirRoot = ps.legacyNativeLibraryPathString;
12971            }
12972            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12973                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12974                if (secureContainerId != null) {
12975                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12976                }
12977            }
12978        }
12979        String publicSrcDir = null;
12980        if(!dataOnly) {
12981            final ApplicationInfo applicationInfo = p.applicationInfo;
12982            if (applicationInfo == null) {
12983                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12984                return false;
12985            }
12986            if (p.isForwardLocked()) {
12987                publicSrcDir = applicationInfo.getBaseResourcePath();
12988            }
12989        }
12990        // TODO: extend to measure size of split APKs
12991        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12992        // not just the first level.
12993        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12994        // just the primary.
12995        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12996        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
12997                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12998        if (res < 0) {
12999            return false;
13000        }
13001
13002        // Fix-up for forward-locked applications in ASEC containers.
13003        if (!isExternal(p)) {
13004            pStats.codeSize += pStats.externalCodeSize;
13005            pStats.externalCodeSize = 0L;
13006        }
13007
13008        return true;
13009    }
13010
13011
13012    @Override
13013    public void addPackageToPreferred(String packageName) {
13014        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13015    }
13016
13017    @Override
13018    public void removePackageFromPreferred(String packageName) {
13019        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13020    }
13021
13022    @Override
13023    public List<PackageInfo> getPreferredPackages(int flags) {
13024        return new ArrayList<PackageInfo>();
13025    }
13026
13027    private int getUidTargetSdkVersionLockedLPr(int uid) {
13028        Object obj = mSettings.getUserIdLPr(uid);
13029        if (obj instanceof SharedUserSetting) {
13030            final SharedUserSetting sus = (SharedUserSetting) obj;
13031            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13032            final Iterator<PackageSetting> it = sus.packages.iterator();
13033            while (it.hasNext()) {
13034                final PackageSetting ps = it.next();
13035                if (ps.pkg != null) {
13036                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13037                    if (v < vers) vers = v;
13038                }
13039            }
13040            return vers;
13041        } else if (obj instanceof PackageSetting) {
13042            final PackageSetting ps = (PackageSetting) obj;
13043            if (ps.pkg != null) {
13044                return ps.pkg.applicationInfo.targetSdkVersion;
13045            }
13046        }
13047        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13048    }
13049
13050    @Override
13051    public void addPreferredActivity(IntentFilter filter, int match,
13052            ComponentName[] set, ComponentName activity, int userId) {
13053        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13054                "Adding preferred");
13055    }
13056
13057    private void addPreferredActivityInternal(IntentFilter filter, int match,
13058            ComponentName[] set, ComponentName activity, boolean always, int userId,
13059            String opname) {
13060        // writer
13061        int callingUid = Binder.getCallingUid();
13062        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13063        if (filter.countActions() == 0) {
13064            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13065            return;
13066        }
13067        synchronized (mPackages) {
13068            if (mContext.checkCallingOrSelfPermission(
13069                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13070                    != PackageManager.PERMISSION_GRANTED) {
13071                if (getUidTargetSdkVersionLockedLPr(callingUid)
13072                        < Build.VERSION_CODES.FROYO) {
13073                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13074                            + callingUid);
13075                    return;
13076                }
13077                mContext.enforceCallingOrSelfPermission(
13078                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13079            }
13080
13081            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13082            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13083                    + userId + ":");
13084            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13085            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13086            scheduleWritePackageRestrictionsLocked(userId);
13087        }
13088    }
13089
13090    @Override
13091    public void replacePreferredActivity(IntentFilter filter, int match,
13092            ComponentName[] set, ComponentName activity, int userId) {
13093        if (filter.countActions() != 1) {
13094            throw new IllegalArgumentException(
13095                    "replacePreferredActivity expects filter to have only 1 action.");
13096        }
13097        if (filter.countDataAuthorities() != 0
13098                || filter.countDataPaths() != 0
13099                || filter.countDataSchemes() > 1
13100                || filter.countDataTypes() != 0) {
13101            throw new IllegalArgumentException(
13102                    "replacePreferredActivity expects filter to have no data authorities, " +
13103                    "paths, or types; and at most one scheme.");
13104        }
13105
13106        final int callingUid = Binder.getCallingUid();
13107        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13108        synchronized (mPackages) {
13109            if (mContext.checkCallingOrSelfPermission(
13110                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13111                    != PackageManager.PERMISSION_GRANTED) {
13112                if (getUidTargetSdkVersionLockedLPr(callingUid)
13113                        < Build.VERSION_CODES.FROYO) {
13114                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13115                            + Binder.getCallingUid());
13116                    return;
13117                }
13118                mContext.enforceCallingOrSelfPermission(
13119                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13120            }
13121
13122            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13123            if (pir != null) {
13124                // Get all of the existing entries that exactly match this filter.
13125                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13126                if (existing != null && existing.size() == 1) {
13127                    PreferredActivity cur = existing.get(0);
13128                    if (DEBUG_PREFERRED) {
13129                        Slog.i(TAG, "Checking replace of preferred:");
13130                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13131                        if (!cur.mPref.mAlways) {
13132                            Slog.i(TAG, "  -- CUR; not mAlways!");
13133                        } else {
13134                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13135                            Slog.i(TAG, "  -- CUR: mSet="
13136                                    + Arrays.toString(cur.mPref.mSetComponents));
13137                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13138                            Slog.i(TAG, "  -- NEW: mMatch="
13139                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13140                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13141                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13142                        }
13143                    }
13144                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13145                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13146                            && cur.mPref.sameSet(set)) {
13147                        // Setting the preferred activity to what it happens to be already
13148                        if (DEBUG_PREFERRED) {
13149                            Slog.i(TAG, "Replacing with same preferred activity "
13150                                    + cur.mPref.mShortComponent + " for user "
13151                                    + userId + ":");
13152                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13153                        }
13154                        return;
13155                    }
13156                }
13157
13158                if (existing != null) {
13159                    if (DEBUG_PREFERRED) {
13160                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13161                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13162                    }
13163                    for (int i = 0; i < existing.size(); i++) {
13164                        PreferredActivity pa = existing.get(i);
13165                        if (DEBUG_PREFERRED) {
13166                            Slog.i(TAG, "Removing existing preferred activity "
13167                                    + pa.mPref.mComponent + ":");
13168                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13169                        }
13170                        pir.removeFilter(pa);
13171                    }
13172                }
13173            }
13174            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13175                    "Replacing preferred");
13176        }
13177    }
13178
13179    @Override
13180    public void clearPackagePreferredActivities(String packageName) {
13181        final int uid = Binder.getCallingUid();
13182        // writer
13183        synchronized (mPackages) {
13184            PackageParser.Package pkg = mPackages.get(packageName);
13185            if (pkg == null || pkg.applicationInfo.uid != uid) {
13186                if (mContext.checkCallingOrSelfPermission(
13187                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13188                        != PackageManager.PERMISSION_GRANTED) {
13189                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13190                            < Build.VERSION_CODES.FROYO) {
13191                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13192                                + Binder.getCallingUid());
13193                        return;
13194                    }
13195                    mContext.enforceCallingOrSelfPermission(
13196                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13197                }
13198            }
13199
13200            int user = UserHandle.getCallingUserId();
13201            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13202                scheduleWritePackageRestrictionsLocked(user);
13203            }
13204        }
13205    }
13206
13207    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13208    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13209        ArrayList<PreferredActivity> removed = null;
13210        boolean changed = false;
13211        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13212            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13213            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13214            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13215                continue;
13216            }
13217            Iterator<PreferredActivity> it = pir.filterIterator();
13218            while (it.hasNext()) {
13219                PreferredActivity pa = it.next();
13220                // Mark entry for removal only if it matches the package name
13221                // and the entry is of type "always".
13222                if (packageName == null ||
13223                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13224                                && pa.mPref.mAlways)) {
13225                    if (removed == null) {
13226                        removed = new ArrayList<PreferredActivity>();
13227                    }
13228                    removed.add(pa);
13229                }
13230            }
13231            if (removed != null) {
13232                for (int j=0; j<removed.size(); j++) {
13233                    PreferredActivity pa = removed.get(j);
13234                    pir.removeFilter(pa);
13235                }
13236                changed = true;
13237            }
13238        }
13239        return changed;
13240    }
13241
13242    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13243    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13244        if (userId == UserHandle.USER_ALL) {
13245            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13246                    sUserManager.getUserIds())) {
13247                for (int oneUserId : sUserManager.getUserIds()) {
13248                    scheduleWritePackageRestrictionsLocked(oneUserId);
13249                }
13250            }
13251        } else {
13252            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13253                scheduleWritePackageRestrictionsLocked(userId);
13254            }
13255        }
13256    }
13257
13258
13259    void clearDefaultBrowserIfNeeded(String packageName) {
13260        for (int oneUserId : sUserManager.getUserIds()) {
13261            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13262            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13263            if (packageName.equals(defaultBrowserPackageName)) {
13264                setDefaultBrowserPackageName(null, oneUserId);
13265            }
13266        }
13267    }
13268
13269    @Override
13270    public void resetPreferredActivities(int userId) {
13271        /* TODO: Actually use userId. Why is it being passed in? */
13272        mContext.enforceCallingOrSelfPermission(
13273                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13274        // writer
13275        synchronized (mPackages) {
13276            int user = UserHandle.getCallingUserId();
13277            clearPackagePreferredActivitiesLPw(null, user);
13278            mSettings.readDefaultPreferredAppsLPw(this, user);
13279            scheduleWritePackageRestrictionsLocked(user);
13280        }
13281    }
13282
13283    @Override
13284    public int getPreferredActivities(List<IntentFilter> outFilters,
13285            List<ComponentName> outActivities, String packageName) {
13286
13287        int num = 0;
13288        final int userId = UserHandle.getCallingUserId();
13289        // reader
13290        synchronized (mPackages) {
13291            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13292            if (pir != null) {
13293                final Iterator<PreferredActivity> it = pir.filterIterator();
13294                while (it.hasNext()) {
13295                    final PreferredActivity pa = it.next();
13296                    if (packageName == null
13297                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13298                                    && pa.mPref.mAlways)) {
13299                        if (outFilters != null) {
13300                            outFilters.add(new IntentFilter(pa));
13301                        }
13302                        if (outActivities != null) {
13303                            outActivities.add(pa.mPref.mComponent);
13304                        }
13305                    }
13306                }
13307            }
13308        }
13309
13310        return num;
13311    }
13312
13313    @Override
13314    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13315            int userId) {
13316        int callingUid = Binder.getCallingUid();
13317        if (callingUid != Process.SYSTEM_UID) {
13318            throw new SecurityException(
13319                    "addPersistentPreferredActivity can only be run by the system");
13320        }
13321        if (filter.countActions() == 0) {
13322            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13323            return;
13324        }
13325        synchronized (mPackages) {
13326            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13327                    " :");
13328            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13329            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13330                    new PersistentPreferredActivity(filter, activity));
13331            scheduleWritePackageRestrictionsLocked(userId);
13332        }
13333    }
13334
13335    @Override
13336    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13337        int callingUid = Binder.getCallingUid();
13338        if (callingUid != Process.SYSTEM_UID) {
13339            throw new SecurityException(
13340                    "clearPackagePersistentPreferredActivities can only be run by the system");
13341        }
13342        ArrayList<PersistentPreferredActivity> removed = null;
13343        boolean changed = false;
13344        synchronized (mPackages) {
13345            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13346                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13347                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13348                        .valueAt(i);
13349                if (userId != thisUserId) {
13350                    continue;
13351                }
13352                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13353                while (it.hasNext()) {
13354                    PersistentPreferredActivity ppa = it.next();
13355                    // Mark entry for removal only if it matches the package name.
13356                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13357                        if (removed == null) {
13358                            removed = new ArrayList<PersistentPreferredActivity>();
13359                        }
13360                        removed.add(ppa);
13361                    }
13362                }
13363                if (removed != null) {
13364                    for (int j=0; j<removed.size(); j++) {
13365                        PersistentPreferredActivity ppa = removed.get(j);
13366                        ppir.removeFilter(ppa);
13367                    }
13368                    changed = true;
13369                }
13370            }
13371
13372            if (changed) {
13373                scheduleWritePackageRestrictionsLocked(userId);
13374            }
13375        }
13376    }
13377
13378    /**
13379     * Non-Binder method, support for the backup/restore mechanism: write the
13380     * full set of preferred activities in its canonical XML format.  Returns true
13381     * on success; false otherwise.
13382     */
13383    @Override
13384    public byte[] getPreferredActivityBackup(int userId) {
13385        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13386            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13387        }
13388
13389        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13390        try {
13391            final XmlSerializer serializer = new FastXmlSerializer();
13392            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13393            serializer.startDocument(null, true);
13394            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13395
13396            synchronized (mPackages) {
13397                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13398            }
13399
13400            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13401            serializer.endDocument();
13402            serializer.flush();
13403        } catch (Exception e) {
13404            if (DEBUG_BACKUP) {
13405                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13406            }
13407            return null;
13408        }
13409
13410        return dataStream.toByteArray();
13411    }
13412
13413    @Override
13414    public void restorePreferredActivities(byte[] backup, int userId) {
13415        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13416            throw new SecurityException("Only the system may call restorePreferredActivities()");
13417        }
13418
13419        try {
13420            final XmlPullParser parser = Xml.newPullParser();
13421            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13422
13423            int type;
13424            while ((type = parser.next()) != XmlPullParser.START_TAG
13425                    && type != XmlPullParser.END_DOCUMENT) {
13426            }
13427            if (type != XmlPullParser.START_TAG) {
13428                // oops didn't find a start tag?!
13429                if (DEBUG_BACKUP) {
13430                    Slog.e(TAG, "Didn't find start tag during restore");
13431                }
13432                return;
13433            }
13434
13435            // this is supposed to be TAG_PREFERRED_BACKUP
13436            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
13437                if (DEBUG_BACKUP) {
13438                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
13439                }
13440                return;
13441            }
13442
13443            // skip interfering stuff, then we're aligned with the backing implementation
13444            while ((type = parser.next()) == XmlPullParser.TEXT) { }
13445            synchronized (mPackages) {
13446                mSettings.readPreferredActivitiesLPw(parser, userId);
13447            }
13448        } catch (Exception e) {
13449            if (DEBUG_BACKUP) {
13450                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13451            }
13452        }
13453    }
13454
13455    @Override
13456    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13457            int sourceUserId, int targetUserId, int flags) {
13458        mContext.enforceCallingOrSelfPermission(
13459                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13460        int callingUid = Binder.getCallingUid();
13461        enforceOwnerRights(ownerPackage, callingUid);
13462        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13463        if (intentFilter.countActions() == 0) {
13464            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13465            return;
13466        }
13467        synchronized (mPackages) {
13468            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13469                    ownerPackage, targetUserId, flags);
13470            CrossProfileIntentResolver resolver =
13471                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13472            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13473            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13474            if (existing != null) {
13475                int size = existing.size();
13476                for (int i = 0; i < size; i++) {
13477                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13478                        return;
13479                    }
13480                }
13481            }
13482            resolver.addFilter(newFilter);
13483            scheduleWritePackageRestrictionsLocked(sourceUserId);
13484        }
13485    }
13486
13487    @Override
13488    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13489        mContext.enforceCallingOrSelfPermission(
13490                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13491        int callingUid = Binder.getCallingUid();
13492        enforceOwnerRights(ownerPackage, callingUid);
13493        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13494        synchronized (mPackages) {
13495            CrossProfileIntentResolver resolver =
13496                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13497            ArraySet<CrossProfileIntentFilter> set =
13498                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13499            for (CrossProfileIntentFilter filter : set) {
13500                if (filter.getOwnerPackage().equals(ownerPackage)) {
13501                    resolver.removeFilter(filter);
13502                }
13503            }
13504            scheduleWritePackageRestrictionsLocked(sourceUserId);
13505        }
13506    }
13507
13508    // Enforcing that callingUid is owning pkg on userId
13509    private void enforceOwnerRights(String pkg, int callingUid) {
13510        // The system owns everything.
13511        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13512            return;
13513        }
13514        int callingUserId = UserHandle.getUserId(callingUid);
13515        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13516        if (pi == null) {
13517            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13518                    + callingUserId);
13519        }
13520        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13521            throw new SecurityException("Calling uid " + callingUid
13522                    + " does not own package " + pkg);
13523        }
13524    }
13525
13526    @Override
13527    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13528        Intent intent = new Intent(Intent.ACTION_MAIN);
13529        intent.addCategory(Intent.CATEGORY_HOME);
13530
13531        final int callingUserId = UserHandle.getCallingUserId();
13532        List<ResolveInfo> list = queryIntentActivities(intent, null,
13533                PackageManager.GET_META_DATA, callingUserId);
13534        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13535                true, false, false, callingUserId);
13536
13537        allHomeCandidates.clear();
13538        if (list != null) {
13539            for (ResolveInfo ri : list) {
13540                allHomeCandidates.add(ri);
13541            }
13542        }
13543        return (preferred == null || preferred.activityInfo == null)
13544                ? null
13545                : new ComponentName(preferred.activityInfo.packageName,
13546                        preferred.activityInfo.name);
13547    }
13548
13549    @Override
13550    public void setApplicationEnabledSetting(String appPackageName,
13551            int newState, int flags, int userId, String callingPackage) {
13552        if (!sUserManager.exists(userId)) return;
13553        if (callingPackage == null) {
13554            callingPackage = Integer.toString(Binder.getCallingUid());
13555        }
13556        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13557    }
13558
13559    @Override
13560    public void setComponentEnabledSetting(ComponentName componentName,
13561            int newState, int flags, int userId) {
13562        if (!sUserManager.exists(userId)) return;
13563        setEnabledSetting(componentName.getPackageName(),
13564                componentName.getClassName(), newState, flags, userId, null);
13565    }
13566
13567    private void setEnabledSetting(final String packageName, String className, int newState,
13568            final int flags, int userId, String callingPackage) {
13569        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13570              || newState == COMPONENT_ENABLED_STATE_ENABLED
13571              || newState == COMPONENT_ENABLED_STATE_DISABLED
13572              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13573              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13574            throw new IllegalArgumentException("Invalid new component state: "
13575                    + newState);
13576        }
13577        PackageSetting pkgSetting;
13578        final int uid = Binder.getCallingUid();
13579        final int permission = mContext.checkCallingOrSelfPermission(
13580                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13581        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13582        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13583        boolean sendNow = false;
13584        boolean isApp = (className == null);
13585        String componentName = isApp ? packageName : className;
13586        int packageUid = -1;
13587        ArrayList<String> components;
13588
13589        // writer
13590        synchronized (mPackages) {
13591            pkgSetting = mSettings.mPackages.get(packageName);
13592            if (pkgSetting == null) {
13593                if (className == null) {
13594                    throw new IllegalArgumentException(
13595                            "Unknown package: " + packageName);
13596                }
13597                throw new IllegalArgumentException(
13598                        "Unknown component: " + packageName
13599                        + "/" + className);
13600            }
13601            // Allow root and verify that userId is not being specified by a different user
13602            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13603                throw new SecurityException(
13604                        "Permission Denial: attempt to change component state from pid="
13605                        + Binder.getCallingPid()
13606                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13607            }
13608            if (className == null) {
13609                // We're dealing with an application/package level state change
13610                if (pkgSetting.getEnabled(userId) == newState) {
13611                    // Nothing to do
13612                    return;
13613                }
13614                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13615                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13616                    // Don't care about who enables an app.
13617                    callingPackage = null;
13618                }
13619                pkgSetting.setEnabled(newState, userId, callingPackage);
13620                // pkgSetting.pkg.mSetEnabled = newState;
13621            } else {
13622                // We're dealing with a component level state change
13623                // First, verify that this is a valid class name.
13624                PackageParser.Package pkg = pkgSetting.pkg;
13625                if (pkg == null || !pkg.hasComponentClassName(className)) {
13626                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13627                        throw new IllegalArgumentException("Component class " + className
13628                                + " does not exist in " + packageName);
13629                    } else {
13630                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13631                                + className + " does not exist in " + packageName);
13632                    }
13633                }
13634                switch (newState) {
13635                case COMPONENT_ENABLED_STATE_ENABLED:
13636                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13637                        return;
13638                    }
13639                    break;
13640                case COMPONENT_ENABLED_STATE_DISABLED:
13641                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13642                        return;
13643                    }
13644                    break;
13645                case COMPONENT_ENABLED_STATE_DEFAULT:
13646                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13647                        return;
13648                    }
13649                    break;
13650                default:
13651                    Slog.e(TAG, "Invalid new component state: " + newState);
13652                    return;
13653                }
13654            }
13655            scheduleWritePackageRestrictionsLocked(userId);
13656            components = mPendingBroadcasts.get(userId, packageName);
13657            final boolean newPackage = components == null;
13658            if (newPackage) {
13659                components = new ArrayList<String>();
13660            }
13661            if (!components.contains(componentName)) {
13662                components.add(componentName);
13663            }
13664            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13665                sendNow = true;
13666                // Purge entry from pending broadcast list if another one exists already
13667                // since we are sending one right away.
13668                mPendingBroadcasts.remove(userId, packageName);
13669            } else {
13670                if (newPackage) {
13671                    mPendingBroadcasts.put(userId, packageName, components);
13672                }
13673                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13674                    // Schedule a message
13675                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13676                }
13677            }
13678        }
13679
13680        long callingId = Binder.clearCallingIdentity();
13681        try {
13682            if (sendNow) {
13683                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13684                sendPackageChangedBroadcast(packageName,
13685                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13686            }
13687        } finally {
13688            Binder.restoreCallingIdentity(callingId);
13689        }
13690    }
13691
13692    private void sendPackageChangedBroadcast(String packageName,
13693            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13694        if (DEBUG_INSTALL)
13695            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13696                    + componentNames);
13697        Bundle extras = new Bundle(4);
13698        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13699        String nameList[] = new String[componentNames.size()];
13700        componentNames.toArray(nameList);
13701        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13702        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13703        extras.putInt(Intent.EXTRA_UID, packageUid);
13704        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13705                new int[] {UserHandle.getUserId(packageUid)});
13706    }
13707
13708    @Override
13709    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13710        if (!sUserManager.exists(userId)) return;
13711        final int uid = Binder.getCallingUid();
13712        final int permission = mContext.checkCallingOrSelfPermission(
13713                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13714        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13715        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13716        // writer
13717        synchronized (mPackages) {
13718            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13719                    allowedByPermission, uid, userId)) {
13720                scheduleWritePackageRestrictionsLocked(userId);
13721            }
13722        }
13723    }
13724
13725    @Override
13726    public String getInstallerPackageName(String packageName) {
13727        // reader
13728        synchronized (mPackages) {
13729            return mSettings.getInstallerPackageNameLPr(packageName);
13730        }
13731    }
13732
13733    @Override
13734    public int getApplicationEnabledSetting(String packageName, int userId) {
13735        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13736        int uid = Binder.getCallingUid();
13737        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13738        // reader
13739        synchronized (mPackages) {
13740            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13741        }
13742    }
13743
13744    @Override
13745    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13746        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13747        int uid = Binder.getCallingUid();
13748        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13749        // reader
13750        synchronized (mPackages) {
13751            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13752        }
13753    }
13754
13755    @Override
13756    public void enterSafeMode() {
13757        enforceSystemOrRoot("Only the system can request entering safe mode");
13758
13759        if (!mSystemReady) {
13760            mSafeMode = true;
13761        }
13762    }
13763
13764    @Override
13765    public void systemReady() {
13766        mSystemReady = true;
13767
13768        // Read the compatibilty setting when the system is ready.
13769        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13770                mContext.getContentResolver(),
13771                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13772        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13773        if (DEBUG_SETTINGS) {
13774            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13775        }
13776
13777        synchronized (mPackages) {
13778            // Verify that all of the preferred activity components actually
13779            // exist.  It is possible for applications to be updated and at
13780            // that point remove a previously declared activity component that
13781            // had been set as a preferred activity.  We try to clean this up
13782            // the next time we encounter that preferred activity, but it is
13783            // possible for the user flow to never be able to return to that
13784            // situation so here we do a sanity check to make sure we haven't
13785            // left any junk around.
13786            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13787            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13788                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13789                removed.clear();
13790                for (PreferredActivity pa : pir.filterSet()) {
13791                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13792                        removed.add(pa);
13793                    }
13794                }
13795                if (removed.size() > 0) {
13796                    for (int r=0; r<removed.size(); r++) {
13797                        PreferredActivity pa = removed.get(r);
13798                        Slog.w(TAG, "Removing dangling preferred activity: "
13799                                + pa.mPref.mComponent);
13800                        pir.removeFilter(pa);
13801                    }
13802                    mSettings.writePackageRestrictionsLPr(
13803                            mSettings.mPreferredActivities.keyAt(i));
13804                }
13805            }
13806        }
13807        sUserManager.systemReady();
13808
13809        // If we upgraded grant all default permissions before kicking off.
13810        if (isFirstBoot() || (CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE && mIsUpgrade)) {
13811            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
13812            for (int userId : UserManagerService.getInstance().getUserIds()) {
13813                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
13814            }
13815        }
13816
13817        // Kick off any messages waiting for system ready
13818        if (mPostSystemReadyMessages != null) {
13819            for (Message msg : mPostSystemReadyMessages) {
13820                msg.sendToTarget();
13821            }
13822            mPostSystemReadyMessages = null;
13823        }
13824
13825        // Watch for external volumes that come and go over time
13826        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13827        storage.registerListener(mStorageListener);
13828
13829        mInstallerService.systemReady();
13830        mPackageDexOptimizer.systemReady();
13831    }
13832
13833    @Override
13834    public boolean isSafeMode() {
13835        return mSafeMode;
13836    }
13837
13838    @Override
13839    public boolean hasSystemUidErrors() {
13840        return mHasSystemUidErrors;
13841    }
13842
13843    static String arrayToString(int[] array) {
13844        StringBuffer buf = new StringBuffer(128);
13845        buf.append('[');
13846        if (array != null) {
13847            for (int i=0; i<array.length; i++) {
13848                if (i > 0) buf.append(", ");
13849                buf.append(array[i]);
13850            }
13851        }
13852        buf.append(']');
13853        return buf.toString();
13854    }
13855
13856    static class DumpState {
13857        public static final int DUMP_LIBS = 1 << 0;
13858        public static final int DUMP_FEATURES = 1 << 1;
13859        public static final int DUMP_RESOLVERS = 1 << 2;
13860        public static final int DUMP_PERMISSIONS = 1 << 3;
13861        public static final int DUMP_PACKAGES = 1 << 4;
13862        public static final int DUMP_SHARED_USERS = 1 << 5;
13863        public static final int DUMP_MESSAGES = 1 << 6;
13864        public static final int DUMP_PROVIDERS = 1 << 7;
13865        public static final int DUMP_VERIFIERS = 1 << 8;
13866        public static final int DUMP_PREFERRED = 1 << 9;
13867        public static final int DUMP_PREFERRED_XML = 1 << 10;
13868        public static final int DUMP_KEYSETS = 1 << 11;
13869        public static final int DUMP_VERSION = 1 << 12;
13870        public static final int DUMP_INSTALLS = 1 << 13;
13871        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13872        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13873
13874        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13875
13876        private int mTypes;
13877
13878        private int mOptions;
13879
13880        private boolean mTitlePrinted;
13881
13882        private SharedUserSetting mSharedUser;
13883
13884        public boolean isDumping(int type) {
13885            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13886                return true;
13887            }
13888
13889            return (mTypes & type) != 0;
13890        }
13891
13892        public void setDump(int type) {
13893            mTypes |= type;
13894        }
13895
13896        public boolean isOptionEnabled(int option) {
13897            return (mOptions & option) != 0;
13898        }
13899
13900        public void setOptionEnabled(int option) {
13901            mOptions |= option;
13902        }
13903
13904        public boolean onTitlePrinted() {
13905            final boolean printed = mTitlePrinted;
13906            mTitlePrinted = true;
13907            return printed;
13908        }
13909
13910        public boolean getTitlePrinted() {
13911            return mTitlePrinted;
13912        }
13913
13914        public void setTitlePrinted(boolean enabled) {
13915            mTitlePrinted = enabled;
13916        }
13917
13918        public SharedUserSetting getSharedUser() {
13919            return mSharedUser;
13920        }
13921
13922        public void setSharedUser(SharedUserSetting user) {
13923            mSharedUser = user;
13924        }
13925    }
13926
13927    @Override
13928    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13929        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13930                != PackageManager.PERMISSION_GRANTED) {
13931            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13932                    + Binder.getCallingPid()
13933                    + ", uid=" + Binder.getCallingUid()
13934                    + " without permission "
13935                    + android.Manifest.permission.DUMP);
13936            return;
13937        }
13938
13939        DumpState dumpState = new DumpState();
13940        boolean fullPreferred = false;
13941        boolean checkin = false;
13942
13943        String packageName = null;
13944
13945        int opti = 0;
13946        while (opti < args.length) {
13947            String opt = args[opti];
13948            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13949                break;
13950            }
13951            opti++;
13952
13953            if ("-a".equals(opt)) {
13954                // Right now we only know how to print all.
13955            } else if ("-h".equals(opt)) {
13956                pw.println("Package manager dump options:");
13957                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13958                pw.println("    --checkin: dump for a checkin");
13959                pw.println("    -f: print details of intent filters");
13960                pw.println("    -h: print this help");
13961                pw.println("  cmd may be one of:");
13962                pw.println("    l[ibraries]: list known shared libraries");
13963                pw.println("    f[ibraries]: list device features");
13964                pw.println("    k[eysets]: print known keysets");
13965                pw.println("    r[esolvers]: dump intent resolvers");
13966                pw.println("    perm[issions]: dump permissions");
13967                pw.println("    pref[erred]: print preferred package settings");
13968                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13969                pw.println("    prov[iders]: dump content providers");
13970                pw.println("    p[ackages]: dump installed packages");
13971                pw.println("    s[hared-users]: dump shared user IDs");
13972                pw.println("    m[essages]: print collected runtime messages");
13973                pw.println("    v[erifiers]: print package verifier info");
13974                pw.println("    version: print database version info");
13975                pw.println("    write: write current settings now");
13976                pw.println("    <package.name>: info about given package");
13977                pw.println("    installs: details about install sessions");
13978                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13979                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13980                return;
13981            } else if ("--checkin".equals(opt)) {
13982                checkin = true;
13983            } else if ("-f".equals(opt)) {
13984                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13985            } else {
13986                pw.println("Unknown argument: " + opt + "; use -h for help");
13987            }
13988        }
13989
13990        // Is the caller requesting to dump a particular piece of data?
13991        if (opti < args.length) {
13992            String cmd = args[opti];
13993            opti++;
13994            // Is this a package name?
13995            if ("android".equals(cmd) || cmd.contains(".")) {
13996                packageName = cmd;
13997                // When dumping a single package, we always dump all of its
13998                // filter information since the amount of data will be reasonable.
13999                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14000            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14001                dumpState.setDump(DumpState.DUMP_LIBS);
14002            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14003                dumpState.setDump(DumpState.DUMP_FEATURES);
14004            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14005                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14006            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14007                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14008            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14009                dumpState.setDump(DumpState.DUMP_PREFERRED);
14010            } else if ("preferred-xml".equals(cmd)) {
14011                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14012                if (opti < args.length && "--full".equals(args[opti])) {
14013                    fullPreferred = true;
14014                    opti++;
14015                }
14016            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14017                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14018            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14019                dumpState.setDump(DumpState.DUMP_PACKAGES);
14020            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14021                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14022            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14023                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14024            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14025                dumpState.setDump(DumpState.DUMP_MESSAGES);
14026            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14027                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14028            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14029                    || "intent-filter-verifiers".equals(cmd)) {
14030                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14031            } else if ("version".equals(cmd)) {
14032                dumpState.setDump(DumpState.DUMP_VERSION);
14033            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14034                dumpState.setDump(DumpState.DUMP_KEYSETS);
14035            } else if ("installs".equals(cmd)) {
14036                dumpState.setDump(DumpState.DUMP_INSTALLS);
14037            } else if ("write".equals(cmd)) {
14038                synchronized (mPackages) {
14039                    mSettings.writeLPr();
14040                    pw.println("Settings written.");
14041                    return;
14042                }
14043            }
14044        }
14045
14046        if (checkin) {
14047            pw.println("vers,1");
14048        }
14049
14050        // reader
14051        synchronized (mPackages) {
14052            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14053                if (!checkin) {
14054                    if (dumpState.onTitlePrinted())
14055                        pw.println();
14056                    pw.println("Database versions:");
14057                    pw.print("  SDK Version:");
14058                    pw.print(" internal=");
14059                    pw.print(mSettings.mInternalSdkPlatform);
14060                    pw.print(" external=");
14061                    pw.println(mSettings.mExternalSdkPlatform);
14062                    pw.print("  DB Version:");
14063                    pw.print(" internal=");
14064                    pw.print(mSettings.mInternalDatabaseVersion);
14065                    pw.print(" external=");
14066                    pw.println(mSettings.mExternalDatabaseVersion);
14067                }
14068            }
14069
14070            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14071                if (!checkin) {
14072                    if (dumpState.onTitlePrinted())
14073                        pw.println();
14074                    pw.println("Verifiers:");
14075                    pw.print("  Required: ");
14076                    pw.print(mRequiredVerifierPackage);
14077                    pw.print(" (uid=");
14078                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14079                    pw.println(")");
14080                } else if (mRequiredVerifierPackage != null) {
14081                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14082                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14083                }
14084            }
14085
14086            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14087                    packageName == null) {
14088                if (mIntentFilterVerifierComponent != null) {
14089                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14090                    if (!checkin) {
14091                        if (dumpState.onTitlePrinted())
14092                            pw.println();
14093                        pw.println("Intent Filter Verifier:");
14094                        pw.print("  Using: ");
14095                        pw.print(verifierPackageName);
14096                        pw.print(" (uid=");
14097                        pw.print(getPackageUid(verifierPackageName, 0));
14098                        pw.println(")");
14099                    } else if (verifierPackageName != null) {
14100                        pw.print("ifv,"); pw.print(verifierPackageName);
14101                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14102                    }
14103                } else {
14104                    pw.println();
14105                    pw.println("No Intent Filter Verifier available!");
14106                }
14107            }
14108
14109            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14110                boolean printedHeader = false;
14111                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14112                while (it.hasNext()) {
14113                    String name = it.next();
14114                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14115                    if (!checkin) {
14116                        if (!printedHeader) {
14117                            if (dumpState.onTitlePrinted())
14118                                pw.println();
14119                            pw.println("Libraries:");
14120                            printedHeader = true;
14121                        }
14122                        pw.print("  ");
14123                    } else {
14124                        pw.print("lib,");
14125                    }
14126                    pw.print(name);
14127                    if (!checkin) {
14128                        pw.print(" -> ");
14129                    }
14130                    if (ent.path != null) {
14131                        if (!checkin) {
14132                            pw.print("(jar) ");
14133                            pw.print(ent.path);
14134                        } else {
14135                            pw.print(",jar,");
14136                            pw.print(ent.path);
14137                        }
14138                    } else {
14139                        if (!checkin) {
14140                            pw.print("(apk) ");
14141                            pw.print(ent.apk);
14142                        } else {
14143                            pw.print(",apk,");
14144                            pw.print(ent.apk);
14145                        }
14146                    }
14147                    pw.println();
14148                }
14149            }
14150
14151            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14152                if (dumpState.onTitlePrinted())
14153                    pw.println();
14154                if (!checkin) {
14155                    pw.println("Features:");
14156                }
14157                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14158                while (it.hasNext()) {
14159                    String name = it.next();
14160                    if (!checkin) {
14161                        pw.print("  ");
14162                    } else {
14163                        pw.print("feat,");
14164                    }
14165                    pw.println(name);
14166                }
14167            }
14168
14169            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14170                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14171                        : "Activity Resolver Table:", "  ", packageName,
14172                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14173                    dumpState.setTitlePrinted(true);
14174                }
14175                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14176                        : "Receiver Resolver Table:", "  ", packageName,
14177                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14178                    dumpState.setTitlePrinted(true);
14179                }
14180                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14181                        : "Service Resolver Table:", "  ", packageName,
14182                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14183                    dumpState.setTitlePrinted(true);
14184                }
14185                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14186                        : "Provider Resolver Table:", "  ", packageName,
14187                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14188                    dumpState.setTitlePrinted(true);
14189                }
14190            }
14191
14192            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14193                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14194                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14195                    int user = mSettings.mPreferredActivities.keyAt(i);
14196                    if (pir.dump(pw,
14197                            dumpState.getTitlePrinted()
14198                                ? "\nPreferred Activities User " + user + ":"
14199                                : "Preferred Activities User " + user + ":", "  ",
14200                            packageName, true, false)) {
14201                        dumpState.setTitlePrinted(true);
14202                    }
14203                }
14204            }
14205
14206            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14207                pw.flush();
14208                FileOutputStream fout = new FileOutputStream(fd);
14209                BufferedOutputStream str = new BufferedOutputStream(fout);
14210                XmlSerializer serializer = new FastXmlSerializer();
14211                try {
14212                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14213                    serializer.startDocument(null, true);
14214                    serializer.setFeature(
14215                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14216                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14217                    serializer.endDocument();
14218                    serializer.flush();
14219                } catch (IllegalArgumentException e) {
14220                    pw.println("Failed writing: " + e);
14221                } catch (IllegalStateException e) {
14222                    pw.println("Failed writing: " + e);
14223                } catch (IOException e) {
14224                    pw.println("Failed writing: " + e);
14225                }
14226            }
14227
14228            if (!checkin
14229                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14230                    && packageName == null) {
14231                pw.println();
14232                int count = mSettings.mPackages.size();
14233                if (count == 0) {
14234                    pw.println("No domain preferred apps!");
14235                    pw.println();
14236                } else {
14237                    final String prefix = "  ";
14238                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14239                    if (allPackageSettings.size() == 0) {
14240                        pw.println("No domain preferred apps!");
14241                        pw.println();
14242                    } else {
14243                        pw.println("Domain preferred apps status:");
14244                        pw.println();
14245                        count = 0;
14246                        for (PackageSetting ps : allPackageSettings) {
14247                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14248                            if (ivi == null || ivi.getPackageName() == null) continue;
14249                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14250                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14251                            pw.println(prefix + "Status: " + ivi.getStatusString());
14252                            pw.println();
14253                            count++;
14254                        }
14255                        if (count == 0) {
14256                            pw.println(prefix + "No domain preferred app status!");
14257                            pw.println();
14258                        }
14259                        for (int userId : sUserManager.getUserIds()) {
14260                            pw.println("Domain preferred apps for User " + userId + ":");
14261                            pw.println();
14262                            count = 0;
14263                            for (PackageSetting ps : allPackageSettings) {
14264                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14265                                if (ivi == null || ivi.getPackageName() == null) {
14266                                    continue;
14267                                }
14268                                final int status = ps.getDomainVerificationStatusForUser(userId);
14269                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14270                                    continue;
14271                                }
14272                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14273                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14274                                String statusStr = IntentFilterVerificationInfo.
14275                                        getStatusStringFromValue(status);
14276                                pw.println(prefix + "Status: " + statusStr);
14277                                pw.println();
14278                                count++;
14279                            }
14280                            if (count == 0) {
14281                                pw.println(prefix + "No domain preferred apps!");
14282                                pw.println();
14283                            }
14284                        }
14285                    }
14286                }
14287            }
14288
14289            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14290                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
14291                if (packageName == null) {
14292                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14293                        if (iperm == 0) {
14294                            if (dumpState.onTitlePrinted())
14295                                pw.println();
14296                            pw.println("AppOp Permissions:");
14297                        }
14298                        pw.print("  AppOp Permission ");
14299                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14300                        pw.println(":");
14301                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14302                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14303                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14304                        }
14305                    }
14306                }
14307            }
14308
14309            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14310                boolean printedSomething = false;
14311                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14312                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14313                        continue;
14314                    }
14315                    if (!printedSomething) {
14316                        if (dumpState.onTitlePrinted())
14317                            pw.println();
14318                        pw.println("Registered ContentProviders:");
14319                        printedSomething = true;
14320                    }
14321                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14322                    pw.print("    "); pw.println(p.toString());
14323                }
14324                printedSomething = false;
14325                for (Map.Entry<String, PackageParser.Provider> entry :
14326                        mProvidersByAuthority.entrySet()) {
14327                    PackageParser.Provider p = entry.getValue();
14328                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14329                        continue;
14330                    }
14331                    if (!printedSomething) {
14332                        if (dumpState.onTitlePrinted())
14333                            pw.println();
14334                        pw.println("ContentProvider Authorities:");
14335                        printedSomething = true;
14336                    }
14337                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14338                    pw.print("    "); pw.println(p.toString());
14339                    if (p.info != null && p.info.applicationInfo != null) {
14340                        final String appInfo = p.info.applicationInfo.toString();
14341                        pw.print("      applicationInfo="); pw.println(appInfo);
14342                    }
14343                }
14344            }
14345
14346            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14347                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14348            }
14349
14350            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14351                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
14352            }
14353
14354            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14355                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
14356            }
14357
14358            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14359                // XXX should handle packageName != null by dumping only install data that
14360                // the given package is involved with.
14361                if (dumpState.onTitlePrinted()) pw.println();
14362                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14363            }
14364
14365            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14366                if (dumpState.onTitlePrinted()) pw.println();
14367                mSettings.dumpReadMessagesLPr(pw, dumpState);
14368
14369                pw.println();
14370                pw.println("Package warning messages:");
14371                BufferedReader in = null;
14372                String line = null;
14373                try {
14374                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14375                    while ((line = in.readLine()) != null) {
14376                        if (line.contains("ignored: updated version")) continue;
14377                        pw.println(line);
14378                    }
14379                } catch (IOException ignored) {
14380                } finally {
14381                    IoUtils.closeQuietly(in);
14382                }
14383            }
14384
14385            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14386                BufferedReader in = null;
14387                String line = null;
14388                try {
14389                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14390                    while ((line = in.readLine()) != null) {
14391                        if (line.contains("ignored: updated version")) continue;
14392                        pw.print("msg,");
14393                        pw.println(line);
14394                    }
14395                } catch (IOException ignored) {
14396                } finally {
14397                    IoUtils.closeQuietly(in);
14398                }
14399            }
14400        }
14401    }
14402
14403    // ------- apps on sdcard specific code -------
14404    static final boolean DEBUG_SD_INSTALL = false;
14405
14406    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14407
14408    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14409
14410    private boolean mMediaMounted = false;
14411
14412    static String getEncryptKey() {
14413        try {
14414            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14415                    SD_ENCRYPTION_KEYSTORE_NAME);
14416            if (sdEncKey == null) {
14417                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14418                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14419                if (sdEncKey == null) {
14420                    Slog.e(TAG, "Failed to create encryption keys");
14421                    return null;
14422                }
14423            }
14424            return sdEncKey;
14425        } catch (NoSuchAlgorithmException nsae) {
14426            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14427            return null;
14428        } catch (IOException ioe) {
14429            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14430            return null;
14431        }
14432    }
14433
14434    /*
14435     * Update media status on PackageManager.
14436     */
14437    @Override
14438    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14439        int callingUid = Binder.getCallingUid();
14440        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14441            throw new SecurityException("Media status can only be updated by the system");
14442        }
14443        // reader; this apparently protects mMediaMounted, but should probably
14444        // be a different lock in that case.
14445        synchronized (mPackages) {
14446            Log.i(TAG, "Updating external media status from "
14447                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14448                    + (mediaStatus ? "mounted" : "unmounted"));
14449            if (DEBUG_SD_INSTALL)
14450                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14451                        + ", mMediaMounted=" + mMediaMounted);
14452            if (mediaStatus == mMediaMounted) {
14453                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14454                        : 0, -1);
14455                mHandler.sendMessage(msg);
14456                return;
14457            }
14458            mMediaMounted = mediaStatus;
14459        }
14460        // Queue up an async operation since the package installation may take a
14461        // little while.
14462        mHandler.post(new Runnable() {
14463            public void run() {
14464                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14465            }
14466        });
14467    }
14468
14469    /**
14470     * Called by MountService when the initial ASECs to scan are available.
14471     * Should block until all the ASEC containers are finished being scanned.
14472     */
14473    public void scanAvailableAsecs() {
14474        updateExternalMediaStatusInner(true, false, false);
14475        if (mShouldRestoreconData) {
14476            SELinuxMMAC.setRestoreconDone();
14477            mShouldRestoreconData = false;
14478        }
14479    }
14480
14481    /*
14482     * Collect information of applications on external media, map them against
14483     * existing containers and update information based on current mount status.
14484     * Please note that we always have to report status if reportStatus has been
14485     * set to true especially when unloading packages.
14486     */
14487    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14488            boolean externalStorage) {
14489        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14490        int[] uidArr = EmptyArray.INT;
14491
14492        final String[] list = PackageHelper.getSecureContainerList();
14493        if (ArrayUtils.isEmpty(list)) {
14494            Log.i(TAG, "No secure containers found");
14495        } else {
14496            // Process list of secure containers and categorize them
14497            // as active or stale based on their package internal state.
14498
14499            // reader
14500            synchronized (mPackages) {
14501                for (String cid : list) {
14502                    // Leave stages untouched for now; installer service owns them
14503                    if (PackageInstallerService.isStageName(cid)) continue;
14504
14505                    if (DEBUG_SD_INSTALL)
14506                        Log.i(TAG, "Processing container " + cid);
14507                    String pkgName = getAsecPackageName(cid);
14508                    if (pkgName == null) {
14509                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14510                        continue;
14511                    }
14512                    if (DEBUG_SD_INSTALL)
14513                        Log.i(TAG, "Looking for pkg : " + pkgName);
14514
14515                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14516                    if (ps == null) {
14517                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14518                        continue;
14519                    }
14520
14521                    /*
14522                     * Skip packages that are not external if we're unmounting
14523                     * external storage.
14524                     */
14525                    if (externalStorage && !isMounted && !isExternal(ps)) {
14526                        continue;
14527                    }
14528
14529                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14530                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14531                    // The package status is changed only if the code path
14532                    // matches between settings and the container id.
14533                    if (ps.codePathString != null
14534                            && ps.codePathString.startsWith(args.getCodePath())) {
14535                        if (DEBUG_SD_INSTALL) {
14536                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14537                                    + " at code path: " + ps.codePathString);
14538                        }
14539
14540                        // We do have a valid package installed on sdcard
14541                        processCids.put(args, ps.codePathString);
14542                        final int uid = ps.appId;
14543                        if (uid != -1) {
14544                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14545                        }
14546                    } else {
14547                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14548                                + ps.codePathString);
14549                    }
14550                }
14551            }
14552
14553            Arrays.sort(uidArr);
14554        }
14555
14556        // Process packages with valid entries.
14557        if (isMounted) {
14558            if (DEBUG_SD_INSTALL)
14559                Log.i(TAG, "Loading packages");
14560            loadMediaPackages(processCids, uidArr);
14561            startCleaningPackages();
14562            mInstallerService.onSecureContainersAvailable();
14563        } else {
14564            if (DEBUG_SD_INSTALL)
14565                Log.i(TAG, "Unloading packages");
14566            unloadMediaPackages(processCids, uidArr, reportStatus);
14567        }
14568    }
14569
14570    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14571            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14572        final int size = infos.size();
14573        final String[] packageNames = new String[size];
14574        final int[] packageUids = new int[size];
14575        for (int i = 0; i < size; i++) {
14576            final ApplicationInfo info = infos.get(i);
14577            packageNames[i] = info.packageName;
14578            packageUids[i] = info.uid;
14579        }
14580        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14581                finishedReceiver);
14582    }
14583
14584    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14585            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14586        sendResourcesChangedBroadcast(mediaStatus, replacing,
14587                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14588    }
14589
14590    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14591            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14592        int size = pkgList.length;
14593        if (size > 0) {
14594            // Send broadcasts here
14595            Bundle extras = new Bundle();
14596            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14597            if (uidArr != null) {
14598                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14599            }
14600            if (replacing) {
14601                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14602            }
14603            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14604                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14605            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14606        }
14607    }
14608
14609   /*
14610     * Look at potentially valid container ids from processCids If package
14611     * information doesn't match the one on record or package scanning fails,
14612     * the cid is added to list of removeCids. We currently don't delete stale
14613     * containers.
14614     */
14615    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14616        ArrayList<String> pkgList = new ArrayList<String>();
14617        Set<AsecInstallArgs> keys = processCids.keySet();
14618
14619        for (AsecInstallArgs args : keys) {
14620            String codePath = processCids.get(args);
14621            if (DEBUG_SD_INSTALL)
14622                Log.i(TAG, "Loading container : " + args.cid);
14623            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14624            try {
14625                // Make sure there are no container errors first.
14626                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14627                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14628                            + " when installing from sdcard");
14629                    continue;
14630                }
14631                // Check code path here.
14632                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14633                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14634                            + " does not match one in settings " + codePath);
14635                    continue;
14636                }
14637                // Parse package
14638                int parseFlags = mDefParseFlags;
14639                if (args.isExternalAsec()) {
14640                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14641                }
14642                if (args.isFwdLocked()) {
14643                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14644                }
14645
14646                synchronized (mInstallLock) {
14647                    PackageParser.Package pkg = null;
14648                    try {
14649                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14650                    } catch (PackageManagerException e) {
14651                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14652                    }
14653                    // Scan the package
14654                    if (pkg != null) {
14655                        /*
14656                         * TODO why is the lock being held? doPostInstall is
14657                         * called in other places without the lock. This needs
14658                         * to be straightened out.
14659                         */
14660                        // writer
14661                        synchronized (mPackages) {
14662                            retCode = PackageManager.INSTALL_SUCCEEDED;
14663                            pkgList.add(pkg.packageName);
14664                            // Post process args
14665                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14666                                    pkg.applicationInfo.uid);
14667                        }
14668                    } else {
14669                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14670                    }
14671                }
14672
14673            } finally {
14674                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14675                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14676                }
14677            }
14678        }
14679        // writer
14680        synchronized (mPackages) {
14681            // If the platform SDK has changed since the last time we booted,
14682            // we need to re-grant app permission to catch any new ones that
14683            // appear. This is really a hack, and means that apps can in some
14684            // cases get permissions that the user didn't initially explicitly
14685            // allow... it would be nice to have some better way to handle
14686            // this situation.
14687            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14688            if (regrantPermissions)
14689                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14690                        + mSdkVersion + "; regranting permissions for external storage");
14691            mSettings.mExternalSdkPlatform = mSdkVersion;
14692
14693            // Make sure group IDs have been assigned, and any permission
14694            // changes in other apps are accounted for
14695            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14696                    | (regrantPermissions
14697                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14698                            : 0));
14699
14700            mSettings.updateExternalDatabaseVersion();
14701
14702            // can downgrade to reader
14703            // Persist settings
14704            mSettings.writeLPr();
14705        }
14706        // Send a broadcast to let everyone know we are done processing
14707        if (pkgList.size() > 0) {
14708            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14709        }
14710    }
14711
14712   /*
14713     * Utility method to unload a list of specified containers
14714     */
14715    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14716        // Just unmount all valid containers.
14717        for (AsecInstallArgs arg : cidArgs) {
14718            synchronized (mInstallLock) {
14719                arg.doPostDeleteLI(false);
14720           }
14721       }
14722   }
14723
14724    /*
14725     * Unload packages mounted on external media. This involves deleting package
14726     * data from internal structures, sending broadcasts about diabled packages,
14727     * gc'ing to free up references, unmounting all secure containers
14728     * corresponding to packages on external media, and posting a
14729     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14730     * that we always have to post this message if status has been requested no
14731     * matter what.
14732     */
14733    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14734            final boolean reportStatus) {
14735        if (DEBUG_SD_INSTALL)
14736            Log.i(TAG, "unloading media packages");
14737        ArrayList<String> pkgList = new ArrayList<String>();
14738        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14739        final Set<AsecInstallArgs> keys = processCids.keySet();
14740        for (AsecInstallArgs args : keys) {
14741            String pkgName = args.getPackageName();
14742            if (DEBUG_SD_INSTALL)
14743                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14744            // Delete package internally
14745            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14746            synchronized (mInstallLock) {
14747                boolean res = deletePackageLI(pkgName, null, false, null, null,
14748                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14749                if (res) {
14750                    pkgList.add(pkgName);
14751                } else {
14752                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14753                    failedList.add(args);
14754                }
14755            }
14756        }
14757
14758        // reader
14759        synchronized (mPackages) {
14760            // We didn't update the settings after removing each package;
14761            // write them now for all packages.
14762            mSettings.writeLPr();
14763        }
14764
14765        // We have to absolutely send UPDATED_MEDIA_STATUS only
14766        // after confirming that all the receivers processed the ordered
14767        // broadcast when packages get disabled, force a gc to clean things up.
14768        // and unload all the containers.
14769        if (pkgList.size() > 0) {
14770            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14771                    new IIntentReceiver.Stub() {
14772                public void performReceive(Intent intent, int resultCode, String data,
14773                        Bundle extras, boolean ordered, boolean sticky,
14774                        int sendingUser) throws RemoteException {
14775                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14776                            reportStatus ? 1 : 0, 1, keys);
14777                    mHandler.sendMessage(msg);
14778                }
14779            });
14780        } else {
14781            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14782                    keys);
14783            mHandler.sendMessage(msg);
14784        }
14785    }
14786
14787    private void loadPrivatePackages(VolumeInfo vol) {
14788        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14789        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14790        synchronized (mInstallLock) {
14791        synchronized (mPackages) {
14792            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14793            for (PackageSetting ps : packages) {
14794                final PackageParser.Package pkg;
14795                try {
14796                    pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14797                    loaded.add(pkg.applicationInfo);
14798                } catch (PackageManagerException e) {
14799                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14800                }
14801            }
14802
14803            // TODO: regrant any permissions that changed based since original install
14804
14805            mSettings.writeLPr();
14806        }
14807        }
14808
14809        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
14810        sendResourcesChangedBroadcast(true, false, loaded, null);
14811    }
14812
14813    private void unloadPrivatePackages(VolumeInfo vol) {
14814        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14815        synchronized (mInstallLock) {
14816        synchronized (mPackages) {
14817            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14818            for (PackageSetting ps : packages) {
14819                if (ps.pkg == null) continue;
14820
14821                final ApplicationInfo info = ps.pkg.applicationInfo;
14822                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14823                if (deletePackageLI(ps.name, null, false, null, null,
14824                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14825                    unloaded.add(info);
14826                } else {
14827                    Slog.w(TAG, "Failed to unload " + ps.codePath);
14828                }
14829            }
14830
14831            mSettings.writeLPr();
14832        }
14833        }
14834
14835        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
14836        sendResourcesChangedBroadcast(false, false, unloaded, null);
14837    }
14838
14839    private void unfreezePackage(String packageName) {
14840        synchronized (mPackages) {
14841            final PackageSetting ps = mSettings.mPackages.get(packageName);
14842            if (ps != null) {
14843                ps.frozen = false;
14844            }
14845        }
14846    }
14847
14848    @Override
14849    public int movePackage(final String packageName, final String volumeUuid) {
14850        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14851
14852        final int moveId = mNextMoveId.getAndIncrement();
14853        try {
14854            movePackageInternal(packageName, volumeUuid, moveId);
14855        } catch (PackageManagerException e) {
14856            Slog.w(TAG, "Failed to move " + packageName, e);
14857            mMoveCallbacks.notifyStatusChanged(moveId,
14858                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14859        }
14860        return moveId;
14861    }
14862
14863    private void movePackageInternal(final String packageName, final String volumeUuid,
14864            final int moveId) throws PackageManagerException {
14865        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14866        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14867        final PackageManager pm = mContext.getPackageManager();
14868
14869        final boolean currentAsec;
14870        final String currentVolumeUuid;
14871        final File codeFile;
14872        final String installerPackageName;
14873        final String packageAbiOverride;
14874        final int appId;
14875        final String seinfo;
14876        final String label;
14877
14878        // reader
14879        synchronized (mPackages) {
14880            final PackageParser.Package pkg = mPackages.get(packageName);
14881            final PackageSetting ps = mSettings.mPackages.get(packageName);
14882            if (pkg == null || ps == null) {
14883                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14884            }
14885
14886            if (pkg.applicationInfo.isSystemApp()) {
14887                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14888                        "Cannot move system application");
14889            }
14890
14891            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
14892                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14893                        "Package already moved to " + volumeUuid);
14894            }
14895
14896            final File probe = new File(pkg.codePath);
14897            final File probeOat = new File(probe, "oat");
14898            if (!probe.isDirectory() || !probeOat.isDirectory()) {
14899                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14900                        "Move only supported for modern cluster style installs");
14901            }
14902
14903            if (ps.frozen) {
14904                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14905                        "Failed to move already frozen package");
14906            }
14907            ps.frozen = true;
14908
14909            currentAsec = pkg.applicationInfo.isForwardLocked()
14910                    || pkg.applicationInfo.isExternalAsec();
14911            currentVolumeUuid = ps.volumeUuid;
14912            codeFile = new File(pkg.codePath);
14913            installerPackageName = ps.installerPackageName;
14914            packageAbiOverride = ps.cpuAbiOverrideString;
14915            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14916            seinfo = pkg.applicationInfo.seinfo;
14917            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
14918        }
14919
14920        // Now that we're guarded by frozen state, kill app during move
14921        killApplication(packageName, appId, "move pkg");
14922
14923        final Bundle extras = new Bundle();
14924        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
14925        extras.putString(Intent.EXTRA_TITLE, label);
14926        mMoveCallbacks.notifyCreated(moveId, extras);
14927
14928        int installFlags;
14929        final boolean moveCompleteApp;
14930        final File measurePath;
14931
14932        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
14933            installFlags = INSTALL_INTERNAL;
14934            moveCompleteApp = !currentAsec;
14935            measurePath = Environment.getDataAppDirectory(volumeUuid);
14936        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
14937            installFlags = INSTALL_EXTERNAL;
14938            moveCompleteApp = false;
14939            measurePath = storage.getPrimaryPhysicalVolume().getPath();
14940        } else {
14941            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
14942            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
14943                    || !volume.isMountedWritable()) {
14944                unfreezePackage(packageName);
14945                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14946                        "Move location not mounted private volume");
14947            }
14948
14949            Preconditions.checkState(!currentAsec);
14950
14951            installFlags = INSTALL_INTERNAL;
14952            moveCompleteApp = true;
14953            measurePath = Environment.getDataAppDirectory(volumeUuid);
14954        }
14955
14956        final PackageStats stats = new PackageStats(null, -1);
14957        synchronized (mInstaller) {
14958            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
14959                unfreezePackage(packageName);
14960                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14961                        "Failed to measure package size");
14962            }
14963        }
14964
14965        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
14966                + stats.dataSize);
14967
14968        final long startFreeBytes = measurePath.getFreeSpace();
14969        final long sizeBytes;
14970        if (moveCompleteApp) {
14971            sizeBytes = stats.codeSize + stats.dataSize;
14972        } else {
14973            sizeBytes = stats.codeSize;
14974        }
14975
14976        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
14977            unfreezePackage(packageName);
14978            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14979                    "Not enough free space to move");
14980        }
14981
14982        mMoveCallbacks.notifyStatusChanged(moveId, 10);
14983
14984        final CountDownLatch installedLatch = new CountDownLatch(1);
14985        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14986            @Override
14987            public void onUserActionRequired(Intent intent) throws RemoteException {
14988                throw new IllegalStateException();
14989            }
14990
14991            @Override
14992            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14993                    Bundle extras) throws RemoteException {
14994                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
14995                        + PackageManager.installStatusToString(returnCode, msg));
14996
14997                installedLatch.countDown();
14998
14999                // Regardless of success or failure of the move operation,
15000                // always unfreeze the package
15001                unfreezePackage(packageName);
15002
15003                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15004                switch (status) {
15005                    case PackageInstaller.STATUS_SUCCESS:
15006                        mMoveCallbacks.notifyStatusChanged(moveId,
15007                                PackageManager.MOVE_SUCCEEDED);
15008                        break;
15009                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15010                        mMoveCallbacks.notifyStatusChanged(moveId,
15011                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15012                        break;
15013                    default:
15014                        mMoveCallbacks.notifyStatusChanged(moveId,
15015                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15016                        break;
15017                }
15018            }
15019        };
15020
15021        final MoveInfo move;
15022        if (moveCompleteApp) {
15023            // Kick off a thread to report progress estimates
15024            new Thread() {
15025                @Override
15026                public void run() {
15027                    while (true) {
15028                        try {
15029                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15030                                break;
15031                            }
15032                        } catch (InterruptedException ignored) {
15033                        }
15034
15035                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15036                        final int progress = 10 + (int) MathUtils.constrain(
15037                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15038                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15039                    }
15040                }
15041            }.start();
15042
15043            final String dataAppName = codeFile.getName();
15044            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15045                    dataAppName, appId, seinfo);
15046        } else {
15047            move = null;
15048        }
15049
15050        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15051
15052        final Message msg = mHandler.obtainMessage(INIT_COPY);
15053        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15054        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15055                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15056        mHandler.sendMessage(msg);
15057    }
15058
15059    @Override
15060    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15061        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15062
15063        final int realMoveId = mNextMoveId.getAndIncrement();
15064        final Bundle extras = new Bundle();
15065        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15066        mMoveCallbacks.notifyCreated(realMoveId, extras);
15067
15068        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15069            @Override
15070            public void onCreated(int moveId, Bundle extras) {
15071                // Ignored
15072            }
15073
15074            @Override
15075            public void onStatusChanged(int moveId, int status, long estMillis) {
15076                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15077            }
15078        };
15079
15080        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15081        storage.setPrimaryStorageUuid(volumeUuid, callback);
15082        return realMoveId;
15083    }
15084
15085    @Override
15086    public int getMoveStatus(int moveId) {
15087        mContext.enforceCallingOrSelfPermission(
15088                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15089        return mMoveCallbacks.mLastStatus.get(moveId);
15090    }
15091
15092    @Override
15093    public void registerMoveCallback(IPackageMoveObserver callback) {
15094        mContext.enforceCallingOrSelfPermission(
15095                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15096        mMoveCallbacks.register(callback);
15097    }
15098
15099    @Override
15100    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15101        mContext.enforceCallingOrSelfPermission(
15102                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15103        mMoveCallbacks.unregister(callback);
15104    }
15105
15106    @Override
15107    public boolean setInstallLocation(int loc) {
15108        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15109                null);
15110        if (getInstallLocation() == loc) {
15111            return true;
15112        }
15113        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15114                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15115            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15116                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15117            return true;
15118        }
15119        return false;
15120   }
15121
15122    @Override
15123    public int getInstallLocation() {
15124        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15125                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15126                PackageHelper.APP_INSTALL_AUTO);
15127    }
15128
15129    /** Called by UserManagerService */
15130    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15131        mDirtyUsers.remove(userHandle);
15132        mSettings.removeUserLPw(userHandle);
15133        mPendingBroadcasts.remove(userHandle);
15134        if (mInstaller != null) {
15135            // Technically, we shouldn't be doing this with the package lock
15136            // held.  However, this is very rare, and there is already so much
15137            // other disk I/O going on, that we'll let it slide for now.
15138            final StorageManager storage = StorageManager.from(mContext);
15139            final List<VolumeInfo> vols = storage.getVolumes();
15140            for (VolumeInfo vol : vols) {
15141                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
15142                    final String volumeUuid = vol.getFsUuid();
15143                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15144                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15145                }
15146            }
15147        }
15148        mUserNeedsBadging.delete(userHandle);
15149        removeUnusedPackagesLILPw(userManager, userHandle);
15150    }
15151
15152    /**
15153     * We're removing userHandle and would like to remove any downloaded packages
15154     * that are no longer in use by any other user.
15155     * @param userHandle the user being removed
15156     */
15157    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15158        final boolean DEBUG_CLEAN_APKS = false;
15159        int [] users = userManager.getUserIdsLPr();
15160        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15161        while (psit.hasNext()) {
15162            PackageSetting ps = psit.next();
15163            if (ps.pkg == null) {
15164                continue;
15165            }
15166            final String packageName = ps.pkg.packageName;
15167            // Skip over if system app
15168            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15169                continue;
15170            }
15171            if (DEBUG_CLEAN_APKS) {
15172                Slog.i(TAG, "Checking package " + packageName);
15173            }
15174            boolean keep = false;
15175            for (int i = 0; i < users.length; i++) {
15176                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15177                    keep = true;
15178                    if (DEBUG_CLEAN_APKS) {
15179                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15180                                + users[i]);
15181                    }
15182                    break;
15183                }
15184            }
15185            if (!keep) {
15186                if (DEBUG_CLEAN_APKS) {
15187                    Slog.i(TAG, "  Removing package " + packageName);
15188                }
15189                mHandler.post(new Runnable() {
15190                    public void run() {
15191                        deletePackageX(packageName, userHandle, 0);
15192                    } //end run
15193                });
15194            }
15195        }
15196    }
15197
15198    /** Called by UserManagerService */
15199    void createNewUserLILPw(int userHandle, File path) {
15200        if (mInstaller != null) {
15201            mInstaller.createUserConfig(userHandle);
15202            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
15203        }
15204    }
15205
15206    void newUserCreatedLILPw(final int userHandle) {
15207        // We cannot grant the default permissions with a lock held as
15208        // we query providers from other components for default handlers
15209        // such as enabled IMEs, etc.
15210        mHandler.post(new Runnable() {
15211            @Override
15212            public void run() {
15213                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15214            }
15215        });
15216    }
15217
15218    @Override
15219    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15220        mContext.enforceCallingOrSelfPermission(
15221                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15222                "Only package verification agents can read the verifier device identity");
15223
15224        synchronized (mPackages) {
15225            return mSettings.getVerifierDeviceIdentityLPw();
15226        }
15227    }
15228
15229    @Override
15230    public void setPermissionEnforced(String permission, boolean enforced) {
15231        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15232        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15233            synchronized (mPackages) {
15234                if (mSettings.mReadExternalStorageEnforced == null
15235                        || mSettings.mReadExternalStorageEnforced != enforced) {
15236                    mSettings.mReadExternalStorageEnforced = enforced;
15237                    mSettings.writeLPr();
15238                }
15239            }
15240            // kill any non-foreground processes so we restart them and
15241            // grant/revoke the GID.
15242            final IActivityManager am = ActivityManagerNative.getDefault();
15243            if (am != null) {
15244                final long token = Binder.clearCallingIdentity();
15245                try {
15246                    am.killProcessesBelowForeground("setPermissionEnforcement");
15247                } catch (RemoteException e) {
15248                } finally {
15249                    Binder.restoreCallingIdentity(token);
15250                }
15251            }
15252        } else {
15253            throw new IllegalArgumentException("No selective enforcement for " + permission);
15254        }
15255    }
15256
15257    @Override
15258    @Deprecated
15259    public boolean isPermissionEnforced(String permission) {
15260        return true;
15261    }
15262
15263    @Override
15264    public boolean isStorageLow() {
15265        final long token = Binder.clearCallingIdentity();
15266        try {
15267            final DeviceStorageMonitorInternal
15268                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15269            if (dsm != null) {
15270                return dsm.isMemoryLow();
15271            } else {
15272                return false;
15273            }
15274        } finally {
15275            Binder.restoreCallingIdentity(token);
15276        }
15277    }
15278
15279    @Override
15280    public IPackageInstaller getPackageInstaller() {
15281        return mInstallerService;
15282    }
15283
15284    private boolean userNeedsBadging(int userId) {
15285        int index = mUserNeedsBadging.indexOfKey(userId);
15286        if (index < 0) {
15287            final UserInfo userInfo;
15288            final long token = Binder.clearCallingIdentity();
15289            try {
15290                userInfo = sUserManager.getUserInfo(userId);
15291            } finally {
15292                Binder.restoreCallingIdentity(token);
15293            }
15294            final boolean b;
15295            if (userInfo != null && userInfo.isManagedProfile()) {
15296                b = true;
15297            } else {
15298                b = false;
15299            }
15300            mUserNeedsBadging.put(userId, b);
15301            return b;
15302        }
15303        return mUserNeedsBadging.valueAt(index);
15304    }
15305
15306    @Override
15307    public KeySet getKeySetByAlias(String packageName, String alias) {
15308        if (packageName == null || alias == null) {
15309            return null;
15310        }
15311        synchronized(mPackages) {
15312            final PackageParser.Package pkg = mPackages.get(packageName);
15313            if (pkg == null) {
15314                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15315                throw new IllegalArgumentException("Unknown package: " + packageName);
15316            }
15317            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15318            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15319        }
15320    }
15321
15322    @Override
15323    public KeySet getSigningKeySet(String packageName) {
15324        if (packageName == null) {
15325            return null;
15326        }
15327        synchronized(mPackages) {
15328            final PackageParser.Package pkg = mPackages.get(packageName);
15329            if (pkg == null) {
15330                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15331                throw new IllegalArgumentException("Unknown package: " + packageName);
15332            }
15333            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15334                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15335                throw new SecurityException("May not access signing KeySet of other apps.");
15336            }
15337            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15338            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15339        }
15340    }
15341
15342    @Override
15343    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15344        if (packageName == null || ks == null) {
15345            return false;
15346        }
15347        synchronized(mPackages) {
15348            final PackageParser.Package pkg = mPackages.get(packageName);
15349            if (pkg == null) {
15350                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15351                throw new IllegalArgumentException("Unknown package: " + packageName);
15352            }
15353            IBinder ksh = ks.getToken();
15354            if (ksh instanceof KeySetHandle) {
15355                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15356                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15357            }
15358            return false;
15359        }
15360    }
15361
15362    @Override
15363    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15364        if (packageName == null || ks == null) {
15365            return false;
15366        }
15367        synchronized(mPackages) {
15368            final PackageParser.Package pkg = mPackages.get(packageName);
15369            if (pkg == null) {
15370                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15371                throw new IllegalArgumentException("Unknown package: " + packageName);
15372            }
15373            IBinder ksh = ks.getToken();
15374            if (ksh instanceof KeySetHandle) {
15375                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15376                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15377            }
15378            return false;
15379        }
15380    }
15381
15382    public void getUsageStatsIfNoPackageUsageInfo() {
15383        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15384            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15385            if (usm == null) {
15386                throw new IllegalStateException("UsageStatsManager must be initialized");
15387            }
15388            long now = System.currentTimeMillis();
15389            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15390            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15391                String packageName = entry.getKey();
15392                PackageParser.Package pkg = mPackages.get(packageName);
15393                if (pkg == null) {
15394                    continue;
15395                }
15396                UsageStats usage = entry.getValue();
15397                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15398                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15399            }
15400        }
15401    }
15402
15403    /**
15404     * Check and throw if the given before/after packages would be considered a
15405     * downgrade.
15406     */
15407    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15408            throws PackageManagerException {
15409        if (after.versionCode < before.mVersionCode) {
15410            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15411                    "Update version code " + after.versionCode + " is older than current "
15412                    + before.mVersionCode);
15413        } else if (after.versionCode == before.mVersionCode) {
15414            if (after.baseRevisionCode < before.baseRevisionCode) {
15415                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15416                        "Update base revision code " + after.baseRevisionCode
15417                        + " is older than current " + before.baseRevisionCode);
15418            }
15419
15420            if (!ArrayUtils.isEmpty(after.splitNames)) {
15421                for (int i = 0; i < after.splitNames.length; i++) {
15422                    final String splitName = after.splitNames[i];
15423                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15424                    if (j != -1) {
15425                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15426                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15427                                    "Update split " + splitName + " revision code "
15428                                    + after.splitRevisionCodes[i] + " is older than current "
15429                                    + before.splitRevisionCodes[j]);
15430                        }
15431                    }
15432                }
15433            }
15434        }
15435    }
15436
15437    private static class MoveCallbacks extends Handler {
15438        private static final int MSG_CREATED = 1;
15439        private static final int MSG_STATUS_CHANGED = 2;
15440
15441        private final RemoteCallbackList<IPackageMoveObserver>
15442                mCallbacks = new RemoteCallbackList<>();
15443
15444        private final SparseIntArray mLastStatus = new SparseIntArray();
15445
15446        public MoveCallbacks(Looper looper) {
15447            super(looper);
15448        }
15449
15450        public void register(IPackageMoveObserver callback) {
15451            mCallbacks.register(callback);
15452        }
15453
15454        public void unregister(IPackageMoveObserver callback) {
15455            mCallbacks.unregister(callback);
15456        }
15457
15458        @Override
15459        public void handleMessage(Message msg) {
15460            final SomeArgs args = (SomeArgs) msg.obj;
15461            final int n = mCallbacks.beginBroadcast();
15462            for (int i = 0; i < n; i++) {
15463                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15464                try {
15465                    invokeCallback(callback, msg.what, args);
15466                } catch (RemoteException ignored) {
15467                }
15468            }
15469            mCallbacks.finishBroadcast();
15470            args.recycle();
15471        }
15472
15473        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15474                throws RemoteException {
15475            switch (what) {
15476                case MSG_CREATED: {
15477                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15478                    break;
15479                }
15480                case MSG_STATUS_CHANGED: {
15481                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15482                    break;
15483                }
15484            }
15485        }
15486
15487        private void notifyCreated(int moveId, Bundle extras) {
15488            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15489
15490            final SomeArgs args = SomeArgs.obtain();
15491            args.argi1 = moveId;
15492            args.arg2 = extras;
15493            obtainMessage(MSG_CREATED, args).sendToTarget();
15494        }
15495
15496        private void notifyStatusChanged(int moveId, int status) {
15497            notifyStatusChanged(moveId, status, -1);
15498        }
15499
15500        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15501            Slog.v(TAG, "Move " + moveId + " status " + status);
15502
15503            final SomeArgs args = SomeArgs.obtain();
15504            args.argi1 = moveId;
15505            args.argi2 = status;
15506            args.arg3 = estMillis;
15507            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15508
15509            synchronized (mLastStatus) {
15510                mLastStatus.put(moveId, status);
15511            }
15512        }
15513    }
15514
15515    private final class OnPermissionChangeListeners extends Handler {
15516        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
15517
15518        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
15519                new RemoteCallbackList<>();
15520
15521        public OnPermissionChangeListeners(Looper looper) {
15522            super(looper);
15523        }
15524
15525        @Override
15526        public void handleMessage(Message msg) {
15527            switch (msg.what) {
15528                case MSG_ON_PERMISSIONS_CHANGED: {
15529                    final int uid = msg.arg1;
15530                    handleOnPermissionsChanged(uid);
15531                } break;
15532            }
15533        }
15534
15535        public void addListenerLocked(IOnPermissionsChangeListener listener) {
15536            mPermissionListeners.register(listener);
15537
15538        }
15539
15540        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
15541            mPermissionListeners.unregister(listener);
15542        }
15543
15544        public void onPermissionsChanged(int uid) {
15545            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
15546                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
15547            }
15548        }
15549
15550        private void handleOnPermissionsChanged(int uid) {
15551            final int count = mPermissionListeners.beginBroadcast();
15552            try {
15553                for (int i = 0; i < count; i++) {
15554                    IOnPermissionsChangeListener callback = mPermissionListeners
15555                            .getBroadcastItem(i);
15556                    try {
15557                        callback.onPermissionsChanged(uid);
15558                    } catch (RemoteException e) {
15559                        Log.e(TAG, "Permission listener is dead", e);
15560                    }
15561                }
15562            } finally {
15563                mPermissionListeners.finishBroadcast();
15564            }
15565        }
15566    }
15567
15568    private class PackageManagerInternalImpl extends PackageManagerInternal {
15569        @Override
15570        public void setLocationPackagesProvider(PackagesProvider provider) {
15571            synchronized (mPackages) {
15572                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
15573            }
15574        }
15575
15576        @Override
15577        public void setImePackagesProvider(PackagesProvider provider) {
15578            synchronized (mPackages) {
15579                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
15580            }
15581        }
15582
15583        @Override
15584        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
15585            synchronized (mPackages) {
15586                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
15587            }
15588        }
15589    }
15590}
15591