PackageManagerService.java revision 275e3e43f2fba72fa99001cafa2a70e5478fc545
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
46import static android.content.pm.PackageManager.INSTALL_INTERNAL;
47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
52import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
53import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
54import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
55import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
56import static android.content.pm.PackageParser.isApkFile;
57import static android.os.Process.PACKAGE_INFO_GID;
58import static android.os.Process.SYSTEM_UID;
59import static android.system.OsConstants.O_CREAT;
60import static android.system.OsConstants.O_RDWR;
61import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
62import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
63import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
64import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
65import static com.android.internal.util.ArrayUtils.appendInt;
66import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
67import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
68import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
69import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
70import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
71
72import android.Manifest;
73import android.app.ActivityManager;
74import android.app.ActivityManagerNative;
75import android.app.AppGlobals;
76import android.app.IActivityManager;
77import android.app.admin.IDevicePolicyManager;
78import android.app.backup.IBackupManager;
79import android.app.usage.UsageStats;
80import android.app.usage.UsageStatsManager;
81import android.content.BroadcastReceiver;
82import android.content.ComponentName;
83import android.content.Context;
84import android.content.IIntentReceiver;
85import android.content.Intent;
86import android.content.IntentFilter;
87import android.content.IntentSender;
88import android.content.IntentSender.SendIntentException;
89import android.content.ServiceConnection;
90import android.content.pm.ActivityInfo;
91import android.content.pm.ApplicationInfo;
92import android.content.pm.FeatureInfo;
93import android.content.pm.IPackageDataObserver;
94import android.content.pm.IPackageDeleteObserver;
95import android.content.pm.IPackageDeleteObserver2;
96import android.content.pm.IPackageInstallObserver2;
97import android.content.pm.IPackageInstaller;
98import android.content.pm.IPackageManager;
99import android.content.pm.IPackageMoveObserver;
100import android.content.pm.IPackageStatsObserver;
101import android.content.pm.InstrumentationInfo;
102import android.content.pm.IntentFilterVerificationInfo;
103import android.content.pm.KeySet;
104import android.content.pm.ManifestDigest;
105import android.content.pm.PackageCleanItem;
106import android.content.pm.PackageInfo;
107import android.content.pm.PackageInfoLite;
108import android.content.pm.PackageInstaller;
109import android.content.pm.PackageManager;
110import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
111import android.content.pm.PackageParser;
112import android.content.pm.PackageParser.ActivityIntentInfo;
113import android.content.pm.PackageParser.PackageLite;
114import android.content.pm.PackageParser.PackageParserException;
115import android.content.pm.PackageStats;
116import android.content.pm.PackageUserState;
117import android.content.pm.ParceledListSlice;
118import android.content.pm.PermissionGroupInfo;
119import android.content.pm.PermissionInfo;
120import android.content.pm.ProviderInfo;
121import android.content.pm.ResolveInfo;
122import android.content.pm.ServiceInfo;
123import android.content.pm.Signature;
124import android.content.pm.UserInfo;
125import android.content.pm.VerificationParams;
126import android.content.pm.VerifierDeviceIdentity;
127import android.content.pm.VerifierInfo;
128import android.content.res.Resources;
129import android.hardware.display.DisplayManager;
130import android.net.Uri;
131import android.os.Binder;
132import android.os.Build;
133import android.os.Bundle;
134import android.os.Debug;
135import android.os.Environment;
136import android.os.Environment.UserEnvironment;
137import android.os.FileUtils;
138import android.os.Handler;
139import android.os.IBinder;
140import android.os.Looper;
141import android.os.Message;
142import android.os.Parcel;
143import android.os.ParcelFileDescriptor;
144import android.os.Process;
145import android.os.RemoteCallbackList;
146import android.os.RemoteException;
147import android.os.SELinux;
148import android.os.ServiceManager;
149import android.os.SystemClock;
150import android.os.SystemProperties;
151import android.os.UserHandle;
152import android.os.UserManager;
153import android.os.storage.IMountService;
154import android.os.storage.StorageEventListener;
155import android.os.storage.StorageManager;
156import android.os.storage.VolumeInfo;
157import android.security.KeyStore;
158import android.security.SystemKeyStore;
159import android.system.ErrnoException;
160import android.system.Os;
161import android.system.StructStat;
162import android.text.TextUtils;
163import android.text.format.DateUtils;
164import android.util.ArrayMap;
165import android.util.ArraySet;
166import android.util.AtomicFile;
167import android.util.DisplayMetrics;
168import android.util.EventLog;
169import android.util.ExceptionUtils;
170import android.util.Log;
171import android.util.LogPrinter;
172import android.util.PrintStreamPrinter;
173import android.util.Slog;
174import android.util.SparseArray;
175import android.util.SparseBooleanArray;
176import android.util.SparseIntArray;
177import android.util.Xml;
178import android.view.Display;
179
180import dalvik.system.DexFile;
181import dalvik.system.VMRuntime;
182
183import libcore.io.IoUtils;
184import libcore.util.EmptyArray;
185
186import com.android.internal.R;
187import com.android.internal.app.IMediaContainerService;
188import com.android.internal.app.ResolverActivity;
189import com.android.internal.content.NativeLibraryHelper;
190import com.android.internal.content.PackageHelper;
191import com.android.internal.os.IParcelFileDescriptorFactory;
192import com.android.internal.os.SomeArgs;
193import com.android.internal.util.ArrayUtils;
194import com.android.internal.util.FastPrintWriter;
195import com.android.internal.util.FastXmlSerializer;
196import com.android.internal.util.IndentingPrintWriter;
197import com.android.internal.util.Preconditions;
198import com.android.server.EventLogTags;
199import com.android.server.FgThread;
200import com.android.server.IntentResolver;
201import com.android.server.LocalServices;
202import com.android.server.ServiceThread;
203import com.android.server.SystemConfig;
204import com.android.server.Watchdog;
205import com.android.server.pm.Settings.DatabaseVersion;
206import com.android.server.storage.DeviceStorageMonitorInternal;
207
208import org.xmlpull.v1.XmlPullParser;
209import org.xmlpull.v1.XmlSerializer;
210
211import java.io.BufferedInputStream;
212import java.io.BufferedOutputStream;
213import java.io.BufferedReader;
214import java.io.ByteArrayInputStream;
215import java.io.ByteArrayOutputStream;
216import java.io.File;
217import java.io.FileDescriptor;
218import java.io.FileNotFoundException;
219import java.io.FileOutputStream;
220import java.io.FileReader;
221import java.io.FilenameFilter;
222import java.io.IOException;
223import java.io.InputStream;
224import java.io.PrintWriter;
225import java.nio.charset.StandardCharsets;
226import java.security.NoSuchAlgorithmException;
227import java.security.PublicKey;
228import java.security.cert.CertificateEncodingException;
229import java.security.cert.CertificateException;
230import java.text.SimpleDateFormat;
231import java.util.ArrayList;
232import java.util.Arrays;
233import java.util.Collection;
234import java.util.Collections;
235import java.util.Comparator;
236import java.util.Date;
237import java.util.Iterator;
238import java.util.List;
239import java.util.Map;
240import java.util.Objects;
241import java.util.Set;
242import java.util.concurrent.atomic.AtomicBoolean;
243import java.util.concurrent.atomic.AtomicInteger;
244import java.util.concurrent.atomic.AtomicLong;
245
246/**
247 * Keep track of all those .apks everywhere.
248 *
249 * This is very central to the platform's security; please run the unit
250 * tests whenever making modifications here:
251 *
252mmm frameworks/base/tests/AndroidTests
253adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
254adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
255 *
256 * {@hide}
257 */
258public class PackageManagerService extends IPackageManager.Stub {
259    static final String TAG = "PackageManager";
260    static final boolean DEBUG_SETTINGS = false;
261    static final boolean DEBUG_PREFERRED = false;
262    static final boolean DEBUG_UPGRADE = false;
263    private static final boolean DEBUG_BACKUP = true;
264    private static final boolean DEBUG_INSTALL = false;
265    private static final boolean DEBUG_REMOVE = false;
266    private static final boolean DEBUG_BROADCASTS = false;
267    private static final boolean DEBUG_SHOW_INFO = false;
268    private static final boolean DEBUG_PACKAGE_INFO = false;
269    private static final boolean DEBUG_INTENT_MATCHING = false;
270    private static final boolean DEBUG_PACKAGE_SCANNING = false;
271    private static final boolean DEBUG_VERIFY = false;
272    private static final boolean DEBUG_DEXOPT = false;
273    private static final boolean DEBUG_ABI_SELECTION = false;
274
275    static final boolean RUNTIME_PERMISSIONS_ENABLED = true;
276
277    private static final int RADIO_UID = Process.PHONE_UID;
278    private static final int LOG_UID = Process.LOG_UID;
279    private static final int NFC_UID = Process.NFC_UID;
280    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
281    private static final int SHELL_UID = Process.SHELL_UID;
282
283    // Cap the size of permission trees that 3rd party apps can define
284    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
285
286    // Suffix used during package installation when copying/moving
287    // package apks to install directory.
288    private static final String INSTALL_PACKAGE_SUFFIX = "-";
289
290    static final int SCAN_NO_DEX = 1<<1;
291    static final int SCAN_FORCE_DEX = 1<<2;
292    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
293    static final int SCAN_NEW_INSTALL = 1<<4;
294    static final int SCAN_NO_PATHS = 1<<5;
295    static final int SCAN_UPDATE_TIME = 1<<6;
296    static final int SCAN_DEFER_DEX = 1<<7;
297    static final int SCAN_BOOTING = 1<<8;
298    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
299    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
300    static final int SCAN_REPLACING = 1<<11;
301    static final int SCAN_REQUIRE_KNOWN = 1<<12;
302
303    static final int REMOVE_CHATTY = 1<<16;
304
305    /**
306     * Timeout (in milliseconds) after which the watchdog should declare that
307     * our handler thread is wedged.  The usual default for such things is one
308     * minute but we sometimes do very lengthy I/O operations on this thread,
309     * such as installing multi-gigabyte applications, so ours needs to be longer.
310     */
311    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
312
313    /**
314     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
315     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
316     * settings entry if available, otherwise we use the hardcoded default.  If it's been
317     * more than this long since the last fstrim, we force one during the boot sequence.
318     *
319     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
320     * one gets run at the next available charging+idle time.  This final mandatory
321     * no-fstrim check kicks in only of the other scheduling criteria is never met.
322     */
323    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
324
325    /**
326     * Whether verification is enabled by default.
327     */
328    private static final boolean DEFAULT_VERIFY_ENABLE = true;
329
330    /**
331     * The default maximum time to wait for the verification agent to return in
332     * milliseconds.
333     */
334    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
335
336    /**
337     * The default response for package verification timeout.
338     *
339     * This can be either PackageManager.VERIFICATION_ALLOW or
340     * PackageManager.VERIFICATION_REJECT.
341     */
342    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
343
344    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
345
346    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
347            DEFAULT_CONTAINER_PACKAGE,
348            "com.android.defcontainer.DefaultContainerService");
349
350    private static final String KILL_APP_REASON_GIDS_CHANGED =
351            "permission grant or revoke changed gids";
352
353    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
354            "permissions revoked";
355
356    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
357
358    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
359
360    /** Permission grant: not grant the permission. */
361    private static final int GRANT_DENIED = 1;
362
363    /** Permission grant: grant the permission as an install permission. */
364    private static final int GRANT_INSTALL = 2;
365
366    /** Permission grant: grant the permission as a runtime one. */
367    private static final int GRANT_RUNTIME = 3;
368
369    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
370    private static final int GRANT_UPGRADE = 4;
371
372    final ServiceThread mHandlerThread;
373
374    final PackageHandler mHandler;
375
376    /**
377     * Messages for {@link #mHandler} that need to wait for system ready before
378     * being dispatched.
379     */
380    private ArrayList<Message> mPostSystemReadyMessages;
381
382    final int mSdkVersion = Build.VERSION.SDK_INT;
383
384    final Context mContext;
385    final boolean mFactoryTest;
386    final boolean mOnlyCore;
387    final boolean mLazyDexOpt;
388    final long mDexOptLRUThresholdInMills;
389    final DisplayMetrics mMetrics;
390    final int mDefParseFlags;
391    final String[] mSeparateProcesses;
392    final boolean mIsUpgrade;
393
394    // This is where all application persistent data goes.
395    final File mAppDataDir;
396
397    // This is where all application persistent data goes for secondary users.
398    final File mUserAppDataDir;
399
400    /** The location for ASEC container files on internal storage. */
401    final String mAsecInternalPath;
402
403    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
404    // LOCK HELD.  Can be called with mInstallLock held.
405    final Installer mInstaller;
406
407    /** Directory where installed third-party apps stored */
408    final File mAppInstallDir;
409
410    /**
411     * Directory to which applications installed internally have their
412     * 32 bit native libraries copied.
413     */
414    private File mAppLib32InstallDir;
415
416    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
417    // apps.
418    final File mDrmAppPrivateInstallDir;
419
420    // ----------------------------------------------------------------
421
422    // Lock for state used when installing and doing other long running
423    // operations.  Methods that must be called with this lock held have
424    // the suffix "LI".
425    final Object mInstallLock = new Object();
426
427    // ----------------------------------------------------------------
428
429    // Keys are String (package name), values are Package.  This also serves
430    // as the lock for the global state.  Methods that must be called with
431    // this lock held have the prefix "LP".
432    final ArrayMap<String, PackageParser.Package> mPackages =
433            new ArrayMap<String, PackageParser.Package>();
434
435    // Tracks available target package names -> overlay package paths.
436    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
437        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
438
439    final Settings mSettings;
440    boolean mRestoredSettings;
441
442    // System configuration read by SystemConfig.
443    final int[] mGlobalGids;
444    final SparseArray<ArraySet<String>> mSystemPermissions;
445    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
446
447    // If mac_permissions.xml was found for seinfo labeling.
448    boolean mFoundPolicyFile;
449
450    // If a recursive restorecon of /data/data/<pkg> is needed.
451    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
452
453    public static final class SharedLibraryEntry {
454        public final String path;
455        public final String apk;
456
457        SharedLibraryEntry(String _path, String _apk) {
458            path = _path;
459            apk = _apk;
460        }
461    }
462
463    // Currently known shared libraries.
464    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
465            new ArrayMap<String, SharedLibraryEntry>();
466
467    // All available activities, for your resolving pleasure.
468    final ActivityIntentResolver mActivities =
469            new ActivityIntentResolver();
470
471    // All available receivers, for your resolving pleasure.
472    final ActivityIntentResolver mReceivers =
473            new ActivityIntentResolver();
474
475    // All available services, for your resolving pleasure.
476    final ServiceIntentResolver mServices = new ServiceIntentResolver();
477
478    // All available providers, for your resolving pleasure.
479    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
480
481    // Mapping from provider base names (first directory in content URI codePath)
482    // to the provider information.
483    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
484            new ArrayMap<String, PackageParser.Provider>();
485
486    // Mapping from instrumentation class names to info about them.
487    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
488            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
489
490    // Mapping from permission names to info about them.
491    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
492            new ArrayMap<String, PackageParser.PermissionGroup>();
493
494    // Packages whose data we have transfered into another package, thus
495    // should no longer exist.
496    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
497
498    // Broadcast actions that are only available to the system.
499    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
500
501    /** List of packages waiting for verification. */
502    final SparseArray<PackageVerificationState> mPendingVerification
503            = new SparseArray<PackageVerificationState>();
504
505    /** Set of packages associated with each app op permission. */
506    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
507
508    final PackageInstallerService mInstallerService;
509
510    private final PackageDexOptimizer mPackageDexOptimizer;
511
512    private AtomicInteger mNextMoveId = new AtomicInteger();
513    private final MoveCallbacks mMoveCallbacks;
514
515    // Cache of users who need badging.
516    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
517
518    /** Token for keys in mPendingVerification. */
519    private int mPendingVerificationToken = 0;
520
521    volatile boolean mSystemReady;
522    volatile boolean mSafeMode;
523    volatile boolean mHasSystemUidErrors;
524
525    ApplicationInfo mAndroidApplication;
526    final ActivityInfo mResolveActivity = new ActivityInfo();
527    final ResolveInfo mResolveInfo = new ResolveInfo();
528    ComponentName mResolveComponentName;
529    PackageParser.Package mPlatformPackage;
530    ComponentName mCustomResolverComponentName;
531
532    boolean mResolverReplaced = false;
533
534    private final ComponentName mIntentFilterVerifierComponent;
535    private int mIntentFilterVerificationToken = 0;
536
537    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
538            = new SparseArray<IntentFilterVerificationState>();
539
540    private interface IntentFilterVerifier<T extends IntentFilter> {
541        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
542                                               T filter, String packageName);
543        void startVerifications(int userId);
544        void receiveVerificationResponse(int verificationId);
545    }
546
547    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
548        private Context mContext;
549        private ComponentName mIntentFilterVerifierComponent;
550        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
551
552        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
553            mContext = context;
554            mIntentFilterVerifierComponent = verifierComponent;
555        }
556
557        private String getDefaultScheme() {
558            // TODO: replace SCHEME_HTTP with SCHEME_HTTPS
559            return IntentFilter.SCHEME_HTTP;
560        }
561
562        @Override
563        public void startVerifications(int userId) {
564            // Launch verifications requests
565            int count = mCurrentIntentFilterVerifications.size();
566            for (int n=0; n<count; n++) {
567                int verificationId = mCurrentIntentFilterVerifications.get(n);
568                final IntentFilterVerificationState ivs =
569                        mIntentFilterVerificationStates.get(verificationId);
570
571                String packageName = ivs.getPackageName();
572
573                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
574                final int filterCount = filters.size();
575                ArraySet<String> domainsSet = new ArraySet<>();
576                for (int m=0; m<filterCount; m++) {
577                    PackageParser.ActivityIntentInfo filter = filters.get(m);
578                    domainsSet.addAll(filter.getHostsList());
579                }
580                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
581                synchronized (mPackages) {
582                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
583                            packageName, domainsList) != null) {
584                        scheduleWriteSettingsLocked();
585                    }
586                }
587                sendVerificationRequest(userId, verificationId, ivs);
588            }
589            mCurrentIntentFilterVerifications.clear();
590        }
591
592        private void sendVerificationRequest(int userId, int verificationId,
593                IntentFilterVerificationState ivs) {
594
595            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
596            verificationIntent.putExtra(
597                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
598                    verificationId);
599            verificationIntent.putExtra(
600                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
601                    getDefaultScheme());
602            verificationIntent.putExtra(
603                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
604                    ivs.getHostsString());
605            verificationIntent.putExtra(
606                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
607                    ivs.getPackageName());
608            verificationIntent.setComponent(mIntentFilterVerifierComponent);
609            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
610
611            UserHandle user = new UserHandle(userId);
612            mContext.sendBroadcastAsUser(verificationIntent, user);
613            Slog.d(TAG, "Sending IntenFilter verification broadcast");
614        }
615
616        public void receiveVerificationResponse(int verificationId) {
617            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
618
619            final boolean verified = ivs.isVerified();
620
621            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
622            final int count = filters.size();
623            for (int n=0; n<count; n++) {
624                PackageParser.ActivityIntentInfo filter = filters.get(n);
625                filter.setVerified(verified);
626
627                Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:"
628                        + verified + " and hosts:" + ivs.getHostsString());
629            }
630
631            mIntentFilterVerificationStates.remove(verificationId);
632
633            final String packageName = ivs.getPackageName();
634            IntentFilterVerificationInfo ivi = null;
635
636            synchronized (mPackages) {
637                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
638            }
639            if (ivi == null) {
640                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
641                        + verificationId + " packageName:" + packageName);
642                return;
643            }
644            Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:"
645                    + verificationId);
646
647            synchronized (mPackages) {
648                if (verified) {
649                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
650                } else {
651                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
652                }
653                scheduleWriteSettingsLocked();
654
655                final int userId = ivs.getUserId();
656                if (userId != UserHandle.USER_ALL) {
657                    final int userStatus =
658                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
659
660                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
661                    boolean needUpdate = false;
662
663                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
664                    // already been set by the User thru the Disambiguation dialog
665                    switch (userStatus) {
666                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
667                            if (verified) {
668                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
669                            } else {
670                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
671                            }
672                            needUpdate = true;
673                            break;
674
675                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
676                            if (verified) {
677                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
678                                needUpdate = true;
679                            }
680                            break;
681
682                        default:
683                            // Nothing to do
684                    }
685
686                    if (needUpdate) {
687                        mSettings.updateIntentFilterVerificationStatusLPw(
688                                packageName, updatedStatus, userId);
689                        scheduleWritePackageRestrictionsLocked(userId);
690                    }
691                }
692            }
693        }
694
695        @Override
696        public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
697                    ActivityIntentInfo filter, String packageName) {
698            if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
699                    filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
700                Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme");
701                return false;
702            }
703            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
704            if (ivs == null) {
705                ivs = createDomainVerificationState(verifierId, userId, verificationId,
706                        packageName);
707            }
708            if (!hasValidDomains(filter)) {
709                return false;
710            }
711            ivs.addFilter(filter);
712            return true;
713        }
714
715        private IntentFilterVerificationState createDomainVerificationState(int verifierId,
716                int userId, int verificationId, String packageName) {
717            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
718                    verifierId, userId, packageName);
719            ivs.setPendingState();
720            synchronized (mPackages) {
721                mIntentFilterVerificationStates.append(verificationId, ivs);
722                mCurrentIntentFilterVerifications.add(verificationId);
723            }
724            return ivs;
725        }
726    }
727
728    private static boolean hasValidDomains(ActivityIntentInfo filter) {
729        return hasValidDomains(filter, true);
730    }
731
732    private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) {
733        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
734                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
735        if (!hasHTTPorHTTPS) {
736            if (logging) {
737                Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme");
738            }
739            return false;
740        }
741        return true;
742    }
743
744    private IntentFilterVerifier mIntentFilterVerifier;
745
746    // Set of pending broadcasts for aggregating enable/disable of components.
747    static class PendingPackageBroadcasts {
748        // for each user id, a map of <package name -> components within that package>
749        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
750
751        public PendingPackageBroadcasts() {
752            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
753        }
754
755        public ArrayList<String> get(int userId, String packageName) {
756            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
757            return packages.get(packageName);
758        }
759
760        public void put(int userId, String packageName, ArrayList<String> components) {
761            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
762            packages.put(packageName, components);
763        }
764
765        public void remove(int userId, String packageName) {
766            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
767            if (packages != null) {
768                packages.remove(packageName);
769            }
770        }
771
772        public void remove(int userId) {
773            mUidMap.remove(userId);
774        }
775
776        public int userIdCount() {
777            return mUidMap.size();
778        }
779
780        public int userIdAt(int n) {
781            return mUidMap.keyAt(n);
782        }
783
784        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
785            return mUidMap.get(userId);
786        }
787
788        public int size() {
789            // total number of pending broadcast entries across all userIds
790            int num = 0;
791            for (int i = 0; i< mUidMap.size(); i++) {
792                num += mUidMap.valueAt(i).size();
793            }
794            return num;
795        }
796
797        public void clear() {
798            mUidMap.clear();
799        }
800
801        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
802            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
803            if (map == null) {
804                map = new ArrayMap<String, ArrayList<String>>();
805                mUidMap.put(userId, map);
806            }
807            return map;
808        }
809    }
810    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
811
812    // Service Connection to remote media container service to copy
813    // package uri's from external media onto secure containers
814    // or internal storage.
815    private IMediaContainerService mContainerService = null;
816
817    static final int SEND_PENDING_BROADCAST = 1;
818    static final int MCS_BOUND = 3;
819    static final int END_COPY = 4;
820    static final int INIT_COPY = 5;
821    static final int MCS_UNBIND = 6;
822    static final int START_CLEANING_PACKAGE = 7;
823    static final int FIND_INSTALL_LOC = 8;
824    static final int POST_INSTALL = 9;
825    static final int MCS_RECONNECT = 10;
826    static final int MCS_GIVE_UP = 11;
827    static final int UPDATED_MEDIA_STATUS = 12;
828    static final int WRITE_SETTINGS = 13;
829    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
830    static final int PACKAGE_VERIFIED = 15;
831    static final int CHECK_PENDING_VERIFICATION = 16;
832    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
833    static final int INTENT_FILTER_VERIFIED = 18;
834
835    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
836
837    // Delay time in millisecs
838    static final int BROADCAST_DELAY = 10 * 1000;
839
840    static UserManagerService sUserManager;
841
842    // Stores a list of users whose package restrictions file needs to be updated
843    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
844
845    final private DefaultContainerConnection mDefContainerConn =
846            new DefaultContainerConnection();
847    class DefaultContainerConnection implements ServiceConnection {
848        public void onServiceConnected(ComponentName name, IBinder service) {
849            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
850            IMediaContainerService imcs =
851                IMediaContainerService.Stub.asInterface(service);
852            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
853        }
854
855        public void onServiceDisconnected(ComponentName name) {
856            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
857        }
858    };
859
860    // Recordkeeping of restore-after-install operations that are currently in flight
861    // between the Package Manager and the Backup Manager
862    class PostInstallData {
863        public InstallArgs args;
864        public PackageInstalledInfo res;
865
866        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
867            args = _a;
868            res = _r;
869        }
870    };
871    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
872    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
873
874    // backup/restore of preferred activity state
875    private static final String TAG_PREFERRED_BACKUP = "pa";
876
877    private final String mRequiredVerifierPackage;
878
879    private final PackageUsage mPackageUsage = new PackageUsage();
880
881    private class PackageUsage {
882        private static final int WRITE_INTERVAL
883            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
884
885        private final Object mFileLock = new Object();
886        private final AtomicLong mLastWritten = new AtomicLong(0);
887        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
888
889        private boolean mIsHistoricalPackageUsageAvailable = true;
890
891        boolean isHistoricalPackageUsageAvailable() {
892            return mIsHistoricalPackageUsageAvailable;
893        }
894
895        void write(boolean force) {
896            if (force) {
897                writeInternal();
898                return;
899            }
900            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
901                && !DEBUG_DEXOPT) {
902                return;
903            }
904            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
905                new Thread("PackageUsage_DiskWriter") {
906                    @Override
907                    public void run() {
908                        try {
909                            writeInternal();
910                        } finally {
911                            mBackgroundWriteRunning.set(false);
912                        }
913                    }
914                }.start();
915            }
916        }
917
918        private void writeInternal() {
919            synchronized (mPackages) {
920                synchronized (mFileLock) {
921                    AtomicFile file = getFile();
922                    FileOutputStream f = null;
923                    try {
924                        f = file.startWrite();
925                        BufferedOutputStream out = new BufferedOutputStream(f);
926                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
927                        StringBuilder sb = new StringBuilder();
928                        for (PackageParser.Package pkg : mPackages.values()) {
929                            if (pkg.mLastPackageUsageTimeInMills == 0) {
930                                continue;
931                            }
932                            sb.setLength(0);
933                            sb.append(pkg.packageName);
934                            sb.append(' ');
935                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
936                            sb.append('\n');
937                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
938                        }
939                        out.flush();
940                        file.finishWrite(f);
941                    } catch (IOException e) {
942                        if (f != null) {
943                            file.failWrite(f);
944                        }
945                        Log.e(TAG, "Failed to write package usage times", e);
946                    }
947                }
948            }
949            mLastWritten.set(SystemClock.elapsedRealtime());
950        }
951
952        void readLP() {
953            synchronized (mFileLock) {
954                AtomicFile file = getFile();
955                BufferedInputStream in = null;
956                try {
957                    in = new BufferedInputStream(file.openRead());
958                    StringBuffer sb = new StringBuffer();
959                    while (true) {
960                        String packageName = readToken(in, sb, ' ');
961                        if (packageName == null) {
962                            break;
963                        }
964                        String timeInMillisString = readToken(in, sb, '\n');
965                        if (timeInMillisString == null) {
966                            throw new IOException("Failed to find last usage time for package "
967                                                  + packageName);
968                        }
969                        PackageParser.Package pkg = mPackages.get(packageName);
970                        if (pkg == null) {
971                            continue;
972                        }
973                        long timeInMillis;
974                        try {
975                            timeInMillis = Long.parseLong(timeInMillisString.toString());
976                        } catch (NumberFormatException e) {
977                            throw new IOException("Failed to parse " + timeInMillisString
978                                                  + " as a long.", e);
979                        }
980                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
981                    }
982                } catch (FileNotFoundException expected) {
983                    mIsHistoricalPackageUsageAvailable = false;
984                } catch (IOException e) {
985                    Log.w(TAG, "Failed to read package usage times", e);
986                } finally {
987                    IoUtils.closeQuietly(in);
988                }
989            }
990            mLastWritten.set(SystemClock.elapsedRealtime());
991        }
992
993        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
994                throws IOException {
995            sb.setLength(0);
996            while (true) {
997                int ch = in.read();
998                if (ch == -1) {
999                    if (sb.length() == 0) {
1000                        return null;
1001                    }
1002                    throw new IOException("Unexpected EOF");
1003                }
1004                if (ch == endOfToken) {
1005                    return sb.toString();
1006                }
1007                sb.append((char)ch);
1008            }
1009        }
1010
1011        private AtomicFile getFile() {
1012            File dataDir = Environment.getDataDirectory();
1013            File systemDir = new File(dataDir, "system");
1014            File fname = new File(systemDir, "package-usage.list");
1015            return new AtomicFile(fname);
1016        }
1017    }
1018
1019    class PackageHandler extends Handler {
1020        private boolean mBound = false;
1021        final ArrayList<HandlerParams> mPendingInstalls =
1022            new ArrayList<HandlerParams>();
1023
1024        private boolean connectToService() {
1025            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1026                    " DefaultContainerService");
1027            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1028            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1029            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1030                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1031                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1032                mBound = true;
1033                return true;
1034            }
1035            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1036            return false;
1037        }
1038
1039        private void disconnectService() {
1040            mContainerService = null;
1041            mBound = false;
1042            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1043            mContext.unbindService(mDefContainerConn);
1044            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1045        }
1046
1047        PackageHandler(Looper looper) {
1048            super(looper);
1049        }
1050
1051        public void handleMessage(Message msg) {
1052            try {
1053                doHandleMessage(msg);
1054            } finally {
1055                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1056            }
1057        }
1058
1059        void doHandleMessage(Message msg) {
1060            switch (msg.what) {
1061                case INIT_COPY: {
1062                    HandlerParams params = (HandlerParams) msg.obj;
1063                    int idx = mPendingInstalls.size();
1064                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1065                    // If a bind was already initiated we dont really
1066                    // need to do anything. The pending install
1067                    // will be processed later on.
1068                    if (!mBound) {
1069                        // If this is the only one pending we might
1070                        // have to bind to the service again.
1071                        if (!connectToService()) {
1072                            Slog.e(TAG, "Failed to bind to media container service");
1073                            params.serviceError();
1074                            return;
1075                        } else {
1076                            // Once we bind to the service, the first
1077                            // pending request will be processed.
1078                            mPendingInstalls.add(idx, params);
1079                        }
1080                    } else {
1081                        mPendingInstalls.add(idx, params);
1082                        // Already bound to the service. Just make
1083                        // sure we trigger off processing the first request.
1084                        if (idx == 0) {
1085                            mHandler.sendEmptyMessage(MCS_BOUND);
1086                        }
1087                    }
1088                    break;
1089                }
1090                case MCS_BOUND: {
1091                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1092                    if (msg.obj != null) {
1093                        mContainerService = (IMediaContainerService) msg.obj;
1094                    }
1095                    if (mContainerService == null) {
1096                        // Something seriously wrong. Bail out
1097                        Slog.e(TAG, "Cannot bind to media container service");
1098                        for (HandlerParams params : mPendingInstalls) {
1099                            // Indicate service bind error
1100                            params.serviceError();
1101                        }
1102                        mPendingInstalls.clear();
1103                    } else if (mPendingInstalls.size() > 0) {
1104                        HandlerParams params = mPendingInstalls.get(0);
1105                        if (params != null) {
1106                            if (params.startCopy()) {
1107                                // We are done...  look for more work or to
1108                                // go idle.
1109                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1110                                        "Checking for more work or unbind...");
1111                                // Delete pending install
1112                                if (mPendingInstalls.size() > 0) {
1113                                    mPendingInstalls.remove(0);
1114                                }
1115                                if (mPendingInstalls.size() == 0) {
1116                                    if (mBound) {
1117                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1118                                                "Posting delayed MCS_UNBIND");
1119                                        removeMessages(MCS_UNBIND);
1120                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1121                                        // Unbind after a little delay, to avoid
1122                                        // continual thrashing.
1123                                        sendMessageDelayed(ubmsg, 10000);
1124                                    }
1125                                } else {
1126                                    // There are more pending requests in queue.
1127                                    // Just post MCS_BOUND message to trigger processing
1128                                    // of next pending install.
1129                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1130                                            "Posting MCS_BOUND for next work");
1131                                    mHandler.sendEmptyMessage(MCS_BOUND);
1132                                }
1133                            }
1134                        }
1135                    } else {
1136                        // Should never happen ideally.
1137                        Slog.w(TAG, "Empty queue");
1138                    }
1139                    break;
1140                }
1141                case MCS_RECONNECT: {
1142                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1143                    if (mPendingInstalls.size() > 0) {
1144                        if (mBound) {
1145                            disconnectService();
1146                        }
1147                        if (!connectToService()) {
1148                            Slog.e(TAG, "Failed to bind to media container service");
1149                            for (HandlerParams params : mPendingInstalls) {
1150                                // Indicate service bind error
1151                                params.serviceError();
1152                            }
1153                            mPendingInstalls.clear();
1154                        }
1155                    }
1156                    break;
1157                }
1158                case MCS_UNBIND: {
1159                    // If there is no actual work left, then time to unbind.
1160                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1161
1162                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1163                        if (mBound) {
1164                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1165
1166                            disconnectService();
1167                        }
1168                    } else if (mPendingInstalls.size() > 0) {
1169                        // There are more pending requests in queue.
1170                        // Just post MCS_BOUND message to trigger processing
1171                        // of next pending install.
1172                        mHandler.sendEmptyMessage(MCS_BOUND);
1173                    }
1174
1175                    break;
1176                }
1177                case MCS_GIVE_UP: {
1178                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1179                    mPendingInstalls.remove(0);
1180                    break;
1181                }
1182                case SEND_PENDING_BROADCAST: {
1183                    String packages[];
1184                    ArrayList<String> components[];
1185                    int size = 0;
1186                    int uids[];
1187                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1188                    synchronized (mPackages) {
1189                        if (mPendingBroadcasts == null) {
1190                            return;
1191                        }
1192                        size = mPendingBroadcasts.size();
1193                        if (size <= 0) {
1194                            // Nothing to be done. Just return
1195                            return;
1196                        }
1197                        packages = new String[size];
1198                        components = new ArrayList[size];
1199                        uids = new int[size];
1200                        int i = 0;  // filling out the above arrays
1201
1202                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1203                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1204                            Iterator<Map.Entry<String, ArrayList<String>>> it
1205                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1206                                            .entrySet().iterator();
1207                            while (it.hasNext() && i < size) {
1208                                Map.Entry<String, ArrayList<String>> ent = it.next();
1209                                packages[i] = ent.getKey();
1210                                components[i] = ent.getValue();
1211                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1212                                uids[i] = (ps != null)
1213                                        ? UserHandle.getUid(packageUserId, ps.appId)
1214                                        : -1;
1215                                i++;
1216                            }
1217                        }
1218                        size = i;
1219                        mPendingBroadcasts.clear();
1220                    }
1221                    // Send broadcasts
1222                    for (int i = 0; i < size; i++) {
1223                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1224                    }
1225                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1226                    break;
1227                }
1228                case START_CLEANING_PACKAGE: {
1229                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1230                    final String packageName = (String)msg.obj;
1231                    final int userId = msg.arg1;
1232                    final boolean andCode = msg.arg2 != 0;
1233                    synchronized (mPackages) {
1234                        if (userId == UserHandle.USER_ALL) {
1235                            int[] users = sUserManager.getUserIds();
1236                            for (int user : users) {
1237                                mSettings.addPackageToCleanLPw(
1238                                        new PackageCleanItem(user, packageName, andCode));
1239                            }
1240                        } else {
1241                            mSettings.addPackageToCleanLPw(
1242                                    new PackageCleanItem(userId, packageName, andCode));
1243                        }
1244                    }
1245                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1246                    startCleaningPackages();
1247                } break;
1248                case POST_INSTALL: {
1249                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1250                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1251                    mRunningInstalls.delete(msg.arg1);
1252                    boolean deleteOld = false;
1253
1254                    if (data != null) {
1255                        InstallArgs args = data.args;
1256                        PackageInstalledInfo res = data.res;
1257
1258                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1259                            res.removedInfo.sendBroadcast(false, true, false);
1260                            Bundle extras = new Bundle(1);
1261                            extras.putInt(Intent.EXTRA_UID, res.uid);
1262
1263                            // Now that we successfully installed the package, grant runtime
1264                            // permissions if requested before broadcasting the install.
1265                            if ((args.installFlags
1266                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1267                                grantRequestedRuntimePermissions(res.pkg,
1268                                        args.user.getIdentifier());
1269                            }
1270
1271                            // Determine the set of users who are adding this
1272                            // package for the first time vs. those who are seeing
1273                            // an update.
1274                            int[] firstUsers;
1275                            int[] updateUsers = new int[0];
1276                            if (res.origUsers == null || res.origUsers.length == 0) {
1277                                firstUsers = res.newUsers;
1278                            } else {
1279                                firstUsers = new int[0];
1280                                for (int i=0; i<res.newUsers.length; i++) {
1281                                    int user = res.newUsers[i];
1282                                    boolean isNew = true;
1283                                    for (int j=0; j<res.origUsers.length; j++) {
1284                                        if (res.origUsers[j] == user) {
1285                                            isNew = false;
1286                                            break;
1287                                        }
1288                                    }
1289                                    if (isNew) {
1290                                        int[] newFirst = new int[firstUsers.length+1];
1291                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1292                                                firstUsers.length);
1293                                        newFirst[firstUsers.length] = user;
1294                                        firstUsers = newFirst;
1295                                    } else {
1296                                        int[] newUpdate = new int[updateUsers.length+1];
1297                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1298                                                updateUsers.length);
1299                                        newUpdate[updateUsers.length] = user;
1300                                        updateUsers = newUpdate;
1301                                    }
1302                                }
1303                            }
1304                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1305                                    res.pkg.applicationInfo.packageName,
1306                                    extras, null, null, firstUsers);
1307                            final boolean update = res.removedInfo.removedPackage != null;
1308                            if (update) {
1309                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1310                            }
1311                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1312                                    res.pkg.applicationInfo.packageName,
1313                                    extras, null, null, updateUsers);
1314                            if (update) {
1315                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1316                                        res.pkg.applicationInfo.packageName,
1317                                        extras, null, null, updateUsers);
1318                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1319                                        null, null,
1320                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1321
1322                                // treat asec-hosted packages like removable media on upgrade
1323                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1324                                    if (DEBUG_INSTALL) {
1325                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1326                                                + " is ASEC-hosted -> AVAILABLE");
1327                                    }
1328                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1329                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1330                                    pkgList.add(res.pkg.applicationInfo.packageName);
1331                                    sendResourcesChangedBroadcast(true, true,
1332                                            pkgList,uidArray, null);
1333                                }
1334                            }
1335                            if (res.removedInfo.args != null) {
1336                                // Remove the replaced package's older resources safely now
1337                                deleteOld = true;
1338                            }
1339
1340                            // Log current value of "unknown sources" setting
1341                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1342                                getUnknownSourcesSettings());
1343                        }
1344                        // Force a gc to clear up things
1345                        Runtime.getRuntime().gc();
1346                        // We delete after a gc for applications  on sdcard.
1347                        if (deleteOld) {
1348                            synchronized (mInstallLock) {
1349                                res.removedInfo.args.doPostDeleteLI(true);
1350                            }
1351                        }
1352                        if (args.observer != null) {
1353                            try {
1354                                Bundle extras = extrasForInstallResult(res);
1355                                args.observer.onPackageInstalled(res.name, res.returnCode,
1356                                        res.returnMsg, extras);
1357                            } catch (RemoteException e) {
1358                                Slog.i(TAG, "Observer no longer exists.");
1359                            }
1360                        }
1361                    } else {
1362                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1363                    }
1364                } break;
1365                case UPDATED_MEDIA_STATUS: {
1366                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1367                    boolean reportStatus = msg.arg1 == 1;
1368                    boolean doGc = msg.arg2 == 1;
1369                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1370                    if (doGc) {
1371                        // Force a gc to clear up stale containers.
1372                        Runtime.getRuntime().gc();
1373                    }
1374                    if (msg.obj != null) {
1375                        @SuppressWarnings("unchecked")
1376                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1377                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1378                        // Unload containers
1379                        unloadAllContainers(args);
1380                    }
1381                    if (reportStatus) {
1382                        try {
1383                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1384                            PackageHelper.getMountService().finishMediaUpdate();
1385                        } catch (RemoteException e) {
1386                            Log.e(TAG, "MountService not running?");
1387                        }
1388                    }
1389                } break;
1390                case WRITE_SETTINGS: {
1391                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1392                    synchronized (mPackages) {
1393                        removeMessages(WRITE_SETTINGS);
1394                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1395                        mSettings.writeLPr();
1396                        mDirtyUsers.clear();
1397                    }
1398                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1399                } break;
1400                case WRITE_PACKAGE_RESTRICTIONS: {
1401                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1402                    synchronized (mPackages) {
1403                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1404                        for (int userId : mDirtyUsers) {
1405                            mSettings.writePackageRestrictionsLPr(userId);
1406                        }
1407                        mDirtyUsers.clear();
1408                    }
1409                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1410                } break;
1411                case CHECK_PENDING_VERIFICATION: {
1412                    final int verificationId = msg.arg1;
1413                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1414
1415                    if ((state != null) && !state.timeoutExtended()) {
1416                        final InstallArgs args = state.getInstallArgs();
1417                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1418
1419                        Slog.i(TAG, "Verification timed out for " + originUri);
1420                        mPendingVerification.remove(verificationId);
1421
1422                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1423
1424                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1425                            Slog.i(TAG, "Continuing with installation of " + originUri);
1426                            state.setVerifierResponse(Binder.getCallingUid(),
1427                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1428                            broadcastPackageVerified(verificationId, originUri,
1429                                    PackageManager.VERIFICATION_ALLOW,
1430                                    state.getInstallArgs().getUser());
1431                            try {
1432                                ret = args.copyApk(mContainerService, true);
1433                            } catch (RemoteException e) {
1434                                Slog.e(TAG, "Could not contact the ContainerService");
1435                            }
1436                        } else {
1437                            broadcastPackageVerified(verificationId, originUri,
1438                                    PackageManager.VERIFICATION_REJECT,
1439                                    state.getInstallArgs().getUser());
1440                        }
1441
1442                        processPendingInstall(args, ret);
1443                        mHandler.sendEmptyMessage(MCS_UNBIND);
1444                    }
1445                    break;
1446                }
1447                case PACKAGE_VERIFIED: {
1448                    final int verificationId = msg.arg1;
1449
1450                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1451                    if (state == null) {
1452                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1453                        break;
1454                    }
1455
1456                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1457
1458                    state.setVerifierResponse(response.callerUid, response.code);
1459
1460                    if (state.isVerificationComplete()) {
1461                        mPendingVerification.remove(verificationId);
1462
1463                        final InstallArgs args = state.getInstallArgs();
1464                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1465
1466                        int ret;
1467                        if (state.isInstallAllowed()) {
1468                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1469                            broadcastPackageVerified(verificationId, originUri,
1470                                    response.code, state.getInstallArgs().getUser());
1471                            try {
1472                                ret = args.copyApk(mContainerService, true);
1473                            } catch (RemoteException e) {
1474                                Slog.e(TAG, "Could not contact the ContainerService");
1475                            }
1476                        } else {
1477                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1478                        }
1479
1480                        processPendingInstall(args, ret);
1481
1482                        mHandler.sendEmptyMessage(MCS_UNBIND);
1483                    }
1484
1485                    break;
1486                }
1487                case START_INTENT_FILTER_VERIFICATIONS: {
1488                    int userId = msg.arg1;
1489                    int verifierUid = msg.arg2;
1490                    PackageParser.Package pkg = (PackageParser.Package)msg.obj;
1491
1492                    verifyIntentFiltersIfNeeded(userId, verifierUid, pkg);
1493                    break;
1494                }
1495                case INTENT_FILTER_VERIFIED: {
1496                    final int verificationId = msg.arg1;
1497
1498                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1499                            verificationId);
1500                    if (state == null) {
1501                        Slog.w(TAG, "Invalid IntentFilter verification token "
1502                                + verificationId + " received");
1503                        break;
1504                    }
1505
1506                    final int userId = state.getUserId();
1507
1508                    Slog.d(TAG, "Processing IntentFilter verification with token:"
1509                            + verificationId + " and userId:" + userId);
1510
1511                    final IntentFilterVerificationResponse response =
1512                            (IntentFilterVerificationResponse) msg.obj;
1513
1514                    state.setVerifierResponse(response.callerUid, response.code);
1515
1516                    Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1517                            + " and userId:" + userId
1518                            + " is settings verifier response with response code:"
1519                            + response.code);
1520
1521                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1522                        Slog.d(TAG, "Domains failing verification: "
1523                                + response.getFailedDomainsString());
1524                    }
1525
1526                    if (state.isVerificationComplete()) {
1527                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1528                    } else {
1529                        Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1530                                + " was not said to be complete");
1531                    }
1532
1533                    break;
1534                }
1535            }
1536        }
1537    }
1538
1539    private StorageEventListener mStorageListener = new StorageEventListener() {
1540        @Override
1541        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1542            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1543                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1544                    // TODO: ensure that private directories exist for all active users
1545                    // TODO: remove user data whose serial number doesn't match
1546                    loadPrivatePackages(vol);
1547                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1548                    unloadPrivatePackages(vol);
1549                }
1550            }
1551
1552            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1553                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1554                    updateExternalMediaStatus(true, false);
1555                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1556                    updateExternalMediaStatus(false, false);
1557                }
1558            }
1559        }
1560    };
1561
1562    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1563        if (userId >= UserHandle.USER_OWNER) {
1564            grantRequestedRuntimePermissionsForUser(pkg, userId);
1565        } else if (userId == UserHandle.USER_ALL) {
1566            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1567                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1568            }
1569        }
1570    }
1571
1572    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1573        SettingBase sb = (SettingBase) pkg.mExtras;
1574        if (sb == null) {
1575            return;
1576        }
1577
1578        PermissionsState permissionsState = sb.getPermissionsState();
1579
1580        for (String permission : pkg.requestedPermissions) {
1581            BasePermission bp = mSettings.mPermissions.get(permission);
1582            if (bp != null && bp.isRuntime()) {
1583                permissionsState.grantRuntimePermission(bp, userId);
1584            }
1585        }
1586    }
1587
1588    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1589        Bundle extras = null;
1590        switch (res.returnCode) {
1591            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1592                extras = new Bundle();
1593                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1594                        res.origPermission);
1595                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1596                        res.origPackage);
1597                break;
1598            }
1599        }
1600        return extras;
1601    }
1602
1603    void scheduleWriteSettingsLocked() {
1604        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1605            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1606        }
1607    }
1608
1609    void scheduleWritePackageRestrictionsLocked(int userId) {
1610        if (!sUserManager.exists(userId)) return;
1611        mDirtyUsers.add(userId);
1612        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1613            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1614        }
1615    }
1616
1617    public static PackageManagerService main(Context context, Installer installer,
1618            boolean factoryTest, boolean onlyCore) {
1619        PackageManagerService m = new PackageManagerService(context, installer,
1620                factoryTest, onlyCore);
1621        ServiceManager.addService("package", m);
1622        return m;
1623    }
1624
1625    static String[] splitString(String str, char sep) {
1626        int count = 1;
1627        int i = 0;
1628        while ((i=str.indexOf(sep, i)) >= 0) {
1629            count++;
1630            i++;
1631        }
1632
1633        String[] res = new String[count];
1634        i=0;
1635        count = 0;
1636        int lastI=0;
1637        while ((i=str.indexOf(sep, i)) >= 0) {
1638            res[count] = str.substring(lastI, i);
1639            count++;
1640            i++;
1641            lastI = i;
1642        }
1643        res[count] = str.substring(lastI, str.length());
1644        return res;
1645    }
1646
1647    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1648        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1649                Context.DISPLAY_SERVICE);
1650        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1651    }
1652
1653    public PackageManagerService(Context context, Installer installer,
1654            boolean factoryTest, boolean onlyCore) {
1655        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1656                SystemClock.uptimeMillis());
1657
1658        if (mSdkVersion <= 0) {
1659            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1660        }
1661
1662        mContext = context;
1663        mFactoryTest = factoryTest;
1664        mOnlyCore = onlyCore;
1665        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1666        mMetrics = new DisplayMetrics();
1667        mSettings = new Settings(mPackages);
1668        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1669                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1670        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1671                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1672        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1673                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1674        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1675                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1676        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1677                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1678        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1679                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1680
1681        // TODO: add a property to control this?
1682        long dexOptLRUThresholdInMinutes;
1683        if (mLazyDexOpt) {
1684            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1685        } else {
1686            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1687        }
1688        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1689
1690        String separateProcesses = SystemProperties.get("debug.separate_processes");
1691        if (separateProcesses != null && separateProcesses.length() > 0) {
1692            if ("*".equals(separateProcesses)) {
1693                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1694                mSeparateProcesses = null;
1695                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1696            } else {
1697                mDefParseFlags = 0;
1698                mSeparateProcesses = separateProcesses.split(",");
1699                Slog.w(TAG, "Running with debug.separate_processes: "
1700                        + separateProcesses);
1701            }
1702        } else {
1703            mDefParseFlags = 0;
1704            mSeparateProcesses = null;
1705        }
1706
1707        mInstaller = installer;
1708        mPackageDexOptimizer = new PackageDexOptimizer(this);
1709        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1710
1711        getDefaultDisplayMetrics(context, mMetrics);
1712
1713        SystemConfig systemConfig = SystemConfig.getInstance();
1714        mGlobalGids = systemConfig.getGlobalGids();
1715        mSystemPermissions = systemConfig.getSystemPermissions();
1716        mAvailableFeatures = systemConfig.getAvailableFeatures();
1717
1718        synchronized (mInstallLock) {
1719        // writer
1720        synchronized (mPackages) {
1721            mHandlerThread = new ServiceThread(TAG,
1722                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1723            mHandlerThread.start();
1724            mHandler = new PackageHandler(mHandlerThread.getLooper());
1725            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1726
1727            File dataDir = Environment.getDataDirectory();
1728            mAppDataDir = new File(dataDir, "data");
1729            mAppInstallDir = new File(dataDir, "app");
1730            mAppLib32InstallDir = new File(dataDir, "app-lib");
1731            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1732            mUserAppDataDir = new File(dataDir, "user");
1733            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1734
1735            sUserManager = new UserManagerService(context, this,
1736                    mInstallLock, mPackages);
1737
1738            // Propagate permission configuration in to package manager.
1739            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1740                    = systemConfig.getPermissions();
1741            for (int i=0; i<permConfig.size(); i++) {
1742                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1743                BasePermission bp = mSettings.mPermissions.get(perm.name);
1744                if (bp == null) {
1745                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1746                    mSettings.mPermissions.put(perm.name, bp);
1747                }
1748                if (perm.gids != null) {
1749                    bp.setGids(perm.gids, perm.perUser);
1750                }
1751            }
1752
1753            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1754            for (int i=0; i<libConfig.size(); i++) {
1755                mSharedLibraries.put(libConfig.keyAt(i),
1756                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1757            }
1758
1759            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1760
1761            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1762                    mSdkVersion, mOnlyCore);
1763
1764            String customResolverActivity = Resources.getSystem().getString(
1765                    R.string.config_customResolverActivity);
1766            if (TextUtils.isEmpty(customResolverActivity)) {
1767                customResolverActivity = null;
1768            } else {
1769                mCustomResolverComponentName = ComponentName.unflattenFromString(
1770                        customResolverActivity);
1771            }
1772
1773            long startTime = SystemClock.uptimeMillis();
1774
1775            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1776                    startTime);
1777
1778            // Set flag to monitor and not change apk file paths when
1779            // scanning install directories.
1780            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1781
1782            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1783
1784            /**
1785             * Add everything in the in the boot class path to the
1786             * list of process files because dexopt will have been run
1787             * if necessary during zygote startup.
1788             */
1789            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1790            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1791
1792            if (bootClassPath != null) {
1793                String[] bootClassPathElements = splitString(bootClassPath, ':');
1794                for (String element : bootClassPathElements) {
1795                    alreadyDexOpted.add(element);
1796                }
1797            } else {
1798                Slog.w(TAG, "No BOOTCLASSPATH found!");
1799            }
1800
1801            if (systemServerClassPath != null) {
1802                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1803                for (String element : systemServerClassPathElements) {
1804                    alreadyDexOpted.add(element);
1805                }
1806            } else {
1807                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1808            }
1809
1810            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1811            final String[] dexCodeInstructionSets =
1812                    getDexCodeInstructionSets(
1813                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1814
1815            /**
1816             * Ensure all external libraries have had dexopt run on them.
1817             */
1818            if (mSharedLibraries.size() > 0) {
1819                // NOTE: For now, we're compiling these system "shared libraries"
1820                // (and framework jars) into all available architectures. It's possible
1821                // to compile them only when we come across an app that uses them (there's
1822                // already logic for that in scanPackageLI) but that adds some complexity.
1823                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1824                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1825                        final String lib = libEntry.path;
1826                        if (lib == null) {
1827                            continue;
1828                        }
1829
1830                        try {
1831                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1832                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1833                                alreadyDexOpted.add(lib);
1834                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1835                            }
1836                        } catch (FileNotFoundException e) {
1837                            Slog.w(TAG, "Library not found: " + lib);
1838                        } catch (IOException e) {
1839                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1840                                    + e.getMessage());
1841                        }
1842                    }
1843                }
1844            }
1845
1846            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1847
1848            // Gross hack for now: we know this file doesn't contain any
1849            // code, so don't dexopt it to avoid the resulting log spew.
1850            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1851
1852            // Gross hack for now: we know this file is only part of
1853            // the boot class path for art, so don't dexopt it to
1854            // avoid the resulting log spew.
1855            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1856
1857            /**
1858             * And there are a number of commands implemented in Java, which
1859             * we currently need to do the dexopt on so that they can be
1860             * run from a non-root shell.
1861             */
1862            String[] frameworkFiles = frameworkDir.list();
1863            if (frameworkFiles != null) {
1864                // TODO: We could compile these only for the most preferred ABI. We should
1865                // first double check that the dex files for these commands are not referenced
1866                // by other system apps.
1867                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1868                    for (int i=0; i<frameworkFiles.length; i++) {
1869                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1870                        String path = libPath.getPath();
1871                        // Skip the file if we already did it.
1872                        if (alreadyDexOpted.contains(path)) {
1873                            continue;
1874                        }
1875                        // Skip the file if it is not a type we want to dexopt.
1876                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1877                            continue;
1878                        }
1879                        try {
1880                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1881                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1882                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1883                            }
1884                        } catch (FileNotFoundException e) {
1885                            Slog.w(TAG, "Jar not found: " + path);
1886                        } catch (IOException e) {
1887                            Slog.w(TAG, "Exception reading jar: " + path, e);
1888                        }
1889                    }
1890                }
1891            }
1892
1893            // Collect vendor overlay packages.
1894            // (Do this before scanning any apps.)
1895            // For security and version matching reason, only consider
1896            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1897            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1898            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1899                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1900
1901            // Find base frameworks (resource packages without code).
1902            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1903                    | PackageParser.PARSE_IS_SYSTEM_DIR
1904                    | PackageParser.PARSE_IS_PRIVILEGED,
1905                    scanFlags | SCAN_NO_DEX, 0);
1906
1907            // Collected privileged system packages.
1908            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1909            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1910                    | PackageParser.PARSE_IS_SYSTEM_DIR
1911                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1912
1913            // Collect ordinary system packages.
1914            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1915            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1916                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1917
1918            // Collect all vendor packages.
1919            File vendorAppDir = new File("/vendor/app");
1920            try {
1921                vendorAppDir = vendorAppDir.getCanonicalFile();
1922            } catch (IOException e) {
1923                // failed to look up canonical path, continue with original one
1924            }
1925            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1926                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1927
1928            // Collect all OEM packages.
1929            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1930            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1931                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1932
1933            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1934            mInstaller.moveFiles();
1935
1936            // Prune any system packages that no longer exist.
1937            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1938            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1939            if (!mOnlyCore) {
1940                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1941                while (psit.hasNext()) {
1942                    PackageSetting ps = psit.next();
1943
1944                    /*
1945                     * If this is not a system app, it can't be a
1946                     * disable system app.
1947                     */
1948                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1949                        continue;
1950                    }
1951
1952                    /*
1953                     * If the package is scanned, it's not erased.
1954                     */
1955                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1956                    if (scannedPkg != null) {
1957                        /*
1958                         * If the system app is both scanned and in the
1959                         * disabled packages list, then it must have been
1960                         * added via OTA. Remove it from the currently
1961                         * scanned package so the previously user-installed
1962                         * application can be scanned.
1963                         */
1964                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1965                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1966                                    + ps.name + "; removing system app.  Last known codePath="
1967                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1968                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1969                                    + scannedPkg.mVersionCode);
1970                            removePackageLI(ps, true);
1971                            expectingBetter.put(ps.name, ps.codePath);
1972                        }
1973
1974                        continue;
1975                    }
1976
1977                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1978                        psit.remove();
1979                        logCriticalInfo(Log.WARN, "System package " + ps.name
1980                                + " no longer exists; wiping its data");
1981                        removeDataDirsLI(null, ps.name);
1982                    } else {
1983                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1984                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1985                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1986                        }
1987                    }
1988                }
1989            }
1990
1991            //look for any incomplete package installations
1992            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1993            //clean up list
1994            for(int i = 0; i < deletePkgsList.size(); i++) {
1995                //clean up here
1996                cleanupInstallFailedPackage(deletePkgsList.get(i));
1997            }
1998            //delete tmp files
1999            deleteTempPackageFiles();
2000
2001            // Remove any shared userIDs that have no associated packages
2002            mSettings.pruneSharedUsersLPw();
2003
2004            if (!mOnlyCore) {
2005                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2006                        SystemClock.uptimeMillis());
2007                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2008
2009                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2010                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2011
2012                /**
2013                 * Remove disable package settings for any updated system
2014                 * apps that were removed via an OTA. If they're not a
2015                 * previously-updated app, remove them completely.
2016                 * Otherwise, just revoke their system-level permissions.
2017                 */
2018                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2019                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2020                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2021
2022                    String msg;
2023                    if (deletedPkg == null) {
2024                        msg = "Updated system package " + deletedAppName
2025                                + " no longer exists; wiping its data";
2026                        removeDataDirsLI(null, deletedAppName);
2027                    } else {
2028                        msg = "Updated system app + " + deletedAppName
2029                                + " no longer present; removing system privileges for "
2030                                + deletedAppName;
2031
2032                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2033
2034                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2035                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2036                    }
2037                    logCriticalInfo(Log.WARN, msg);
2038                }
2039
2040                /**
2041                 * Make sure all system apps that we expected to appear on
2042                 * the userdata partition actually showed up. If they never
2043                 * appeared, crawl back and revive the system version.
2044                 */
2045                for (int i = 0; i < expectingBetter.size(); i++) {
2046                    final String packageName = expectingBetter.keyAt(i);
2047                    if (!mPackages.containsKey(packageName)) {
2048                        final File scanFile = expectingBetter.valueAt(i);
2049
2050                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2051                                + " but never showed up; reverting to system");
2052
2053                        final int reparseFlags;
2054                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2055                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2056                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2057                                    | PackageParser.PARSE_IS_PRIVILEGED;
2058                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2059                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2060                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2061                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2062                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2063                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2064                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2065                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2066                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2067                        } else {
2068                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2069                            continue;
2070                        }
2071
2072                        mSettings.enableSystemPackageLPw(packageName);
2073
2074                        try {
2075                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2076                        } catch (PackageManagerException e) {
2077                            Slog.e(TAG, "Failed to parse original system package: "
2078                                    + e.getMessage());
2079                        }
2080                    }
2081                }
2082            }
2083
2084            // Now that we know all of the shared libraries, update all clients to have
2085            // the correct library paths.
2086            updateAllSharedLibrariesLPw();
2087
2088            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2089                // NOTE: We ignore potential failures here during a system scan (like
2090                // the rest of the commands above) because there's precious little we
2091                // can do about it. A settings error is reported, though.
2092                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2093                        false /* force dexopt */, false /* defer dexopt */);
2094            }
2095
2096            // Now that we know all the packages we are keeping,
2097            // read and update their last usage times.
2098            mPackageUsage.readLP();
2099
2100            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2101                    SystemClock.uptimeMillis());
2102            Slog.i(TAG, "Time to scan packages: "
2103                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2104                    + " seconds");
2105
2106            // If the platform SDK has changed since the last time we booted,
2107            // we need to re-grant app permission to catch any new ones that
2108            // appear.  This is really a hack, and means that apps can in some
2109            // cases get permissions that the user didn't initially explicitly
2110            // allow...  it would be nice to have some better way to handle
2111            // this situation.
2112            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2113                    != mSdkVersion;
2114            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2115                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2116                    + "; regranting permissions for internal storage");
2117            mSettings.mInternalSdkPlatform = mSdkVersion;
2118
2119            // For now runtime permissions are toggled via a system property.
2120            if (!RUNTIME_PERMISSIONS_ENABLED) {
2121                // Remove the runtime permissions state if the feature
2122                // was disabled by flipping the system property.
2123                mSettings.deleteRuntimePermissionsFiles();
2124            }
2125
2126            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2127                    | (regrantPermissions
2128                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2129                            : 0));
2130
2131            // If this is the first boot, and it is a normal boot, then
2132            // we need to initialize the default preferred apps.
2133            if (!mRestoredSettings && !onlyCore) {
2134                mSettings.readDefaultPreferredAppsLPw(this, 0);
2135            }
2136
2137            // If this is first boot after an OTA, and a normal boot, then
2138            // we need to clear code cache directories.
2139            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2140            if (mIsUpgrade && !onlyCore) {
2141                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2142                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2143                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2144                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2145                }
2146                mSettings.mFingerprint = Build.FINGERPRINT;
2147            }
2148
2149            // All the changes are done during package scanning.
2150            mSettings.updateInternalDatabaseVersion();
2151
2152            // can downgrade to reader
2153            mSettings.writeLPr();
2154
2155            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2156                    SystemClock.uptimeMillis());
2157
2158            mRequiredVerifierPackage = getRequiredVerifierLPr();
2159
2160            mInstallerService = new PackageInstallerService(context, this);
2161
2162            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2163            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2164                    mIntentFilterVerifierComponent);
2165
2166            primeDomainVerificationsLPw(false);
2167
2168        } // synchronized (mPackages)
2169        } // synchronized (mInstallLock)
2170
2171        // Now after opening every single application zip, make sure they
2172        // are all flushed.  Not really needed, but keeps things nice and
2173        // tidy.
2174        Runtime.getRuntime().gc();
2175    }
2176
2177    @Override
2178    public boolean isFirstBoot() {
2179        return !mRestoredSettings;
2180    }
2181
2182    @Override
2183    public boolean isOnlyCoreApps() {
2184        return mOnlyCore;
2185    }
2186
2187    @Override
2188    public boolean isUpgrade() {
2189        return mIsUpgrade;
2190    }
2191
2192    private String getRequiredVerifierLPr() {
2193        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2194        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2195                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2196
2197        String requiredVerifier = null;
2198
2199        final int N = receivers.size();
2200        for (int i = 0; i < N; i++) {
2201            final ResolveInfo info = receivers.get(i);
2202
2203            if (info.activityInfo == null) {
2204                continue;
2205            }
2206
2207            final String packageName = info.activityInfo.packageName;
2208
2209            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2210                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2211                continue;
2212            }
2213
2214            if (requiredVerifier != null) {
2215                throw new RuntimeException("There can be only one required verifier");
2216            }
2217
2218            requiredVerifier = packageName;
2219        }
2220
2221        return requiredVerifier;
2222    }
2223
2224    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2225        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2226        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2227                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2228
2229        ComponentName verifierComponentName = null;
2230
2231        int priority = -1000;
2232        final int N = receivers.size();
2233        for (int i = 0; i < N; i++) {
2234            final ResolveInfo info = receivers.get(i);
2235
2236            if (info.activityInfo == null) {
2237                continue;
2238            }
2239
2240            final String packageName = info.activityInfo.packageName;
2241
2242            final PackageSetting ps = mSettings.mPackages.get(packageName);
2243            if (ps == null) {
2244                continue;
2245            }
2246
2247            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2248                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2249                continue;
2250            }
2251
2252            // Select the IntentFilterVerifier with the highest priority
2253            if (priority < info.priority) {
2254                priority = info.priority;
2255                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2256                Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName +
2257                        " with priority: " + info.priority);
2258            }
2259        }
2260
2261        return verifierComponentName;
2262    }
2263
2264    private void primeDomainVerificationsLPw(boolean logging) {
2265        Slog.d(TAG, "Start priming domain verification");
2266        boolean updated = false;
2267        ArrayList<String> allHosts = new ArrayList<>();
2268        for (PackageParser.Package pkg : mPackages.values()) {
2269            final String packageName = pkg.packageName;
2270            if (!hasDomainURLs(pkg)) {
2271                if (logging) {
2272                    Slog.d(TAG, "No priming domain verifications for " +
2273                            "package with no domain URLs: " + packageName);
2274                }
2275                continue;
2276            }
2277            for (PackageParser.Activity a : pkg.activities) {
2278                for (ActivityIntentInfo filter : a.intents) {
2279                    if (hasValidDomains(filter, false)) {
2280                        allHosts.addAll(filter.getHostsList());
2281                    }
2282                }
2283            }
2284            if (allHosts.size() > 0) {
2285                allHosts.add("*");
2286            }
2287            IntentFilterVerificationInfo ivi =
2288                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHosts);
2289            if (ivi != null) {
2290                // We will always log this
2291                Slog.d(TAG, "Priming domain verifications for package: " + packageName);
2292                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2293                updated = true;
2294            }
2295            else {
2296                if (logging) {
2297                    Slog.d(TAG, "No priming domain verifications for package: " + packageName);
2298                }
2299            }
2300            allHosts.clear();
2301        }
2302        if (updated) {
2303            scheduleWriteSettingsLocked();
2304        }
2305        Slog.d(TAG, "End priming domain verification");
2306    }
2307
2308    @Override
2309    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2310            throws RemoteException {
2311        try {
2312            return super.onTransact(code, data, reply, flags);
2313        } catch (RuntimeException e) {
2314            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2315                Slog.wtf(TAG, "Package Manager Crash", e);
2316            }
2317            throw e;
2318        }
2319    }
2320
2321    void cleanupInstallFailedPackage(PackageSetting ps) {
2322        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2323
2324        removeDataDirsLI(ps.volumeUuid, ps.name);
2325        if (ps.codePath != null) {
2326            if (ps.codePath.isDirectory()) {
2327                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2328            } else {
2329                ps.codePath.delete();
2330            }
2331        }
2332        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2333            if (ps.resourcePath.isDirectory()) {
2334                FileUtils.deleteContents(ps.resourcePath);
2335            }
2336            ps.resourcePath.delete();
2337        }
2338        mSettings.removePackageLPw(ps.name);
2339    }
2340
2341    static int[] appendInts(int[] cur, int[] add) {
2342        if (add == null) return cur;
2343        if (cur == null) return add;
2344        final int N = add.length;
2345        for (int i=0; i<N; i++) {
2346            cur = appendInt(cur, add[i]);
2347        }
2348        return cur;
2349    }
2350
2351    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2352        if (!sUserManager.exists(userId)) return null;
2353        final PackageSetting ps = (PackageSetting) p.mExtras;
2354        if (ps == null) {
2355            return null;
2356        }
2357
2358        final PermissionsState permissionsState = ps.getPermissionsState();
2359
2360        final int[] gids = permissionsState.computeGids(userId);
2361        final Set<String> permissions = permissionsState.getPermissions(userId);
2362        final PackageUserState state = ps.readUserState(userId);
2363
2364        return PackageParser.generatePackageInfo(p, gids, flags,
2365                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2366    }
2367
2368    @Override
2369    public boolean isPackageAvailable(String packageName, int userId) {
2370        if (!sUserManager.exists(userId)) return false;
2371        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2372        synchronized (mPackages) {
2373            PackageParser.Package p = mPackages.get(packageName);
2374            if (p != null) {
2375                final PackageSetting ps = (PackageSetting) p.mExtras;
2376                if (ps != null) {
2377                    final PackageUserState state = ps.readUserState(userId);
2378                    if (state != null) {
2379                        return PackageParser.isAvailable(state);
2380                    }
2381                }
2382            }
2383        }
2384        return false;
2385    }
2386
2387    @Override
2388    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2389        if (!sUserManager.exists(userId)) return null;
2390        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2391        // reader
2392        synchronized (mPackages) {
2393            PackageParser.Package p = mPackages.get(packageName);
2394            if (DEBUG_PACKAGE_INFO)
2395                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2396            if (p != null) {
2397                return generatePackageInfo(p, flags, userId);
2398            }
2399            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2400                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2401            }
2402        }
2403        return null;
2404    }
2405
2406    @Override
2407    public String[] currentToCanonicalPackageNames(String[] names) {
2408        String[] out = new String[names.length];
2409        // reader
2410        synchronized (mPackages) {
2411            for (int i=names.length-1; i>=0; i--) {
2412                PackageSetting ps = mSettings.mPackages.get(names[i]);
2413                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2414            }
2415        }
2416        return out;
2417    }
2418
2419    @Override
2420    public String[] canonicalToCurrentPackageNames(String[] names) {
2421        String[] out = new String[names.length];
2422        // reader
2423        synchronized (mPackages) {
2424            for (int i=names.length-1; i>=0; i--) {
2425                String cur = mSettings.mRenamedPackages.get(names[i]);
2426                out[i] = cur != null ? cur : names[i];
2427            }
2428        }
2429        return out;
2430    }
2431
2432    @Override
2433    public int getPackageUid(String packageName, int userId) {
2434        if (!sUserManager.exists(userId)) return -1;
2435        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2436
2437        // reader
2438        synchronized (mPackages) {
2439            PackageParser.Package p = mPackages.get(packageName);
2440            if(p != null) {
2441                return UserHandle.getUid(userId, p.applicationInfo.uid);
2442            }
2443            PackageSetting ps = mSettings.mPackages.get(packageName);
2444            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2445                return -1;
2446            }
2447            p = ps.pkg;
2448            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2449        }
2450    }
2451
2452    @Override
2453    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2454        if (!sUserManager.exists(userId)) {
2455            return null;
2456        }
2457
2458        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2459                "getPackageGids");
2460
2461        // reader
2462        synchronized (mPackages) {
2463            PackageParser.Package p = mPackages.get(packageName);
2464            if (DEBUG_PACKAGE_INFO) {
2465                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2466            }
2467            if (p != null) {
2468                PackageSetting ps = (PackageSetting) p.mExtras;
2469                return ps.getPermissionsState().computeGids(userId);
2470            }
2471        }
2472
2473        return null;
2474    }
2475
2476    static PermissionInfo generatePermissionInfo(
2477            BasePermission bp, int flags) {
2478        if (bp.perm != null) {
2479            return PackageParser.generatePermissionInfo(bp.perm, flags);
2480        }
2481        PermissionInfo pi = new PermissionInfo();
2482        pi.name = bp.name;
2483        pi.packageName = bp.sourcePackage;
2484        pi.nonLocalizedLabel = bp.name;
2485        pi.protectionLevel = bp.protectionLevel;
2486        return pi;
2487    }
2488
2489    @Override
2490    public PermissionInfo getPermissionInfo(String name, int flags) {
2491        // reader
2492        synchronized (mPackages) {
2493            final BasePermission p = mSettings.mPermissions.get(name);
2494            if (p != null) {
2495                return generatePermissionInfo(p, flags);
2496            }
2497            return null;
2498        }
2499    }
2500
2501    @Override
2502    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2503        // reader
2504        synchronized (mPackages) {
2505            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2506            for (BasePermission p : mSettings.mPermissions.values()) {
2507                if (group == null) {
2508                    if (p.perm == null || p.perm.info.group == null) {
2509                        out.add(generatePermissionInfo(p, flags));
2510                    }
2511                } else {
2512                    if (p.perm != null && group.equals(p.perm.info.group)) {
2513                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2514                    }
2515                }
2516            }
2517
2518            if (out.size() > 0) {
2519                return out;
2520            }
2521            return mPermissionGroups.containsKey(group) ? out : null;
2522        }
2523    }
2524
2525    @Override
2526    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2527        // reader
2528        synchronized (mPackages) {
2529            return PackageParser.generatePermissionGroupInfo(
2530                    mPermissionGroups.get(name), flags);
2531        }
2532    }
2533
2534    @Override
2535    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2536        // reader
2537        synchronized (mPackages) {
2538            final int N = mPermissionGroups.size();
2539            ArrayList<PermissionGroupInfo> out
2540                    = new ArrayList<PermissionGroupInfo>(N);
2541            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2542                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2543            }
2544            return out;
2545        }
2546    }
2547
2548    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2549            int userId) {
2550        if (!sUserManager.exists(userId)) return null;
2551        PackageSetting ps = mSettings.mPackages.get(packageName);
2552        if (ps != null) {
2553            if (ps.pkg == null) {
2554                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2555                        flags, userId);
2556                if (pInfo != null) {
2557                    return pInfo.applicationInfo;
2558                }
2559                return null;
2560            }
2561            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2562                    ps.readUserState(userId), userId);
2563        }
2564        return null;
2565    }
2566
2567    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2568            int userId) {
2569        if (!sUserManager.exists(userId)) return null;
2570        PackageSetting ps = mSettings.mPackages.get(packageName);
2571        if (ps != null) {
2572            PackageParser.Package pkg = ps.pkg;
2573            if (pkg == null) {
2574                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2575                    return null;
2576                }
2577                // Only data remains, so we aren't worried about code paths
2578                pkg = new PackageParser.Package(packageName);
2579                pkg.applicationInfo.packageName = packageName;
2580                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2581                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2582                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2583                        packageName, userId).getAbsolutePath();
2584                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2585                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2586            }
2587            return generatePackageInfo(pkg, flags, userId);
2588        }
2589        return null;
2590    }
2591
2592    @Override
2593    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2594        if (!sUserManager.exists(userId)) return null;
2595        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2596        // writer
2597        synchronized (mPackages) {
2598            PackageParser.Package p = mPackages.get(packageName);
2599            if (DEBUG_PACKAGE_INFO) Log.v(
2600                    TAG, "getApplicationInfo " + packageName
2601                    + ": " + p);
2602            if (p != null) {
2603                PackageSetting ps = mSettings.mPackages.get(packageName);
2604                if (ps == null) return null;
2605                // Note: isEnabledLP() does not apply here - always return info
2606                return PackageParser.generateApplicationInfo(
2607                        p, flags, ps.readUserState(userId), userId);
2608            }
2609            if ("android".equals(packageName)||"system".equals(packageName)) {
2610                return mAndroidApplication;
2611            }
2612            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2613                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2614            }
2615        }
2616        return null;
2617    }
2618
2619    @Override
2620    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2621            final IPackageDataObserver observer) {
2622        mContext.enforceCallingOrSelfPermission(
2623                android.Manifest.permission.CLEAR_APP_CACHE, null);
2624        // Queue up an async operation since clearing cache may take a little while.
2625        mHandler.post(new Runnable() {
2626            public void run() {
2627                mHandler.removeCallbacks(this);
2628                int retCode = -1;
2629                synchronized (mInstallLock) {
2630                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2631                    if (retCode < 0) {
2632                        Slog.w(TAG, "Couldn't clear application caches");
2633                    }
2634                }
2635                if (observer != null) {
2636                    try {
2637                        observer.onRemoveCompleted(null, (retCode >= 0));
2638                    } catch (RemoteException e) {
2639                        Slog.w(TAG, "RemoveException when invoking call back");
2640                    }
2641                }
2642            }
2643        });
2644    }
2645
2646    @Override
2647    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2648            final IntentSender pi) {
2649        mContext.enforceCallingOrSelfPermission(
2650                android.Manifest.permission.CLEAR_APP_CACHE, null);
2651        // Queue up an async operation since clearing cache may take a little while.
2652        mHandler.post(new Runnable() {
2653            public void run() {
2654                mHandler.removeCallbacks(this);
2655                int retCode = -1;
2656                synchronized (mInstallLock) {
2657                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2658                    if (retCode < 0) {
2659                        Slog.w(TAG, "Couldn't clear application caches");
2660                    }
2661                }
2662                if(pi != null) {
2663                    try {
2664                        // Callback via pending intent
2665                        int code = (retCode >= 0) ? 1 : 0;
2666                        pi.sendIntent(null, code, null,
2667                                null, null);
2668                    } catch (SendIntentException e1) {
2669                        Slog.i(TAG, "Failed to send pending intent");
2670                    }
2671                }
2672            }
2673        });
2674    }
2675
2676    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2677        synchronized (mInstallLock) {
2678            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2679                throw new IOException("Failed to free enough space");
2680            }
2681        }
2682    }
2683
2684    @Override
2685    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2686        if (!sUserManager.exists(userId)) return null;
2687        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2688        synchronized (mPackages) {
2689            PackageParser.Activity a = mActivities.mActivities.get(component);
2690
2691            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2692            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2693                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2694                if (ps == null) return null;
2695                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2696                        userId);
2697            }
2698            if (mResolveComponentName.equals(component)) {
2699                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2700                        new PackageUserState(), userId);
2701            }
2702        }
2703        return null;
2704    }
2705
2706    @Override
2707    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2708            String resolvedType) {
2709        synchronized (mPackages) {
2710            PackageParser.Activity a = mActivities.mActivities.get(component);
2711            if (a == null) {
2712                return false;
2713            }
2714            for (int i=0; i<a.intents.size(); i++) {
2715                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2716                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2717                    return true;
2718                }
2719            }
2720            return false;
2721        }
2722    }
2723
2724    @Override
2725    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2726        if (!sUserManager.exists(userId)) return null;
2727        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2728        synchronized (mPackages) {
2729            PackageParser.Activity a = mReceivers.mActivities.get(component);
2730            if (DEBUG_PACKAGE_INFO) Log.v(
2731                TAG, "getReceiverInfo " + component + ": " + a);
2732            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2733                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2734                if (ps == null) return null;
2735                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2736                        userId);
2737            }
2738        }
2739        return null;
2740    }
2741
2742    @Override
2743    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2744        if (!sUserManager.exists(userId)) return null;
2745        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2746        synchronized (mPackages) {
2747            PackageParser.Service s = mServices.mServices.get(component);
2748            if (DEBUG_PACKAGE_INFO) Log.v(
2749                TAG, "getServiceInfo " + component + ": " + s);
2750            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2751                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2752                if (ps == null) return null;
2753                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2754                        userId);
2755            }
2756        }
2757        return null;
2758    }
2759
2760    @Override
2761    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2762        if (!sUserManager.exists(userId)) return null;
2763        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2764        synchronized (mPackages) {
2765            PackageParser.Provider p = mProviders.mProviders.get(component);
2766            if (DEBUG_PACKAGE_INFO) Log.v(
2767                TAG, "getProviderInfo " + component + ": " + p);
2768            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2769                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2770                if (ps == null) return null;
2771                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2772                        userId);
2773            }
2774        }
2775        return null;
2776    }
2777
2778    @Override
2779    public String[] getSystemSharedLibraryNames() {
2780        Set<String> libSet;
2781        synchronized (mPackages) {
2782            libSet = mSharedLibraries.keySet();
2783            int size = libSet.size();
2784            if (size > 0) {
2785                String[] libs = new String[size];
2786                libSet.toArray(libs);
2787                return libs;
2788            }
2789        }
2790        return null;
2791    }
2792
2793    /**
2794     * @hide
2795     */
2796    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2797        synchronized (mPackages) {
2798            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2799            if (lib != null && lib.apk != null) {
2800                return mPackages.get(lib.apk);
2801            }
2802        }
2803        return null;
2804    }
2805
2806    @Override
2807    public FeatureInfo[] getSystemAvailableFeatures() {
2808        Collection<FeatureInfo> featSet;
2809        synchronized (mPackages) {
2810            featSet = mAvailableFeatures.values();
2811            int size = featSet.size();
2812            if (size > 0) {
2813                FeatureInfo[] features = new FeatureInfo[size+1];
2814                featSet.toArray(features);
2815                FeatureInfo fi = new FeatureInfo();
2816                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2817                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2818                features[size] = fi;
2819                return features;
2820            }
2821        }
2822        return null;
2823    }
2824
2825    @Override
2826    public boolean hasSystemFeature(String name) {
2827        synchronized (mPackages) {
2828            return mAvailableFeatures.containsKey(name);
2829        }
2830    }
2831
2832    private void checkValidCaller(int uid, int userId) {
2833        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2834            return;
2835
2836        throw new SecurityException("Caller uid=" + uid
2837                + " is not privileged to communicate with user=" + userId);
2838    }
2839
2840    @Override
2841    public int checkPermission(String permName, String pkgName, int userId) {
2842        if (!sUserManager.exists(userId)) {
2843            return PackageManager.PERMISSION_DENIED;
2844        }
2845
2846        synchronized (mPackages) {
2847            final PackageParser.Package p = mPackages.get(pkgName);
2848            if (p != null && p.mExtras != null) {
2849                final PackageSetting ps = (PackageSetting) p.mExtras;
2850                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2851                    return PackageManager.PERMISSION_GRANTED;
2852                }
2853            }
2854        }
2855
2856        return PackageManager.PERMISSION_DENIED;
2857    }
2858
2859    @Override
2860    public int checkUidPermission(String permName, int uid) {
2861        final int userId = UserHandle.getUserId(uid);
2862
2863        if (!sUserManager.exists(userId)) {
2864            return PackageManager.PERMISSION_DENIED;
2865        }
2866
2867        synchronized (mPackages) {
2868            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2869            if (obj != null) {
2870                final SettingBase ps = (SettingBase) obj;
2871                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2872                    return PackageManager.PERMISSION_GRANTED;
2873                }
2874            } else {
2875                ArraySet<String> perms = mSystemPermissions.get(uid);
2876                if (perms != null && perms.contains(permName)) {
2877                    return PackageManager.PERMISSION_GRANTED;
2878                }
2879            }
2880        }
2881
2882        return PackageManager.PERMISSION_DENIED;
2883    }
2884
2885    /**
2886     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2887     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2888     * @param checkShell TODO(yamasani):
2889     * @param message the message to log on security exception
2890     */
2891    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2892            boolean checkShell, String message) {
2893        if (userId < 0) {
2894            throw new IllegalArgumentException("Invalid userId " + userId);
2895        }
2896        if (checkShell) {
2897            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2898        }
2899        if (userId == UserHandle.getUserId(callingUid)) return;
2900        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2901            if (requireFullPermission) {
2902                mContext.enforceCallingOrSelfPermission(
2903                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2904            } else {
2905                try {
2906                    mContext.enforceCallingOrSelfPermission(
2907                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2908                } catch (SecurityException se) {
2909                    mContext.enforceCallingOrSelfPermission(
2910                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2911                }
2912            }
2913        }
2914    }
2915
2916    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2917        if (callingUid == Process.SHELL_UID) {
2918            if (userHandle >= 0
2919                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2920                throw new SecurityException("Shell does not have permission to access user "
2921                        + userHandle);
2922            } else if (userHandle < 0) {
2923                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2924                        + Debug.getCallers(3));
2925            }
2926        }
2927    }
2928
2929    private BasePermission findPermissionTreeLP(String permName) {
2930        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2931            if (permName.startsWith(bp.name) &&
2932                    permName.length() > bp.name.length() &&
2933                    permName.charAt(bp.name.length()) == '.') {
2934                return bp;
2935            }
2936        }
2937        return null;
2938    }
2939
2940    private BasePermission checkPermissionTreeLP(String permName) {
2941        if (permName != null) {
2942            BasePermission bp = findPermissionTreeLP(permName);
2943            if (bp != null) {
2944                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2945                    return bp;
2946                }
2947                throw new SecurityException("Calling uid "
2948                        + Binder.getCallingUid()
2949                        + " is not allowed to add to permission tree "
2950                        + bp.name + " owned by uid " + bp.uid);
2951            }
2952        }
2953        throw new SecurityException("No permission tree found for " + permName);
2954    }
2955
2956    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2957        if (s1 == null) {
2958            return s2 == null;
2959        }
2960        if (s2 == null) {
2961            return false;
2962        }
2963        if (s1.getClass() != s2.getClass()) {
2964            return false;
2965        }
2966        return s1.equals(s2);
2967    }
2968
2969    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2970        if (pi1.icon != pi2.icon) return false;
2971        if (pi1.logo != pi2.logo) return false;
2972        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2973        if (!compareStrings(pi1.name, pi2.name)) return false;
2974        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2975        // We'll take care of setting this one.
2976        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2977        // These are not currently stored in settings.
2978        //if (!compareStrings(pi1.group, pi2.group)) return false;
2979        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2980        //if (pi1.labelRes != pi2.labelRes) return false;
2981        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2982        return true;
2983    }
2984
2985    int permissionInfoFootprint(PermissionInfo info) {
2986        int size = info.name.length();
2987        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2988        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2989        return size;
2990    }
2991
2992    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2993        int size = 0;
2994        for (BasePermission perm : mSettings.mPermissions.values()) {
2995            if (perm.uid == tree.uid) {
2996                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2997            }
2998        }
2999        return size;
3000    }
3001
3002    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3003        // We calculate the max size of permissions defined by this uid and throw
3004        // if that plus the size of 'info' would exceed our stated maximum.
3005        if (tree.uid != Process.SYSTEM_UID) {
3006            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3007            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3008                throw new SecurityException("Permission tree size cap exceeded");
3009            }
3010        }
3011    }
3012
3013    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3014        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3015            throw new SecurityException("Label must be specified in permission");
3016        }
3017        BasePermission tree = checkPermissionTreeLP(info.name);
3018        BasePermission bp = mSettings.mPermissions.get(info.name);
3019        boolean added = bp == null;
3020        boolean changed = true;
3021        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3022        if (added) {
3023            enforcePermissionCapLocked(info, tree);
3024            bp = new BasePermission(info.name, tree.sourcePackage,
3025                    BasePermission.TYPE_DYNAMIC);
3026        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3027            throw new SecurityException(
3028                    "Not allowed to modify non-dynamic permission "
3029                    + info.name);
3030        } else {
3031            if (bp.protectionLevel == fixedLevel
3032                    && bp.perm.owner.equals(tree.perm.owner)
3033                    && bp.uid == tree.uid
3034                    && comparePermissionInfos(bp.perm.info, info)) {
3035                changed = false;
3036            }
3037        }
3038        bp.protectionLevel = fixedLevel;
3039        info = new PermissionInfo(info);
3040        info.protectionLevel = fixedLevel;
3041        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3042        bp.perm.info.packageName = tree.perm.info.packageName;
3043        bp.uid = tree.uid;
3044        if (added) {
3045            mSettings.mPermissions.put(info.name, bp);
3046        }
3047        if (changed) {
3048            if (!async) {
3049                mSettings.writeLPr();
3050            } else {
3051                scheduleWriteSettingsLocked();
3052            }
3053        }
3054        return added;
3055    }
3056
3057    @Override
3058    public boolean addPermission(PermissionInfo info) {
3059        synchronized (mPackages) {
3060            return addPermissionLocked(info, false);
3061        }
3062    }
3063
3064    @Override
3065    public boolean addPermissionAsync(PermissionInfo info) {
3066        synchronized (mPackages) {
3067            return addPermissionLocked(info, true);
3068        }
3069    }
3070
3071    @Override
3072    public void removePermission(String name) {
3073        synchronized (mPackages) {
3074            checkPermissionTreeLP(name);
3075            BasePermission bp = mSettings.mPermissions.get(name);
3076            if (bp != null) {
3077                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3078                    throw new SecurityException(
3079                            "Not allowed to modify non-dynamic permission "
3080                            + name);
3081                }
3082                mSettings.mPermissions.remove(name);
3083                mSettings.writeLPr();
3084            }
3085        }
3086    }
3087
3088    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3089            BasePermission bp) {
3090        int index = pkg.requestedPermissions.indexOf(bp.name);
3091        if (index == -1) {
3092            throw new SecurityException("Package " + pkg.packageName
3093                    + " has not requested permission " + bp.name);
3094        }
3095        if (!bp.isRuntime()) {
3096            throw new SecurityException("Permission " + bp.name
3097                    + " is not a changeable permission type");
3098        }
3099    }
3100
3101    @Override
3102    public boolean grantPermission(String packageName, String name, int userId) {
3103        if (!RUNTIME_PERMISSIONS_ENABLED) {
3104            return false;
3105        }
3106
3107        if (!sUserManager.exists(userId)) {
3108            return false;
3109        }
3110
3111        mContext.enforceCallingOrSelfPermission(
3112                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3113                "grantPermission");
3114
3115        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3116                "grantPermission");
3117
3118        boolean gidsChanged = false;
3119        final SettingBase sb;
3120
3121        synchronized (mPackages) {
3122            final PackageParser.Package pkg = mPackages.get(packageName);
3123            if (pkg == null) {
3124                throw new IllegalArgumentException("Unknown package: " + packageName);
3125            }
3126
3127            final BasePermission bp = mSettings.mPermissions.get(name);
3128            if (bp == null) {
3129                throw new IllegalArgumentException("Unknown permission: " + name);
3130            }
3131
3132            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3133
3134            sb = (SettingBase) pkg.mExtras;
3135            if (sb == null) {
3136                throw new IllegalArgumentException("Unknown package: " + packageName);
3137            }
3138
3139            final PermissionsState permissionsState = sb.getPermissionsState();
3140
3141            final int result = permissionsState.grantRuntimePermission(bp, userId);
3142            switch (result) {
3143                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3144                    return false;
3145                }
3146
3147                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3148                    gidsChanged = true;
3149                } break;
3150            }
3151
3152            // Not critical if that is lost - app has to request again.
3153            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3154        }
3155
3156        if (gidsChanged) {
3157            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3158        }
3159
3160        return true;
3161    }
3162
3163    @Override
3164    public boolean revokePermission(String packageName, String name, int userId) {
3165        if (!RUNTIME_PERMISSIONS_ENABLED) {
3166            return false;
3167        }
3168
3169        if (!sUserManager.exists(userId)) {
3170            return false;
3171        }
3172
3173        mContext.enforceCallingOrSelfPermission(
3174                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3175                "revokePermission");
3176
3177        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3178                "revokePermission");
3179
3180        final SettingBase sb;
3181
3182        synchronized (mPackages) {
3183            final PackageParser.Package pkg = mPackages.get(packageName);
3184            if (pkg == null) {
3185                throw new IllegalArgumentException("Unknown package: " + packageName);
3186            }
3187
3188            final BasePermission bp = mSettings.mPermissions.get(name);
3189            if (bp == null) {
3190                throw new IllegalArgumentException("Unknown permission: " + name);
3191            }
3192
3193            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3194
3195            sb = (SettingBase) pkg.mExtras;
3196            if (sb == null) {
3197                throw new IllegalArgumentException("Unknown package: " + packageName);
3198            }
3199
3200            final PermissionsState permissionsState = sb.getPermissionsState();
3201
3202            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3203                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3204                return false;
3205            }
3206
3207            // Critical, after this call all should never have the permission.
3208            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3209        }
3210
3211        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3212
3213        return true;
3214    }
3215
3216    @Override
3217    public boolean isProtectedBroadcast(String actionName) {
3218        synchronized (mPackages) {
3219            return mProtectedBroadcasts.contains(actionName);
3220        }
3221    }
3222
3223    @Override
3224    public int checkSignatures(String pkg1, String pkg2) {
3225        synchronized (mPackages) {
3226            final PackageParser.Package p1 = mPackages.get(pkg1);
3227            final PackageParser.Package p2 = mPackages.get(pkg2);
3228            if (p1 == null || p1.mExtras == null
3229                    || p2 == null || p2.mExtras == null) {
3230                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3231            }
3232            return compareSignatures(p1.mSignatures, p2.mSignatures);
3233        }
3234    }
3235
3236    @Override
3237    public int checkUidSignatures(int uid1, int uid2) {
3238        // Map to base uids.
3239        uid1 = UserHandle.getAppId(uid1);
3240        uid2 = UserHandle.getAppId(uid2);
3241        // reader
3242        synchronized (mPackages) {
3243            Signature[] s1;
3244            Signature[] s2;
3245            Object obj = mSettings.getUserIdLPr(uid1);
3246            if (obj != null) {
3247                if (obj instanceof SharedUserSetting) {
3248                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3249                } else if (obj instanceof PackageSetting) {
3250                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3251                } else {
3252                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3253                }
3254            } else {
3255                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3256            }
3257            obj = mSettings.getUserIdLPr(uid2);
3258            if (obj != null) {
3259                if (obj instanceof SharedUserSetting) {
3260                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3261                } else if (obj instanceof PackageSetting) {
3262                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3263                } else {
3264                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3265                }
3266            } else {
3267                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3268            }
3269            return compareSignatures(s1, s2);
3270        }
3271    }
3272
3273    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3274        final long identity = Binder.clearCallingIdentity();
3275        try {
3276            if (sb instanceof SharedUserSetting) {
3277                SharedUserSetting sus = (SharedUserSetting) sb;
3278                final int packageCount = sus.packages.size();
3279                for (int i = 0; i < packageCount; i++) {
3280                    PackageSetting susPs = sus.packages.valueAt(i);
3281                    if (userId == UserHandle.USER_ALL) {
3282                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3283                    } else {
3284                        final int uid = UserHandle.getUid(userId, susPs.appId);
3285                        killUid(uid, reason);
3286                    }
3287                }
3288            } else if (sb instanceof PackageSetting) {
3289                PackageSetting ps = (PackageSetting) sb;
3290                if (userId == UserHandle.USER_ALL) {
3291                    killApplication(ps.pkg.packageName, ps.appId, reason);
3292                } else {
3293                    final int uid = UserHandle.getUid(userId, ps.appId);
3294                    killUid(uid, reason);
3295                }
3296            }
3297        } finally {
3298            Binder.restoreCallingIdentity(identity);
3299        }
3300    }
3301
3302    private static void killUid(int uid, String reason) {
3303        IActivityManager am = ActivityManagerNative.getDefault();
3304        if (am != null) {
3305            try {
3306                am.killUid(uid, reason);
3307            } catch (RemoteException e) {
3308                /* ignore - same process */
3309            }
3310        }
3311    }
3312
3313    /**
3314     * Compares two sets of signatures. Returns:
3315     * <br />
3316     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3317     * <br />
3318     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3319     * <br />
3320     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3321     * <br />
3322     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3323     * <br />
3324     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3325     */
3326    static int compareSignatures(Signature[] s1, Signature[] s2) {
3327        if (s1 == null) {
3328            return s2 == null
3329                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3330                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3331        }
3332
3333        if (s2 == null) {
3334            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3335        }
3336
3337        if (s1.length != s2.length) {
3338            return PackageManager.SIGNATURE_NO_MATCH;
3339        }
3340
3341        // Since both signature sets are of size 1, we can compare without HashSets.
3342        if (s1.length == 1) {
3343            return s1[0].equals(s2[0]) ?
3344                    PackageManager.SIGNATURE_MATCH :
3345                    PackageManager.SIGNATURE_NO_MATCH;
3346        }
3347
3348        ArraySet<Signature> set1 = new ArraySet<Signature>();
3349        for (Signature sig : s1) {
3350            set1.add(sig);
3351        }
3352        ArraySet<Signature> set2 = new ArraySet<Signature>();
3353        for (Signature sig : s2) {
3354            set2.add(sig);
3355        }
3356        // Make sure s2 contains all signatures in s1.
3357        if (set1.equals(set2)) {
3358            return PackageManager.SIGNATURE_MATCH;
3359        }
3360        return PackageManager.SIGNATURE_NO_MATCH;
3361    }
3362
3363    /**
3364     * If the database version for this type of package (internal storage or
3365     * external storage) is less than the version where package signatures
3366     * were updated, return true.
3367     */
3368    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3369        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3370                DatabaseVersion.SIGNATURE_END_ENTITY))
3371                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3372                        DatabaseVersion.SIGNATURE_END_ENTITY));
3373    }
3374
3375    /**
3376     * Used for backward compatibility to make sure any packages with
3377     * certificate chains get upgraded to the new style. {@code existingSigs}
3378     * will be in the old format (since they were stored on disk from before the
3379     * system upgrade) and {@code scannedSigs} will be in the newer format.
3380     */
3381    private int compareSignaturesCompat(PackageSignatures existingSigs,
3382            PackageParser.Package scannedPkg) {
3383        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3384            return PackageManager.SIGNATURE_NO_MATCH;
3385        }
3386
3387        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3388        for (Signature sig : existingSigs.mSignatures) {
3389            existingSet.add(sig);
3390        }
3391        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3392        for (Signature sig : scannedPkg.mSignatures) {
3393            try {
3394                Signature[] chainSignatures = sig.getChainSignatures();
3395                for (Signature chainSig : chainSignatures) {
3396                    scannedCompatSet.add(chainSig);
3397                }
3398            } catch (CertificateEncodingException e) {
3399                scannedCompatSet.add(sig);
3400            }
3401        }
3402        /*
3403         * Make sure the expanded scanned set contains all signatures in the
3404         * existing one.
3405         */
3406        if (scannedCompatSet.equals(existingSet)) {
3407            // Migrate the old signatures to the new scheme.
3408            existingSigs.assignSignatures(scannedPkg.mSignatures);
3409            // The new KeySets will be re-added later in the scanning process.
3410            synchronized (mPackages) {
3411                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3412            }
3413            return PackageManager.SIGNATURE_MATCH;
3414        }
3415        return PackageManager.SIGNATURE_NO_MATCH;
3416    }
3417
3418    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3419        if (isExternal(scannedPkg)) {
3420            return mSettings.isExternalDatabaseVersionOlderThan(
3421                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3422        } else {
3423            return mSettings.isInternalDatabaseVersionOlderThan(
3424                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3425        }
3426    }
3427
3428    private int compareSignaturesRecover(PackageSignatures existingSigs,
3429            PackageParser.Package scannedPkg) {
3430        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3431            return PackageManager.SIGNATURE_NO_MATCH;
3432        }
3433
3434        String msg = null;
3435        try {
3436            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3437                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3438                        + scannedPkg.packageName);
3439                return PackageManager.SIGNATURE_MATCH;
3440            }
3441        } catch (CertificateException e) {
3442            msg = e.getMessage();
3443        }
3444
3445        logCriticalInfo(Log.INFO,
3446                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3447        return PackageManager.SIGNATURE_NO_MATCH;
3448    }
3449
3450    @Override
3451    public String[] getPackagesForUid(int uid) {
3452        uid = UserHandle.getAppId(uid);
3453        // reader
3454        synchronized (mPackages) {
3455            Object obj = mSettings.getUserIdLPr(uid);
3456            if (obj instanceof SharedUserSetting) {
3457                final SharedUserSetting sus = (SharedUserSetting) obj;
3458                final int N = sus.packages.size();
3459                final String[] res = new String[N];
3460                final Iterator<PackageSetting> it = sus.packages.iterator();
3461                int i = 0;
3462                while (it.hasNext()) {
3463                    res[i++] = it.next().name;
3464                }
3465                return res;
3466            } else if (obj instanceof PackageSetting) {
3467                final PackageSetting ps = (PackageSetting) obj;
3468                return new String[] { ps.name };
3469            }
3470        }
3471        return null;
3472    }
3473
3474    @Override
3475    public String getNameForUid(int uid) {
3476        // reader
3477        synchronized (mPackages) {
3478            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3479            if (obj instanceof SharedUserSetting) {
3480                final SharedUserSetting sus = (SharedUserSetting) obj;
3481                return sus.name + ":" + sus.userId;
3482            } else if (obj instanceof PackageSetting) {
3483                final PackageSetting ps = (PackageSetting) obj;
3484                return ps.name;
3485            }
3486        }
3487        return null;
3488    }
3489
3490    @Override
3491    public int getUidForSharedUser(String sharedUserName) {
3492        if(sharedUserName == null) {
3493            return -1;
3494        }
3495        // reader
3496        synchronized (mPackages) {
3497            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3498            if (suid == null) {
3499                return -1;
3500            }
3501            return suid.userId;
3502        }
3503    }
3504
3505    @Override
3506    public int getFlagsForUid(int uid) {
3507        synchronized (mPackages) {
3508            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3509            if (obj instanceof SharedUserSetting) {
3510                final SharedUserSetting sus = (SharedUserSetting) obj;
3511                return sus.pkgFlags;
3512            } else if (obj instanceof PackageSetting) {
3513                final PackageSetting ps = (PackageSetting) obj;
3514                return ps.pkgFlags;
3515            }
3516        }
3517        return 0;
3518    }
3519
3520    @Override
3521    public int getPrivateFlagsForUid(int uid) {
3522        synchronized (mPackages) {
3523            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3524            if (obj instanceof SharedUserSetting) {
3525                final SharedUserSetting sus = (SharedUserSetting) obj;
3526                return sus.pkgPrivateFlags;
3527            } else if (obj instanceof PackageSetting) {
3528                final PackageSetting ps = (PackageSetting) obj;
3529                return ps.pkgPrivateFlags;
3530            }
3531        }
3532        return 0;
3533    }
3534
3535    @Override
3536    public boolean isUidPrivileged(int uid) {
3537        uid = UserHandle.getAppId(uid);
3538        // reader
3539        synchronized (mPackages) {
3540            Object obj = mSettings.getUserIdLPr(uid);
3541            if (obj instanceof SharedUserSetting) {
3542                final SharedUserSetting sus = (SharedUserSetting) obj;
3543                final Iterator<PackageSetting> it = sus.packages.iterator();
3544                while (it.hasNext()) {
3545                    if (it.next().isPrivileged()) {
3546                        return true;
3547                    }
3548                }
3549            } else if (obj instanceof PackageSetting) {
3550                final PackageSetting ps = (PackageSetting) obj;
3551                return ps.isPrivileged();
3552            }
3553        }
3554        return false;
3555    }
3556
3557    @Override
3558    public String[] getAppOpPermissionPackages(String permissionName) {
3559        synchronized (mPackages) {
3560            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3561            if (pkgs == null) {
3562                return null;
3563            }
3564            return pkgs.toArray(new String[pkgs.size()]);
3565        }
3566    }
3567
3568    @Override
3569    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3570            int flags, int userId) {
3571        if (!sUserManager.exists(userId)) return null;
3572        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3573        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3574        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3575    }
3576
3577    @Override
3578    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3579            IntentFilter filter, int match, ComponentName activity) {
3580        final int userId = UserHandle.getCallingUserId();
3581        if (DEBUG_PREFERRED) {
3582            Log.v(TAG, "setLastChosenActivity intent=" + intent
3583                + " resolvedType=" + resolvedType
3584                + " flags=" + flags
3585                + " filter=" + filter
3586                + " match=" + match
3587                + " activity=" + activity);
3588            filter.dump(new PrintStreamPrinter(System.out), "    ");
3589        }
3590        intent.setComponent(null);
3591        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3592        // Find any earlier preferred or last chosen entries and nuke them
3593        findPreferredActivity(intent, resolvedType,
3594                flags, query, 0, false, true, false, userId);
3595        // Add the new activity as the last chosen for this filter
3596        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3597                "Setting last chosen");
3598    }
3599
3600    @Override
3601    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3602        final int userId = UserHandle.getCallingUserId();
3603        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3604        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3605        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3606                false, false, false, userId);
3607    }
3608
3609    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3610            int flags, List<ResolveInfo> query, int userId) {
3611        if (query != null) {
3612            final int N = query.size();
3613            if (N == 1) {
3614                return query.get(0);
3615            } else if (N > 1) {
3616                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3617                // If there is more than one activity with the same priority,
3618                // then let the user decide between them.
3619                ResolveInfo r0 = query.get(0);
3620                ResolveInfo r1 = query.get(1);
3621                if (DEBUG_INTENT_MATCHING || debug) {
3622                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3623                            + r1.activityInfo.name + "=" + r1.priority);
3624                }
3625                // If the first activity has a higher priority, or a different
3626                // default, then it is always desireable to pick it.
3627                if (r0.priority != r1.priority
3628                        || r0.preferredOrder != r1.preferredOrder
3629                        || r0.isDefault != r1.isDefault) {
3630                    return query.get(0);
3631                }
3632                // If we have saved a preference for a preferred activity for
3633                // this Intent, use that.
3634                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3635                        flags, query, r0.priority, true, false, debug, userId);
3636                if (ri != null) {
3637                    return ri;
3638                }
3639                if (userId != 0) {
3640                    ri = new ResolveInfo(mResolveInfo);
3641                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3642                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3643                            ri.activityInfo.applicationInfo);
3644                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3645                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3646                    return ri;
3647                }
3648                return mResolveInfo;
3649            }
3650        }
3651        return null;
3652    }
3653
3654    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3655            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3656        final int N = query.size();
3657        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3658                .get(userId);
3659        // Get the list of persistent preferred activities that handle the intent
3660        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3661        List<PersistentPreferredActivity> pprefs = ppir != null
3662                ? ppir.queryIntent(intent, resolvedType,
3663                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3664                : null;
3665        if (pprefs != null && pprefs.size() > 0) {
3666            final int M = pprefs.size();
3667            for (int i=0; i<M; i++) {
3668                final PersistentPreferredActivity ppa = pprefs.get(i);
3669                if (DEBUG_PREFERRED || debug) {
3670                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3671                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3672                            + "\n  component=" + ppa.mComponent);
3673                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3674                }
3675                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3676                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3677                if (DEBUG_PREFERRED || debug) {
3678                    Slog.v(TAG, "Found persistent preferred activity:");
3679                    if (ai != null) {
3680                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3681                    } else {
3682                        Slog.v(TAG, "  null");
3683                    }
3684                }
3685                if (ai == null) {
3686                    // This previously registered persistent preferred activity
3687                    // component is no longer known. Ignore it and do NOT remove it.
3688                    continue;
3689                }
3690                for (int j=0; j<N; j++) {
3691                    final ResolveInfo ri = query.get(j);
3692                    if (!ri.activityInfo.applicationInfo.packageName
3693                            .equals(ai.applicationInfo.packageName)) {
3694                        continue;
3695                    }
3696                    if (!ri.activityInfo.name.equals(ai.name)) {
3697                        continue;
3698                    }
3699                    //  Found a persistent preference that can handle the intent.
3700                    if (DEBUG_PREFERRED || debug) {
3701                        Slog.v(TAG, "Returning persistent preferred activity: " +
3702                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3703                    }
3704                    return ri;
3705                }
3706            }
3707        }
3708        return null;
3709    }
3710
3711    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3712            List<ResolveInfo> query, int priority, boolean always,
3713            boolean removeMatches, boolean debug, int userId) {
3714        if (!sUserManager.exists(userId)) return null;
3715        // writer
3716        synchronized (mPackages) {
3717            if (intent.getSelector() != null) {
3718                intent = intent.getSelector();
3719            }
3720            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3721
3722            // Try to find a matching persistent preferred activity.
3723            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3724                    debug, userId);
3725
3726            // If a persistent preferred activity matched, use it.
3727            if (pri != null) {
3728                return pri;
3729            }
3730
3731            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3732            // Get the list of preferred activities that handle the intent
3733            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3734            List<PreferredActivity> prefs = pir != null
3735                    ? pir.queryIntent(intent, resolvedType,
3736                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3737                    : null;
3738            if (prefs != null && prefs.size() > 0) {
3739                boolean changed = false;
3740                try {
3741                    // First figure out how good the original match set is.
3742                    // We will only allow preferred activities that came
3743                    // from the same match quality.
3744                    int match = 0;
3745
3746                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3747
3748                    final int N = query.size();
3749                    for (int j=0; j<N; j++) {
3750                        final ResolveInfo ri = query.get(j);
3751                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3752                                + ": 0x" + Integer.toHexString(match));
3753                        if (ri.match > match) {
3754                            match = ri.match;
3755                        }
3756                    }
3757
3758                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3759                            + Integer.toHexString(match));
3760
3761                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3762                    final int M = prefs.size();
3763                    for (int i=0; i<M; i++) {
3764                        final PreferredActivity pa = prefs.get(i);
3765                        if (DEBUG_PREFERRED || debug) {
3766                            Slog.v(TAG, "Checking PreferredActivity ds="
3767                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3768                                    + "\n  component=" + pa.mPref.mComponent);
3769                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3770                        }
3771                        if (pa.mPref.mMatch != match) {
3772                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3773                                    + Integer.toHexString(pa.mPref.mMatch));
3774                            continue;
3775                        }
3776                        // If it's not an "always" type preferred activity and that's what we're
3777                        // looking for, skip it.
3778                        if (always && !pa.mPref.mAlways) {
3779                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3780                            continue;
3781                        }
3782                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3783                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3784                        if (DEBUG_PREFERRED || debug) {
3785                            Slog.v(TAG, "Found preferred activity:");
3786                            if (ai != null) {
3787                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3788                            } else {
3789                                Slog.v(TAG, "  null");
3790                            }
3791                        }
3792                        if (ai == null) {
3793                            // This previously registered preferred activity
3794                            // component is no longer known.  Most likely an update
3795                            // to the app was installed and in the new version this
3796                            // component no longer exists.  Clean it up by removing
3797                            // it from the preferred activities list, and skip it.
3798                            Slog.w(TAG, "Removing dangling preferred activity: "
3799                                    + pa.mPref.mComponent);
3800                            pir.removeFilter(pa);
3801                            changed = true;
3802                            continue;
3803                        }
3804                        for (int j=0; j<N; j++) {
3805                            final ResolveInfo ri = query.get(j);
3806                            if (!ri.activityInfo.applicationInfo.packageName
3807                                    .equals(ai.applicationInfo.packageName)) {
3808                                continue;
3809                            }
3810                            if (!ri.activityInfo.name.equals(ai.name)) {
3811                                continue;
3812                            }
3813
3814                            if (removeMatches) {
3815                                pir.removeFilter(pa);
3816                                changed = true;
3817                                if (DEBUG_PREFERRED) {
3818                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3819                                }
3820                                break;
3821                            }
3822
3823                            // Okay we found a previously set preferred or last chosen app.
3824                            // If the result set is different from when this
3825                            // was created, we need to clear it and re-ask the
3826                            // user their preference, if we're looking for an "always" type entry.
3827                            if (always && !pa.mPref.sameSet(query)) {
3828                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3829                                        + intent + " type " + resolvedType);
3830                                if (DEBUG_PREFERRED) {
3831                                    Slog.v(TAG, "Removing preferred activity since set changed "
3832                                            + pa.mPref.mComponent);
3833                                }
3834                                pir.removeFilter(pa);
3835                                // Re-add the filter as a "last chosen" entry (!always)
3836                                PreferredActivity lastChosen = new PreferredActivity(
3837                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3838                                pir.addFilter(lastChosen);
3839                                changed = true;
3840                                return null;
3841                            }
3842
3843                            // Yay! Either the set matched or we're looking for the last chosen
3844                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3845                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3846                            return ri;
3847                        }
3848                    }
3849                } finally {
3850                    if (changed) {
3851                        if (DEBUG_PREFERRED) {
3852                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3853                        }
3854                        scheduleWritePackageRestrictionsLocked(userId);
3855                    }
3856                }
3857            }
3858        }
3859        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3860        return null;
3861    }
3862
3863    /*
3864     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3865     */
3866    @Override
3867    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3868            int targetUserId) {
3869        mContext.enforceCallingOrSelfPermission(
3870                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3871        List<CrossProfileIntentFilter> matches =
3872                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3873        if (matches != null) {
3874            int size = matches.size();
3875            for (int i = 0; i < size; i++) {
3876                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3877            }
3878        }
3879        return false;
3880    }
3881
3882    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3883            String resolvedType, int userId) {
3884        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3885        if (resolver != null) {
3886            return resolver.queryIntent(intent, resolvedType, false, userId);
3887        }
3888        return null;
3889    }
3890
3891    @Override
3892    public List<ResolveInfo> queryIntentActivities(Intent intent,
3893            String resolvedType, int flags, int userId) {
3894        if (!sUserManager.exists(userId)) return Collections.emptyList();
3895        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3896        ComponentName comp = intent.getComponent();
3897        if (comp == null) {
3898            if (intent.getSelector() != null) {
3899                intent = intent.getSelector();
3900                comp = intent.getComponent();
3901            }
3902        }
3903
3904        if (comp != null) {
3905            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3906            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3907            if (ai != null) {
3908                final ResolveInfo ri = new ResolveInfo();
3909                ri.activityInfo = ai;
3910                list.add(ri);
3911            }
3912            return list;
3913        }
3914
3915        // reader
3916        synchronized (mPackages) {
3917            final String pkgName = intent.getPackage();
3918            if (pkgName == null) {
3919                List<CrossProfileIntentFilter> matchingFilters =
3920                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3921                // Check for results that need to skip the current profile.
3922                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3923                        resolvedType, flags, userId);
3924                if (resolveInfo != null) {
3925                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3926                    result.add(resolveInfo);
3927                    return filterIfNotPrimaryUser(result, userId);
3928                }
3929                // Check for cross profile results.
3930                resolveInfo = queryCrossProfileIntents(
3931                        matchingFilters, intent, resolvedType, flags, userId);
3932
3933                // Check for results in the current profile.
3934                List<ResolveInfo> result = mActivities.queryIntent(
3935                        intent, resolvedType, flags, userId);
3936                if (resolveInfo != null) {
3937                    result.add(resolveInfo);
3938                    Collections.sort(result, mResolvePrioritySorter);
3939                }
3940                result = filterIfNotPrimaryUser(result, userId);
3941                if (result.size() > 1 && hasWebURI(intent)) {
3942                    return filterCandidatesWithDomainPreferedActivitiesLPr(result);
3943                }
3944                return result;
3945            }
3946            final PackageParser.Package pkg = mPackages.get(pkgName);
3947            if (pkg != null) {
3948                return filterIfNotPrimaryUser(
3949                        mActivities.queryIntentForPackage(
3950                                intent, resolvedType, flags, pkg.activities, userId),
3951                        userId);
3952            }
3953            return new ArrayList<ResolveInfo>();
3954        }
3955    }
3956
3957    /**
3958     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
3959     *
3960     * @return filtered list
3961     */
3962    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
3963        if (userId == UserHandle.USER_OWNER) {
3964            return resolveInfos;
3965        }
3966        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
3967            ResolveInfo info = resolveInfos.get(i);
3968            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
3969                resolveInfos.remove(i);
3970            }
3971        }
3972        return resolveInfos;
3973    }
3974
3975    private static boolean hasWebURI(Intent intent) {
3976        if (intent.getData() == null) {
3977            return false;
3978        }
3979        final String scheme = intent.getScheme();
3980        if (TextUtils.isEmpty(scheme)) {
3981            return false;
3982        }
3983        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
3984    }
3985
3986    private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr(
3987            List<ResolveInfo> candidates) {
3988        if (DEBUG_PREFERRED) {
3989            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
3990                    candidates.size());
3991        }
3992
3993        final int userId = UserHandle.getCallingUserId();
3994        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
3995        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
3996        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
3997        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
3998
3999        synchronized (mPackages) {
4000            final int count = candidates.size();
4001            // First, try to use the domain prefered App
4002            for (int n=0; n<count; n++) {
4003                ResolveInfo info = candidates.get(n);
4004                String packageName = info.activityInfo.packageName;
4005                PackageSetting ps = mSettings.mPackages.get(packageName);
4006                if (ps != null) {
4007                    // Try to get the status from User settings first
4008                    int status = getDomainVerificationStatusLPr(ps, userId);
4009                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4010                        result.add(info);
4011                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4012                        neverList.add(info);
4013                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4014                        undefinedList.add(info);
4015                    }
4016                    // Add to the special match all list (Browser use case)
4017                    if (info.handleAllWebDataURI) {
4018                        matchAllList.add(info);
4019                    }
4020                }
4021            }
4022            // If there is nothing selected, add all candidates and remove the ones that the User
4023            // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and
4024            // also remove any Browser Apps ones.
4025            // If there is still none after this pass, add all undefined one and Browser Apps and
4026            // let the User decide with the Disambiguation dialog if there are several ones.
4027            if (result.size() == 0) {
4028                result.addAll(candidates);
4029            }
4030            result.removeAll(neverList);
4031            result.removeAll(matchAllList);
4032            if (result.size() == 0) {
4033                result.addAll(undefinedList);
4034                result.addAll(matchAllList);
4035            }
4036        }
4037        if (DEBUG_PREFERRED) {
4038            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4039                    result.size());
4040        }
4041        return result;
4042    }
4043
4044    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4045        int status = ps.getDomainVerificationStatusForUser(userId);
4046        // if none available, get the master status
4047        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4048            if (ps.getIntentFilterVerificationInfo() != null) {
4049                status = ps.getIntentFilterVerificationInfo().getStatus();
4050            }
4051        }
4052        return status;
4053    }
4054
4055    private ResolveInfo querySkipCurrentProfileIntents(
4056            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4057            int flags, int sourceUserId) {
4058        if (matchingFilters != null) {
4059            int size = matchingFilters.size();
4060            for (int i = 0; i < size; i ++) {
4061                CrossProfileIntentFilter filter = matchingFilters.get(i);
4062                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4063                    // Checking if there are activities in the target user that can handle the
4064                    // intent.
4065                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4066                            flags, sourceUserId);
4067                    if (resolveInfo != null) {
4068                        return resolveInfo;
4069                    }
4070                }
4071            }
4072        }
4073        return null;
4074    }
4075
4076    // Return matching ResolveInfo if any for skip current profile intent filters.
4077    private ResolveInfo queryCrossProfileIntents(
4078            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4079            int flags, int sourceUserId) {
4080        if (matchingFilters != null) {
4081            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4082            // match the same intent. For performance reasons, it is better not to
4083            // run queryIntent twice for the same userId
4084            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4085            int size = matchingFilters.size();
4086            for (int i = 0; i < size; i++) {
4087                CrossProfileIntentFilter filter = matchingFilters.get(i);
4088                int targetUserId = filter.getTargetUserId();
4089                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4090                        && !alreadyTriedUserIds.get(targetUserId)) {
4091                    // Checking if there are activities in the target user that can handle the
4092                    // intent.
4093                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4094                            flags, sourceUserId);
4095                    if (resolveInfo != null) return resolveInfo;
4096                    alreadyTriedUserIds.put(targetUserId, true);
4097                }
4098            }
4099        }
4100        return null;
4101    }
4102
4103    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4104            String resolvedType, int flags, int sourceUserId) {
4105        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4106                resolvedType, flags, filter.getTargetUserId());
4107        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4108            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4109        }
4110        return null;
4111    }
4112
4113    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4114            int sourceUserId, int targetUserId) {
4115        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4116        String className;
4117        if (targetUserId == UserHandle.USER_OWNER) {
4118            className = FORWARD_INTENT_TO_USER_OWNER;
4119        } else {
4120            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4121        }
4122        ComponentName forwardingActivityComponentName = new ComponentName(
4123                mAndroidApplication.packageName, className);
4124        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4125                sourceUserId);
4126        if (targetUserId == UserHandle.USER_OWNER) {
4127            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4128            forwardingResolveInfo.noResourceId = true;
4129        }
4130        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4131        forwardingResolveInfo.priority = 0;
4132        forwardingResolveInfo.preferredOrder = 0;
4133        forwardingResolveInfo.match = 0;
4134        forwardingResolveInfo.isDefault = true;
4135        forwardingResolveInfo.filter = filter;
4136        forwardingResolveInfo.targetUserId = targetUserId;
4137        return forwardingResolveInfo;
4138    }
4139
4140    @Override
4141    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4142            Intent[] specifics, String[] specificTypes, Intent intent,
4143            String resolvedType, int flags, int userId) {
4144        if (!sUserManager.exists(userId)) return Collections.emptyList();
4145        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4146                false, "query intent activity options");
4147        final String resultsAction = intent.getAction();
4148
4149        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4150                | PackageManager.GET_RESOLVED_FILTER, userId);
4151
4152        if (DEBUG_INTENT_MATCHING) {
4153            Log.v(TAG, "Query " + intent + ": " + results);
4154        }
4155
4156        int specificsPos = 0;
4157        int N;
4158
4159        // todo: note that the algorithm used here is O(N^2).  This
4160        // isn't a problem in our current environment, but if we start running
4161        // into situations where we have more than 5 or 10 matches then this
4162        // should probably be changed to something smarter...
4163
4164        // First we go through and resolve each of the specific items
4165        // that were supplied, taking care of removing any corresponding
4166        // duplicate items in the generic resolve list.
4167        if (specifics != null) {
4168            for (int i=0; i<specifics.length; i++) {
4169                final Intent sintent = specifics[i];
4170                if (sintent == null) {
4171                    continue;
4172                }
4173
4174                if (DEBUG_INTENT_MATCHING) {
4175                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4176                }
4177
4178                String action = sintent.getAction();
4179                if (resultsAction != null && resultsAction.equals(action)) {
4180                    // If this action was explicitly requested, then don't
4181                    // remove things that have it.
4182                    action = null;
4183                }
4184
4185                ResolveInfo ri = null;
4186                ActivityInfo ai = null;
4187
4188                ComponentName comp = sintent.getComponent();
4189                if (comp == null) {
4190                    ri = resolveIntent(
4191                        sintent,
4192                        specificTypes != null ? specificTypes[i] : null,
4193                            flags, userId);
4194                    if (ri == null) {
4195                        continue;
4196                    }
4197                    if (ri == mResolveInfo) {
4198                        // ACK!  Must do something better with this.
4199                    }
4200                    ai = ri.activityInfo;
4201                    comp = new ComponentName(ai.applicationInfo.packageName,
4202                            ai.name);
4203                } else {
4204                    ai = getActivityInfo(comp, flags, userId);
4205                    if (ai == null) {
4206                        continue;
4207                    }
4208                }
4209
4210                // Look for any generic query activities that are duplicates
4211                // of this specific one, and remove them from the results.
4212                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4213                N = results.size();
4214                int j;
4215                for (j=specificsPos; j<N; j++) {
4216                    ResolveInfo sri = results.get(j);
4217                    if ((sri.activityInfo.name.equals(comp.getClassName())
4218                            && sri.activityInfo.applicationInfo.packageName.equals(
4219                                    comp.getPackageName()))
4220                        || (action != null && sri.filter.matchAction(action))) {
4221                        results.remove(j);
4222                        if (DEBUG_INTENT_MATCHING) Log.v(
4223                            TAG, "Removing duplicate item from " + j
4224                            + " due to specific " + specificsPos);
4225                        if (ri == null) {
4226                            ri = sri;
4227                        }
4228                        j--;
4229                        N--;
4230                    }
4231                }
4232
4233                // Add this specific item to its proper place.
4234                if (ri == null) {
4235                    ri = new ResolveInfo();
4236                    ri.activityInfo = ai;
4237                }
4238                results.add(specificsPos, ri);
4239                ri.specificIndex = i;
4240                specificsPos++;
4241            }
4242        }
4243
4244        // Now we go through the remaining generic results and remove any
4245        // duplicate actions that are found here.
4246        N = results.size();
4247        for (int i=specificsPos; i<N-1; i++) {
4248            final ResolveInfo rii = results.get(i);
4249            if (rii.filter == null) {
4250                continue;
4251            }
4252
4253            // Iterate over all of the actions of this result's intent
4254            // filter...  typically this should be just one.
4255            final Iterator<String> it = rii.filter.actionsIterator();
4256            if (it == null) {
4257                continue;
4258            }
4259            while (it.hasNext()) {
4260                final String action = it.next();
4261                if (resultsAction != null && resultsAction.equals(action)) {
4262                    // If this action was explicitly requested, then don't
4263                    // remove things that have it.
4264                    continue;
4265                }
4266                for (int j=i+1; j<N; j++) {
4267                    final ResolveInfo rij = results.get(j);
4268                    if (rij.filter != null && rij.filter.hasAction(action)) {
4269                        results.remove(j);
4270                        if (DEBUG_INTENT_MATCHING) Log.v(
4271                            TAG, "Removing duplicate item from " + j
4272                            + " due to action " + action + " at " + i);
4273                        j--;
4274                        N--;
4275                    }
4276                }
4277            }
4278
4279            // If the caller didn't request filter information, drop it now
4280            // so we don't have to marshall/unmarshall it.
4281            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4282                rii.filter = null;
4283            }
4284        }
4285
4286        // Filter out the caller activity if so requested.
4287        if (caller != null) {
4288            N = results.size();
4289            for (int i=0; i<N; i++) {
4290                ActivityInfo ainfo = results.get(i).activityInfo;
4291                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4292                        && caller.getClassName().equals(ainfo.name)) {
4293                    results.remove(i);
4294                    break;
4295                }
4296            }
4297        }
4298
4299        // If the caller didn't request filter information,
4300        // drop them now so we don't have to
4301        // marshall/unmarshall it.
4302        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4303            N = results.size();
4304            for (int i=0; i<N; i++) {
4305                results.get(i).filter = null;
4306            }
4307        }
4308
4309        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4310        return results;
4311    }
4312
4313    @Override
4314    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4315            int userId) {
4316        if (!sUserManager.exists(userId)) return Collections.emptyList();
4317        ComponentName comp = intent.getComponent();
4318        if (comp == null) {
4319            if (intent.getSelector() != null) {
4320                intent = intent.getSelector();
4321                comp = intent.getComponent();
4322            }
4323        }
4324        if (comp != null) {
4325            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4326            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4327            if (ai != null) {
4328                ResolveInfo ri = new ResolveInfo();
4329                ri.activityInfo = ai;
4330                list.add(ri);
4331            }
4332            return list;
4333        }
4334
4335        // reader
4336        synchronized (mPackages) {
4337            String pkgName = intent.getPackage();
4338            if (pkgName == null) {
4339                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4340            }
4341            final PackageParser.Package pkg = mPackages.get(pkgName);
4342            if (pkg != null) {
4343                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4344                        userId);
4345            }
4346            return null;
4347        }
4348    }
4349
4350    @Override
4351    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4352        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4353        if (!sUserManager.exists(userId)) return null;
4354        if (query != null) {
4355            if (query.size() >= 1) {
4356                // If there is more than one service with the same priority,
4357                // just arbitrarily pick the first one.
4358                return query.get(0);
4359            }
4360        }
4361        return null;
4362    }
4363
4364    @Override
4365    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4366            int userId) {
4367        if (!sUserManager.exists(userId)) return Collections.emptyList();
4368        ComponentName comp = intent.getComponent();
4369        if (comp == null) {
4370            if (intent.getSelector() != null) {
4371                intent = intent.getSelector();
4372                comp = intent.getComponent();
4373            }
4374        }
4375        if (comp != null) {
4376            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4377            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4378            if (si != null) {
4379                final ResolveInfo ri = new ResolveInfo();
4380                ri.serviceInfo = si;
4381                list.add(ri);
4382            }
4383            return list;
4384        }
4385
4386        // reader
4387        synchronized (mPackages) {
4388            String pkgName = intent.getPackage();
4389            if (pkgName == null) {
4390                return mServices.queryIntent(intent, resolvedType, flags, userId);
4391            }
4392            final PackageParser.Package pkg = mPackages.get(pkgName);
4393            if (pkg != null) {
4394                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4395                        userId);
4396            }
4397            return null;
4398        }
4399    }
4400
4401    @Override
4402    public List<ResolveInfo> queryIntentContentProviders(
4403            Intent intent, String resolvedType, int flags, int userId) {
4404        if (!sUserManager.exists(userId)) return Collections.emptyList();
4405        ComponentName comp = intent.getComponent();
4406        if (comp == null) {
4407            if (intent.getSelector() != null) {
4408                intent = intent.getSelector();
4409                comp = intent.getComponent();
4410            }
4411        }
4412        if (comp != null) {
4413            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4414            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4415            if (pi != null) {
4416                final ResolveInfo ri = new ResolveInfo();
4417                ri.providerInfo = pi;
4418                list.add(ri);
4419            }
4420            return list;
4421        }
4422
4423        // reader
4424        synchronized (mPackages) {
4425            String pkgName = intent.getPackage();
4426            if (pkgName == null) {
4427                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4428            }
4429            final PackageParser.Package pkg = mPackages.get(pkgName);
4430            if (pkg != null) {
4431                return mProviders.queryIntentForPackage(
4432                        intent, resolvedType, flags, pkg.providers, userId);
4433            }
4434            return null;
4435        }
4436    }
4437
4438    @Override
4439    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4440        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4441
4442        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4443
4444        // writer
4445        synchronized (mPackages) {
4446            ArrayList<PackageInfo> list;
4447            if (listUninstalled) {
4448                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4449                for (PackageSetting ps : mSettings.mPackages.values()) {
4450                    PackageInfo pi;
4451                    if (ps.pkg != null) {
4452                        pi = generatePackageInfo(ps.pkg, flags, userId);
4453                    } else {
4454                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4455                    }
4456                    if (pi != null) {
4457                        list.add(pi);
4458                    }
4459                }
4460            } else {
4461                list = new ArrayList<PackageInfo>(mPackages.size());
4462                for (PackageParser.Package p : mPackages.values()) {
4463                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4464                    if (pi != null) {
4465                        list.add(pi);
4466                    }
4467                }
4468            }
4469
4470            return new ParceledListSlice<PackageInfo>(list);
4471        }
4472    }
4473
4474    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4475            String[] permissions, boolean[] tmp, int flags, int userId) {
4476        int numMatch = 0;
4477        final PermissionsState permissionsState = ps.getPermissionsState();
4478        for (int i=0; i<permissions.length; i++) {
4479            final String permission = permissions[i];
4480            if (permissionsState.hasPermission(permission, userId)) {
4481                tmp[i] = true;
4482                numMatch++;
4483            } else {
4484                tmp[i] = false;
4485            }
4486        }
4487        if (numMatch == 0) {
4488            return;
4489        }
4490        PackageInfo pi;
4491        if (ps.pkg != null) {
4492            pi = generatePackageInfo(ps.pkg, flags, userId);
4493        } else {
4494            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4495        }
4496        // The above might return null in cases of uninstalled apps or install-state
4497        // skew across users/profiles.
4498        if (pi != null) {
4499            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4500                if (numMatch == permissions.length) {
4501                    pi.requestedPermissions = permissions;
4502                } else {
4503                    pi.requestedPermissions = new String[numMatch];
4504                    numMatch = 0;
4505                    for (int i=0; i<permissions.length; i++) {
4506                        if (tmp[i]) {
4507                            pi.requestedPermissions[numMatch] = permissions[i];
4508                            numMatch++;
4509                        }
4510                    }
4511                }
4512            }
4513            list.add(pi);
4514        }
4515    }
4516
4517    @Override
4518    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4519            String[] permissions, int flags, int userId) {
4520        if (!sUserManager.exists(userId)) return null;
4521        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4522
4523        // writer
4524        synchronized (mPackages) {
4525            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4526            boolean[] tmpBools = new boolean[permissions.length];
4527            if (listUninstalled) {
4528                for (PackageSetting ps : mSettings.mPackages.values()) {
4529                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4530                }
4531            } else {
4532                for (PackageParser.Package pkg : mPackages.values()) {
4533                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4534                    if (ps != null) {
4535                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4536                                userId);
4537                    }
4538                }
4539            }
4540
4541            return new ParceledListSlice<PackageInfo>(list);
4542        }
4543    }
4544
4545    @Override
4546    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4547        if (!sUserManager.exists(userId)) return null;
4548        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4549
4550        // writer
4551        synchronized (mPackages) {
4552            ArrayList<ApplicationInfo> list;
4553            if (listUninstalled) {
4554                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4555                for (PackageSetting ps : mSettings.mPackages.values()) {
4556                    ApplicationInfo ai;
4557                    if (ps.pkg != null) {
4558                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4559                                ps.readUserState(userId), userId);
4560                    } else {
4561                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4562                    }
4563                    if (ai != null) {
4564                        list.add(ai);
4565                    }
4566                }
4567            } else {
4568                list = new ArrayList<ApplicationInfo>(mPackages.size());
4569                for (PackageParser.Package p : mPackages.values()) {
4570                    if (p.mExtras != null) {
4571                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4572                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4573                        if (ai != null) {
4574                            list.add(ai);
4575                        }
4576                    }
4577                }
4578            }
4579
4580            return new ParceledListSlice<ApplicationInfo>(list);
4581        }
4582    }
4583
4584    public List<ApplicationInfo> getPersistentApplications(int flags) {
4585        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4586
4587        // reader
4588        synchronized (mPackages) {
4589            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4590            final int userId = UserHandle.getCallingUserId();
4591            while (i.hasNext()) {
4592                final PackageParser.Package p = i.next();
4593                if (p.applicationInfo != null
4594                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4595                        && (!mSafeMode || isSystemApp(p))) {
4596                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4597                    if (ps != null) {
4598                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4599                                ps.readUserState(userId), userId);
4600                        if (ai != null) {
4601                            finalList.add(ai);
4602                        }
4603                    }
4604                }
4605            }
4606        }
4607
4608        return finalList;
4609    }
4610
4611    @Override
4612    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4613        if (!sUserManager.exists(userId)) return null;
4614        // reader
4615        synchronized (mPackages) {
4616            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4617            PackageSetting ps = provider != null
4618                    ? mSettings.mPackages.get(provider.owner.packageName)
4619                    : null;
4620            return ps != null
4621                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4622                    && (!mSafeMode || (provider.info.applicationInfo.flags
4623                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4624                    ? PackageParser.generateProviderInfo(provider, flags,
4625                            ps.readUserState(userId), userId)
4626                    : null;
4627        }
4628    }
4629
4630    /**
4631     * @deprecated
4632     */
4633    @Deprecated
4634    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4635        // reader
4636        synchronized (mPackages) {
4637            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4638                    .entrySet().iterator();
4639            final int userId = UserHandle.getCallingUserId();
4640            while (i.hasNext()) {
4641                Map.Entry<String, PackageParser.Provider> entry = i.next();
4642                PackageParser.Provider p = entry.getValue();
4643                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4644
4645                if (ps != null && p.syncable
4646                        && (!mSafeMode || (p.info.applicationInfo.flags
4647                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4648                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4649                            ps.readUserState(userId), userId);
4650                    if (info != null) {
4651                        outNames.add(entry.getKey());
4652                        outInfo.add(info);
4653                    }
4654                }
4655            }
4656        }
4657    }
4658
4659    @Override
4660    public List<ProviderInfo> queryContentProviders(String processName,
4661            int uid, int flags) {
4662        ArrayList<ProviderInfo> finalList = null;
4663        // reader
4664        synchronized (mPackages) {
4665            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4666            final int userId = processName != null ?
4667                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4668            while (i.hasNext()) {
4669                final PackageParser.Provider p = i.next();
4670                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4671                if (ps != null && p.info.authority != null
4672                        && (processName == null
4673                                || (p.info.processName.equals(processName)
4674                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4675                        && mSettings.isEnabledLPr(p.info, flags, userId)
4676                        && (!mSafeMode
4677                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4678                    if (finalList == null) {
4679                        finalList = new ArrayList<ProviderInfo>(3);
4680                    }
4681                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4682                            ps.readUserState(userId), userId);
4683                    if (info != null) {
4684                        finalList.add(info);
4685                    }
4686                }
4687            }
4688        }
4689
4690        if (finalList != null) {
4691            Collections.sort(finalList, mProviderInitOrderSorter);
4692        }
4693
4694        return finalList;
4695    }
4696
4697    @Override
4698    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4699            int flags) {
4700        // reader
4701        synchronized (mPackages) {
4702            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4703            return PackageParser.generateInstrumentationInfo(i, flags);
4704        }
4705    }
4706
4707    @Override
4708    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4709            int flags) {
4710        ArrayList<InstrumentationInfo> finalList =
4711            new ArrayList<InstrumentationInfo>();
4712
4713        // reader
4714        synchronized (mPackages) {
4715            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4716            while (i.hasNext()) {
4717                final PackageParser.Instrumentation p = i.next();
4718                if (targetPackage == null
4719                        || targetPackage.equals(p.info.targetPackage)) {
4720                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4721                            flags);
4722                    if (ii != null) {
4723                        finalList.add(ii);
4724                    }
4725                }
4726            }
4727        }
4728
4729        return finalList;
4730    }
4731
4732    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4733        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4734        if (overlays == null) {
4735            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4736            return;
4737        }
4738        for (PackageParser.Package opkg : overlays.values()) {
4739            // Not much to do if idmap fails: we already logged the error
4740            // and we certainly don't want to abort installation of pkg simply
4741            // because an overlay didn't fit properly. For these reasons,
4742            // ignore the return value of createIdmapForPackagePairLI.
4743            createIdmapForPackagePairLI(pkg, opkg);
4744        }
4745    }
4746
4747    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4748            PackageParser.Package opkg) {
4749        if (!opkg.mTrustedOverlay) {
4750            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4751                    opkg.baseCodePath + ": overlay not trusted");
4752            return false;
4753        }
4754        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4755        if (overlaySet == null) {
4756            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4757                    opkg.baseCodePath + " but target package has no known overlays");
4758            return false;
4759        }
4760        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4761        // TODO: generate idmap for split APKs
4762        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4763            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4764                    + opkg.baseCodePath);
4765            return false;
4766        }
4767        PackageParser.Package[] overlayArray =
4768            overlaySet.values().toArray(new PackageParser.Package[0]);
4769        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4770            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4771                return p1.mOverlayPriority - p2.mOverlayPriority;
4772            }
4773        };
4774        Arrays.sort(overlayArray, cmp);
4775
4776        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4777        int i = 0;
4778        for (PackageParser.Package p : overlayArray) {
4779            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4780        }
4781        return true;
4782    }
4783
4784    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4785        final File[] files = dir.listFiles();
4786        if (ArrayUtils.isEmpty(files)) {
4787            Log.d(TAG, "No files in app dir " + dir);
4788            return;
4789        }
4790
4791        if (DEBUG_PACKAGE_SCANNING) {
4792            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4793                    + " flags=0x" + Integer.toHexString(parseFlags));
4794        }
4795
4796        for (File file : files) {
4797            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4798                    && !PackageInstallerService.isStageName(file.getName());
4799            if (!isPackage) {
4800                // Ignore entries which are not packages
4801                continue;
4802            }
4803            try {
4804                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4805                        scanFlags, currentTime, null);
4806            } catch (PackageManagerException e) {
4807                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4808
4809                // Delete invalid userdata apps
4810                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4811                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4812                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4813                    if (file.isDirectory()) {
4814                        mInstaller.rmPackageDir(file.getAbsolutePath());
4815                    } else {
4816                        file.delete();
4817                    }
4818                }
4819            }
4820        }
4821    }
4822
4823    private static File getSettingsProblemFile() {
4824        File dataDir = Environment.getDataDirectory();
4825        File systemDir = new File(dataDir, "system");
4826        File fname = new File(systemDir, "uiderrors.txt");
4827        return fname;
4828    }
4829
4830    static void reportSettingsProblem(int priority, String msg) {
4831        logCriticalInfo(priority, msg);
4832    }
4833
4834    static void logCriticalInfo(int priority, String msg) {
4835        Slog.println(priority, TAG, msg);
4836        EventLogTags.writePmCriticalInfo(msg);
4837        try {
4838            File fname = getSettingsProblemFile();
4839            FileOutputStream out = new FileOutputStream(fname, true);
4840            PrintWriter pw = new FastPrintWriter(out);
4841            SimpleDateFormat formatter = new SimpleDateFormat();
4842            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4843            pw.println(dateString + ": " + msg);
4844            pw.close();
4845            FileUtils.setPermissions(
4846                    fname.toString(),
4847                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4848                    -1, -1);
4849        } catch (java.io.IOException e) {
4850        }
4851    }
4852
4853    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4854            PackageParser.Package pkg, File srcFile, int parseFlags)
4855            throws PackageManagerException {
4856        if (ps != null
4857                && ps.codePath.equals(srcFile)
4858                && ps.timeStamp == srcFile.lastModified()
4859                && !isCompatSignatureUpdateNeeded(pkg)
4860                && !isRecoverSignatureUpdateNeeded(pkg)) {
4861            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4862            if (ps.signatures.mSignatures != null
4863                    && ps.signatures.mSignatures.length != 0
4864                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4865                // Optimization: reuse the existing cached certificates
4866                // if the package appears to be unchanged.
4867                pkg.mSignatures = ps.signatures.mSignatures;
4868                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4869                synchronized (mPackages) {
4870                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4871                }
4872                return;
4873            }
4874
4875            Slog.w(TAG, "PackageSetting for " + ps.name
4876                    + " is missing signatures.  Collecting certs again to recover them.");
4877        } else {
4878            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4879        }
4880
4881        try {
4882            pp.collectCertificates(pkg, parseFlags);
4883            pp.collectManifestDigest(pkg);
4884        } catch (PackageParserException e) {
4885            throw PackageManagerException.from(e);
4886        }
4887    }
4888
4889    /*
4890     *  Scan a package and return the newly parsed package.
4891     *  Returns null in case of errors and the error code is stored in mLastScanError
4892     */
4893    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4894            long currentTime, UserHandle user) throws PackageManagerException {
4895        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4896        parseFlags |= mDefParseFlags;
4897        PackageParser pp = new PackageParser();
4898        pp.setSeparateProcesses(mSeparateProcesses);
4899        pp.setOnlyCoreApps(mOnlyCore);
4900        pp.setDisplayMetrics(mMetrics);
4901
4902        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4903            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4904        }
4905
4906        final PackageParser.Package pkg;
4907        try {
4908            pkg = pp.parsePackage(scanFile, parseFlags);
4909        } catch (PackageParserException e) {
4910            throw PackageManagerException.from(e);
4911        }
4912
4913        PackageSetting ps = null;
4914        PackageSetting updatedPkg;
4915        // reader
4916        synchronized (mPackages) {
4917            // Look to see if we already know about this package.
4918            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4919            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4920                // This package has been renamed to its original name.  Let's
4921                // use that.
4922                ps = mSettings.peekPackageLPr(oldName);
4923            }
4924            // If there was no original package, see one for the real package name.
4925            if (ps == null) {
4926                ps = mSettings.peekPackageLPr(pkg.packageName);
4927            }
4928            // Check to see if this package could be hiding/updating a system
4929            // package.  Must look for it either under the original or real
4930            // package name depending on our state.
4931            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4932            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4933        }
4934        boolean updatedPkgBetter = false;
4935        // First check if this is a system package that may involve an update
4936        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4937            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
4938            // it needs to drop FLAG_PRIVILEGED.
4939            if (locationIsPrivileged(scanFile)) {
4940                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4941            } else {
4942                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4943            }
4944
4945            if (ps != null && !ps.codePath.equals(scanFile)) {
4946                // The path has changed from what was last scanned...  check the
4947                // version of the new path against what we have stored to determine
4948                // what to do.
4949                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4950                if (pkg.mVersionCode <= ps.versionCode) {
4951                    // The system package has been updated and the code path does not match
4952                    // Ignore entry. Skip it.
4953                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
4954                            + " ignored: updated version " + ps.versionCode
4955                            + " better than this " + pkg.mVersionCode);
4956                    if (!updatedPkg.codePath.equals(scanFile)) {
4957                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4958                                + ps.name + " changing from " + updatedPkg.codePathString
4959                                + " to " + scanFile);
4960                        updatedPkg.codePath = scanFile;
4961                        updatedPkg.codePathString = scanFile.toString();
4962                        updatedPkg.resourcePath = scanFile;
4963                        updatedPkg.resourcePathString = scanFile.toString();
4964                    }
4965                    updatedPkg.pkg = pkg;
4966                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4967                } else {
4968                    // The current app on the system partition is better than
4969                    // what we have updated to on the data partition; switch
4970                    // back to the system partition version.
4971                    // At this point, its safely assumed that package installation for
4972                    // apps in system partition will go through. If not there won't be a working
4973                    // version of the app
4974                    // writer
4975                    synchronized (mPackages) {
4976                        // Just remove the loaded entries from package lists.
4977                        mPackages.remove(ps.name);
4978                    }
4979
4980                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4981                            + " reverting from " + ps.codePathString
4982                            + ": new version " + pkg.mVersionCode
4983                            + " better than installed " + ps.versionCode);
4984
4985                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4986                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4987                            getAppDexInstructionSets(ps));
4988                    synchronized (mInstallLock) {
4989                        args.cleanUpResourcesLI();
4990                    }
4991                    synchronized (mPackages) {
4992                        mSettings.enableSystemPackageLPw(ps.name);
4993                    }
4994                    updatedPkgBetter = true;
4995                }
4996            }
4997        }
4998
4999        if (updatedPkg != null) {
5000            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5001            // initially
5002            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5003
5004            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5005            // flag set initially
5006            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5007                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5008            }
5009        }
5010
5011        // Verify certificates against what was last scanned
5012        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5013
5014        /*
5015         * A new system app appeared, but we already had a non-system one of the
5016         * same name installed earlier.
5017         */
5018        boolean shouldHideSystemApp = false;
5019        if (updatedPkg == null && ps != null
5020                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5021            /*
5022             * Check to make sure the signatures match first. If they don't,
5023             * wipe the installed application and its data.
5024             */
5025            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5026                    != PackageManager.SIGNATURE_MATCH) {
5027                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5028                        + " signatures don't match existing userdata copy; removing");
5029                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5030                ps = null;
5031            } else {
5032                /*
5033                 * If the newly-added system app is an older version than the
5034                 * already installed version, hide it. It will be scanned later
5035                 * and re-added like an update.
5036                 */
5037                if (pkg.mVersionCode <= ps.versionCode) {
5038                    shouldHideSystemApp = true;
5039                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5040                            + " but new version " + pkg.mVersionCode + " better than installed "
5041                            + ps.versionCode + "; hiding system");
5042                } else {
5043                    /*
5044                     * The newly found system app is a newer version that the
5045                     * one previously installed. Simply remove the
5046                     * already-installed application and replace it with our own
5047                     * while keeping the application data.
5048                     */
5049                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5050                            + " reverting from " + ps.codePathString + ": new version "
5051                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5052                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5053                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
5054                            getAppDexInstructionSets(ps));
5055                    synchronized (mInstallLock) {
5056                        args.cleanUpResourcesLI();
5057                    }
5058                }
5059            }
5060        }
5061
5062        // The apk is forward locked (not public) if its code and resources
5063        // are kept in different files. (except for app in either system or
5064        // vendor path).
5065        // TODO grab this value from PackageSettings
5066        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5067            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5068                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5069            }
5070        }
5071
5072        // TODO: extend to support forward-locked splits
5073        String resourcePath = null;
5074        String baseResourcePath = null;
5075        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5076            if (ps != null && ps.resourcePathString != null) {
5077                resourcePath = ps.resourcePathString;
5078                baseResourcePath = ps.resourcePathString;
5079            } else {
5080                // Should not happen at all. Just log an error.
5081                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5082            }
5083        } else {
5084            resourcePath = pkg.codePath;
5085            baseResourcePath = pkg.baseCodePath;
5086        }
5087
5088        // Set application objects path explicitly.
5089        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5090        pkg.applicationInfo.setCodePath(pkg.codePath);
5091        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5092        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5093        pkg.applicationInfo.setResourcePath(resourcePath);
5094        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5095        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5096
5097        // Note that we invoke the following method only if we are about to unpack an application
5098        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5099                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5100
5101        /*
5102         * If the system app should be overridden by a previously installed
5103         * data, hide the system app now and let the /data/app scan pick it up
5104         * again.
5105         */
5106        if (shouldHideSystemApp) {
5107            synchronized (mPackages) {
5108                /*
5109                 * We have to grant systems permissions before we hide, because
5110                 * grantPermissions will assume the package update is trying to
5111                 * expand its permissions.
5112                 */
5113                grantPermissionsLPw(pkg, true, pkg.packageName);
5114                mSettings.disableSystemPackageLPw(pkg.packageName);
5115            }
5116        }
5117
5118        return scannedPkg;
5119    }
5120
5121    private static String fixProcessName(String defProcessName,
5122            String processName, int uid) {
5123        if (processName == null) {
5124            return defProcessName;
5125        }
5126        return processName;
5127    }
5128
5129    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5130            throws PackageManagerException {
5131        if (pkgSetting.signatures.mSignatures != null) {
5132            // Already existing package. Make sure signatures match
5133            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5134                    == PackageManager.SIGNATURE_MATCH;
5135            if (!match) {
5136                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5137                        == PackageManager.SIGNATURE_MATCH;
5138            }
5139            if (!match) {
5140                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5141                        == PackageManager.SIGNATURE_MATCH;
5142            }
5143            if (!match) {
5144                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5145                        + pkg.packageName + " signatures do not match the "
5146                        + "previously installed version; ignoring!");
5147            }
5148        }
5149
5150        // Check for shared user signatures
5151        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5152            // Already existing package. Make sure signatures match
5153            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5154                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5155            if (!match) {
5156                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5157                        == PackageManager.SIGNATURE_MATCH;
5158            }
5159            if (!match) {
5160                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5161                        == PackageManager.SIGNATURE_MATCH;
5162            }
5163            if (!match) {
5164                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5165                        "Package " + pkg.packageName
5166                        + " has no signatures that match those in shared user "
5167                        + pkgSetting.sharedUser.name + "; ignoring!");
5168            }
5169        }
5170    }
5171
5172    /**
5173     * Enforces that only the system UID or root's UID can call a method exposed
5174     * via Binder.
5175     *
5176     * @param message used as message if SecurityException is thrown
5177     * @throws SecurityException if the caller is not system or root
5178     */
5179    private static final void enforceSystemOrRoot(String message) {
5180        final int uid = Binder.getCallingUid();
5181        if (uid != Process.SYSTEM_UID && uid != 0) {
5182            throw new SecurityException(message);
5183        }
5184    }
5185
5186    @Override
5187    public void performBootDexOpt() {
5188        enforceSystemOrRoot("Only the system can request dexopt be performed");
5189
5190        // Before everything else, see whether we need to fstrim.
5191        try {
5192            IMountService ms = PackageHelper.getMountService();
5193            if (ms != null) {
5194                final boolean isUpgrade = isUpgrade();
5195                boolean doTrim = isUpgrade;
5196                if (doTrim) {
5197                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5198                } else {
5199                    final long interval = android.provider.Settings.Global.getLong(
5200                            mContext.getContentResolver(),
5201                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5202                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5203                    if (interval > 0) {
5204                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5205                        if (timeSinceLast > interval) {
5206                            doTrim = true;
5207                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5208                                    + "; running immediately");
5209                        }
5210                    }
5211                }
5212                if (doTrim) {
5213                    if (!isFirstBoot()) {
5214                        try {
5215                            ActivityManagerNative.getDefault().showBootMessage(
5216                                    mContext.getResources().getString(
5217                                            R.string.android_upgrading_fstrim), true);
5218                        } catch (RemoteException e) {
5219                        }
5220                    }
5221                    ms.runMaintenance();
5222                }
5223            } else {
5224                Slog.e(TAG, "Mount service unavailable!");
5225            }
5226        } catch (RemoteException e) {
5227            // Can't happen; MountService is local
5228        }
5229
5230        final ArraySet<PackageParser.Package> pkgs;
5231        synchronized (mPackages) {
5232            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5233        }
5234
5235        if (pkgs != null) {
5236            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5237            // in case the device runs out of space.
5238            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5239            // Give priority to core apps.
5240            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5241                PackageParser.Package pkg = it.next();
5242                if (pkg.coreApp) {
5243                    if (DEBUG_DEXOPT) {
5244                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5245                    }
5246                    sortedPkgs.add(pkg);
5247                    it.remove();
5248                }
5249            }
5250            // Give priority to system apps that listen for pre boot complete.
5251            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5252            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5253            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5254                PackageParser.Package pkg = it.next();
5255                if (pkgNames.contains(pkg.packageName)) {
5256                    if (DEBUG_DEXOPT) {
5257                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5258                    }
5259                    sortedPkgs.add(pkg);
5260                    it.remove();
5261                }
5262            }
5263            // Give priority to system apps.
5264            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5265                PackageParser.Package pkg = it.next();
5266                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5267                    if (DEBUG_DEXOPT) {
5268                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5269                    }
5270                    sortedPkgs.add(pkg);
5271                    it.remove();
5272                }
5273            }
5274            // Give priority to updated system apps.
5275            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5276                PackageParser.Package pkg = it.next();
5277                if (pkg.isUpdatedSystemApp()) {
5278                    if (DEBUG_DEXOPT) {
5279                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5280                    }
5281                    sortedPkgs.add(pkg);
5282                    it.remove();
5283                }
5284            }
5285            // Give priority to apps that listen for boot complete.
5286            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5287            pkgNames = getPackageNamesForIntent(intent);
5288            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5289                PackageParser.Package pkg = it.next();
5290                if (pkgNames.contains(pkg.packageName)) {
5291                    if (DEBUG_DEXOPT) {
5292                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5293                    }
5294                    sortedPkgs.add(pkg);
5295                    it.remove();
5296                }
5297            }
5298            // Filter out packages that aren't recently used.
5299            filterRecentlyUsedApps(pkgs);
5300            // Add all remaining apps.
5301            for (PackageParser.Package pkg : pkgs) {
5302                if (DEBUG_DEXOPT) {
5303                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5304                }
5305                sortedPkgs.add(pkg);
5306            }
5307
5308            // If we want to be lazy, filter everything that wasn't recently used.
5309            if (mLazyDexOpt) {
5310                filterRecentlyUsedApps(sortedPkgs);
5311            }
5312
5313            int i = 0;
5314            int total = sortedPkgs.size();
5315            File dataDir = Environment.getDataDirectory();
5316            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5317            if (lowThreshold == 0) {
5318                throw new IllegalStateException("Invalid low memory threshold");
5319            }
5320            for (PackageParser.Package pkg : sortedPkgs) {
5321                long usableSpace = dataDir.getUsableSpace();
5322                if (usableSpace < lowThreshold) {
5323                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5324                    break;
5325                }
5326                performBootDexOpt(pkg, ++i, total);
5327            }
5328        }
5329    }
5330
5331    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5332        // Filter out packages that aren't recently used.
5333        //
5334        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5335        // should do a full dexopt.
5336        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5337            int total = pkgs.size();
5338            int skipped = 0;
5339            long now = System.currentTimeMillis();
5340            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5341                PackageParser.Package pkg = i.next();
5342                long then = pkg.mLastPackageUsageTimeInMills;
5343                if (then + mDexOptLRUThresholdInMills < now) {
5344                    if (DEBUG_DEXOPT) {
5345                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5346                              ((then == 0) ? "never" : new Date(then)));
5347                    }
5348                    i.remove();
5349                    skipped++;
5350                }
5351            }
5352            if (DEBUG_DEXOPT) {
5353                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5354            }
5355        }
5356    }
5357
5358    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5359        List<ResolveInfo> ris = null;
5360        try {
5361            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5362                    intent, null, 0, UserHandle.USER_OWNER);
5363        } catch (RemoteException e) {
5364        }
5365        ArraySet<String> pkgNames = new ArraySet<String>();
5366        if (ris != null) {
5367            for (ResolveInfo ri : ris) {
5368                pkgNames.add(ri.activityInfo.packageName);
5369            }
5370        }
5371        return pkgNames;
5372    }
5373
5374    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5375        if (DEBUG_DEXOPT) {
5376            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5377        }
5378        if (!isFirstBoot()) {
5379            try {
5380                ActivityManagerNative.getDefault().showBootMessage(
5381                        mContext.getResources().getString(R.string.android_upgrading_apk,
5382                                curr, total), true);
5383            } catch (RemoteException e) {
5384            }
5385        }
5386        PackageParser.Package p = pkg;
5387        synchronized (mInstallLock) {
5388            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5389                    false /* force dex */, false /* defer */, true /* include dependencies */);
5390        }
5391    }
5392
5393    @Override
5394    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5395        return performDexOpt(packageName, instructionSet, false);
5396    }
5397
5398    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5399        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5400        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5401        if (!dexopt && !updateUsage) {
5402            // We aren't going to dexopt or update usage, so bail early.
5403            return false;
5404        }
5405        PackageParser.Package p;
5406        final String targetInstructionSet;
5407        synchronized (mPackages) {
5408            p = mPackages.get(packageName);
5409            if (p == null) {
5410                return false;
5411            }
5412            if (updateUsage) {
5413                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5414            }
5415            mPackageUsage.write(false);
5416            if (!dexopt) {
5417                // We aren't going to dexopt, so bail early.
5418                return false;
5419            }
5420
5421            targetInstructionSet = instructionSet != null ? instructionSet :
5422                    getPrimaryInstructionSet(p.applicationInfo);
5423            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5424                return false;
5425            }
5426        }
5427
5428        synchronized (mInstallLock) {
5429            final String[] instructionSets = new String[] { targetInstructionSet };
5430            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5431                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5432            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5433        }
5434    }
5435
5436    public ArraySet<String> getPackagesThatNeedDexOpt() {
5437        ArraySet<String> pkgs = null;
5438        synchronized (mPackages) {
5439            for (PackageParser.Package p : mPackages.values()) {
5440                if (DEBUG_DEXOPT) {
5441                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5442                }
5443                if (!p.mDexOptPerformed.isEmpty()) {
5444                    continue;
5445                }
5446                if (pkgs == null) {
5447                    pkgs = new ArraySet<String>();
5448                }
5449                pkgs.add(p.packageName);
5450            }
5451        }
5452        return pkgs;
5453    }
5454
5455    public void shutdown() {
5456        mPackageUsage.write(true);
5457    }
5458
5459    @Override
5460    public void forceDexOpt(String packageName) {
5461        enforceSystemOrRoot("forceDexOpt");
5462
5463        PackageParser.Package pkg;
5464        synchronized (mPackages) {
5465            pkg = mPackages.get(packageName);
5466            if (pkg == null) {
5467                throw new IllegalArgumentException("Missing package: " + packageName);
5468            }
5469        }
5470
5471        synchronized (mInstallLock) {
5472            final String[] instructionSets = new String[] {
5473                    getPrimaryInstructionSet(pkg.applicationInfo) };
5474            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5475                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5476            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5477                throw new IllegalStateException("Failed to dexopt: " + res);
5478            }
5479        }
5480    }
5481
5482    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5483        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5484            Slog.w(TAG, "Unable to update from " + oldPkg.name
5485                    + " to " + newPkg.packageName
5486                    + ": old package not in system partition");
5487            return false;
5488        } else if (mPackages.get(oldPkg.name) != null) {
5489            Slog.w(TAG, "Unable to update from " + oldPkg.name
5490                    + " to " + newPkg.packageName
5491                    + ": old package still exists");
5492            return false;
5493        }
5494        return true;
5495    }
5496
5497    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5498        int[] users = sUserManager.getUserIds();
5499        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5500        if (res < 0) {
5501            return res;
5502        }
5503        for (int user : users) {
5504            if (user != 0) {
5505                res = mInstaller.createUserData(volumeUuid, packageName,
5506                        UserHandle.getUid(user, uid), user, seinfo);
5507                if (res < 0) {
5508                    return res;
5509                }
5510            }
5511        }
5512        return res;
5513    }
5514
5515    private int removeDataDirsLI(String volumeUuid, String packageName) {
5516        int[] users = sUserManager.getUserIds();
5517        int res = 0;
5518        for (int user : users) {
5519            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5520            if (resInner < 0) {
5521                res = resInner;
5522            }
5523        }
5524
5525        return res;
5526    }
5527
5528    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5529        int[] users = sUserManager.getUserIds();
5530        int res = 0;
5531        for (int user : users) {
5532            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5533            if (resInner < 0) {
5534                res = resInner;
5535            }
5536        }
5537        return res;
5538    }
5539
5540    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5541            PackageParser.Package changingLib) {
5542        if (file.path != null) {
5543            usesLibraryFiles.add(file.path);
5544            return;
5545        }
5546        PackageParser.Package p = mPackages.get(file.apk);
5547        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5548            // If we are doing this while in the middle of updating a library apk,
5549            // then we need to make sure to use that new apk for determining the
5550            // dependencies here.  (We haven't yet finished committing the new apk
5551            // to the package manager state.)
5552            if (p == null || p.packageName.equals(changingLib.packageName)) {
5553                p = changingLib;
5554            }
5555        }
5556        if (p != null) {
5557            usesLibraryFiles.addAll(p.getAllCodePaths());
5558        }
5559    }
5560
5561    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5562            PackageParser.Package changingLib) throws PackageManagerException {
5563        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5564            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5565            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5566            for (int i=0; i<N; i++) {
5567                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5568                if (file == null) {
5569                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5570                            "Package " + pkg.packageName + " requires unavailable shared library "
5571                            + pkg.usesLibraries.get(i) + "; failing!");
5572                }
5573                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5574            }
5575            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5576            for (int i=0; i<N; i++) {
5577                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5578                if (file == null) {
5579                    Slog.w(TAG, "Package " + pkg.packageName
5580                            + " desires unavailable shared library "
5581                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5582                } else {
5583                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5584                }
5585            }
5586            N = usesLibraryFiles.size();
5587            if (N > 0) {
5588                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5589            } else {
5590                pkg.usesLibraryFiles = null;
5591            }
5592        }
5593    }
5594
5595    private static boolean hasString(List<String> list, List<String> which) {
5596        if (list == null) {
5597            return false;
5598        }
5599        for (int i=list.size()-1; i>=0; i--) {
5600            for (int j=which.size()-1; j>=0; j--) {
5601                if (which.get(j).equals(list.get(i))) {
5602                    return true;
5603                }
5604            }
5605        }
5606        return false;
5607    }
5608
5609    private void updateAllSharedLibrariesLPw() {
5610        for (PackageParser.Package pkg : mPackages.values()) {
5611            try {
5612                updateSharedLibrariesLPw(pkg, null);
5613            } catch (PackageManagerException e) {
5614                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5615            }
5616        }
5617    }
5618
5619    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5620            PackageParser.Package changingPkg) {
5621        ArrayList<PackageParser.Package> res = null;
5622        for (PackageParser.Package pkg : mPackages.values()) {
5623            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5624                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5625                if (res == null) {
5626                    res = new ArrayList<PackageParser.Package>();
5627                }
5628                res.add(pkg);
5629                try {
5630                    updateSharedLibrariesLPw(pkg, changingPkg);
5631                } catch (PackageManagerException e) {
5632                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5633                }
5634            }
5635        }
5636        return res;
5637    }
5638
5639    /**
5640     * Derive the value of the {@code cpuAbiOverride} based on the provided
5641     * value and an optional stored value from the package settings.
5642     */
5643    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5644        String cpuAbiOverride = null;
5645
5646        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5647            cpuAbiOverride = null;
5648        } else if (abiOverride != null) {
5649            cpuAbiOverride = abiOverride;
5650        } else if (settings != null) {
5651            cpuAbiOverride = settings.cpuAbiOverrideString;
5652        }
5653
5654        return cpuAbiOverride;
5655    }
5656
5657    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5658            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5659        boolean success = false;
5660        try {
5661            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5662                    currentTime, user);
5663            success = true;
5664            return res;
5665        } finally {
5666            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5667                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
5668            }
5669        }
5670    }
5671
5672    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5673            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5674        final File scanFile = new File(pkg.codePath);
5675        if (pkg.applicationInfo.getCodePath() == null ||
5676                pkg.applicationInfo.getResourcePath() == null) {
5677            // Bail out. The resource and code paths haven't been set.
5678            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5679                    "Code and resource paths haven't been set correctly");
5680        }
5681
5682        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5683            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5684        } else {
5685            // Only allow system apps to be flagged as core apps.
5686            pkg.coreApp = false;
5687        }
5688
5689        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5690            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5691        }
5692
5693        if (mCustomResolverComponentName != null &&
5694                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5695            setUpCustomResolverActivity(pkg);
5696        }
5697
5698        if (pkg.packageName.equals("android")) {
5699            synchronized (mPackages) {
5700                if (mAndroidApplication != null) {
5701                    Slog.w(TAG, "*************************************************");
5702                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5703                    Slog.w(TAG, " file=" + scanFile);
5704                    Slog.w(TAG, "*************************************************");
5705                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5706                            "Core android package being redefined.  Skipping.");
5707                }
5708
5709                // Set up information for our fall-back user intent resolution activity.
5710                mPlatformPackage = pkg;
5711                pkg.mVersionCode = mSdkVersion;
5712                mAndroidApplication = pkg.applicationInfo;
5713
5714                if (!mResolverReplaced) {
5715                    mResolveActivity.applicationInfo = mAndroidApplication;
5716                    mResolveActivity.name = ResolverActivity.class.getName();
5717                    mResolveActivity.packageName = mAndroidApplication.packageName;
5718                    mResolveActivity.processName = "system:ui";
5719                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5720                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5721                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5722                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5723                    mResolveActivity.exported = true;
5724                    mResolveActivity.enabled = true;
5725                    mResolveInfo.activityInfo = mResolveActivity;
5726                    mResolveInfo.priority = 0;
5727                    mResolveInfo.preferredOrder = 0;
5728                    mResolveInfo.match = 0;
5729                    mResolveComponentName = new ComponentName(
5730                            mAndroidApplication.packageName, mResolveActivity.name);
5731                }
5732            }
5733        }
5734
5735        if (DEBUG_PACKAGE_SCANNING) {
5736            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5737                Log.d(TAG, "Scanning package " + pkg.packageName);
5738        }
5739
5740        if (mPackages.containsKey(pkg.packageName)
5741                || mSharedLibraries.containsKey(pkg.packageName)) {
5742            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5743                    "Application package " + pkg.packageName
5744                    + " already installed.  Skipping duplicate.");
5745        }
5746
5747        // If we're only installing presumed-existing packages, require that the
5748        // scanned APK is both already known and at the path previously established
5749        // for it.  Previously unknown packages we pick up normally, but if we have an
5750        // a priori expectation about this package's install presence, enforce it.
5751        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
5752            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
5753            if (known != null) {
5754                if (DEBUG_PACKAGE_SCANNING) {
5755                    Log.d(TAG, "Examining " + pkg.codePath
5756                            + " and requiring known paths " + known.codePathString
5757                            + " & " + known.resourcePathString);
5758                }
5759                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
5760                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
5761                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
5762                            "Application package " + pkg.packageName
5763                            + " found at " + pkg.applicationInfo.getCodePath()
5764                            + " but expected at " + known.codePathString + "; ignoring.");
5765                }
5766            }
5767        }
5768
5769        // Initialize package source and resource directories
5770        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5771        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5772
5773        SharedUserSetting suid = null;
5774        PackageSetting pkgSetting = null;
5775
5776        if (!isSystemApp(pkg)) {
5777            // Only system apps can use these features.
5778            pkg.mOriginalPackages = null;
5779            pkg.mRealPackage = null;
5780            pkg.mAdoptPermissions = null;
5781        }
5782
5783        // writer
5784        synchronized (mPackages) {
5785            if (pkg.mSharedUserId != null) {
5786                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5787                if (suid == null) {
5788                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5789                            "Creating application package " + pkg.packageName
5790                            + " for shared user failed");
5791                }
5792                if (DEBUG_PACKAGE_SCANNING) {
5793                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5794                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5795                                + "): packages=" + suid.packages);
5796                }
5797            }
5798
5799            // Check if we are renaming from an original package name.
5800            PackageSetting origPackage = null;
5801            String realName = null;
5802            if (pkg.mOriginalPackages != null) {
5803                // This package may need to be renamed to a previously
5804                // installed name.  Let's check on that...
5805                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5806                if (pkg.mOriginalPackages.contains(renamed)) {
5807                    // This package had originally been installed as the
5808                    // original name, and we have already taken care of
5809                    // transitioning to the new one.  Just update the new
5810                    // one to continue using the old name.
5811                    realName = pkg.mRealPackage;
5812                    if (!pkg.packageName.equals(renamed)) {
5813                        // Callers into this function may have already taken
5814                        // care of renaming the package; only do it here if
5815                        // it is not already done.
5816                        pkg.setPackageName(renamed);
5817                    }
5818
5819                } else {
5820                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5821                        if ((origPackage = mSettings.peekPackageLPr(
5822                                pkg.mOriginalPackages.get(i))) != null) {
5823                            // We do have the package already installed under its
5824                            // original name...  should we use it?
5825                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5826                                // New package is not compatible with original.
5827                                origPackage = null;
5828                                continue;
5829                            } else if (origPackage.sharedUser != null) {
5830                                // Make sure uid is compatible between packages.
5831                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5832                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5833                                            + " to " + pkg.packageName + ": old uid "
5834                                            + origPackage.sharedUser.name
5835                                            + " differs from " + pkg.mSharedUserId);
5836                                    origPackage = null;
5837                                    continue;
5838                                }
5839                            } else {
5840                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5841                                        + pkg.packageName + " to old name " + origPackage.name);
5842                            }
5843                            break;
5844                        }
5845                    }
5846                }
5847            }
5848
5849            if (mTransferedPackages.contains(pkg.packageName)) {
5850                Slog.w(TAG, "Package " + pkg.packageName
5851                        + " was transferred to another, but its .apk remains");
5852            }
5853
5854            // Just create the setting, don't add it yet. For already existing packages
5855            // the PkgSetting exists already and doesn't have to be created.
5856            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5857                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5858                    pkg.applicationInfo.primaryCpuAbi,
5859                    pkg.applicationInfo.secondaryCpuAbi,
5860                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
5861                    user, false);
5862            if (pkgSetting == null) {
5863                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5864                        "Creating application package " + pkg.packageName + " failed");
5865            }
5866
5867            if (pkgSetting.origPackage != null) {
5868                // If we are first transitioning from an original package,
5869                // fix up the new package's name now.  We need to do this after
5870                // looking up the package under its new name, so getPackageLP
5871                // can take care of fiddling things correctly.
5872                pkg.setPackageName(origPackage.name);
5873
5874                // File a report about this.
5875                String msg = "New package " + pkgSetting.realName
5876                        + " renamed to replace old package " + pkgSetting.name;
5877                reportSettingsProblem(Log.WARN, msg);
5878
5879                // Make a note of it.
5880                mTransferedPackages.add(origPackage.name);
5881
5882                // No longer need to retain this.
5883                pkgSetting.origPackage = null;
5884            }
5885
5886            if (realName != null) {
5887                // Make a note of it.
5888                mTransferedPackages.add(pkg.packageName);
5889            }
5890
5891            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5892                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5893            }
5894
5895            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5896                // Check all shared libraries and map to their actual file path.
5897                // We only do this here for apps not on a system dir, because those
5898                // are the only ones that can fail an install due to this.  We
5899                // will take care of the system apps by updating all of their
5900                // library paths after the scan is done.
5901                updateSharedLibrariesLPw(pkg, null);
5902            }
5903
5904            if (mFoundPolicyFile) {
5905                SELinuxMMAC.assignSeinfoValue(pkg);
5906            }
5907
5908            pkg.applicationInfo.uid = pkgSetting.appId;
5909            pkg.mExtras = pkgSetting;
5910            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5911                try {
5912                    verifySignaturesLP(pkgSetting, pkg);
5913                    // We just determined the app is signed correctly, so bring
5914                    // over the latest parsed certs.
5915                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5916                } catch (PackageManagerException e) {
5917                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5918                        throw e;
5919                    }
5920                    // The signature has changed, but this package is in the system
5921                    // image...  let's recover!
5922                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5923                    // However...  if this package is part of a shared user, but it
5924                    // doesn't match the signature of the shared user, let's fail.
5925                    // What this means is that you can't change the signatures
5926                    // associated with an overall shared user, which doesn't seem all
5927                    // that unreasonable.
5928                    if (pkgSetting.sharedUser != null) {
5929                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5930                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5931                            throw new PackageManagerException(
5932                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5933                                            "Signature mismatch for shared user : "
5934                                            + pkgSetting.sharedUser);
5935                        }
5936                    }
5937                    // File a report about this.
5938                    String msg = "System package " + pkg.packageName
5939                        + " signature changed; retaining data.";
5940                    reportSettingsProblem(Log.WARN, msg);
5941                }
5942            } else {
5943                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5944                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5945                            + pkg.packageName + " upgrade keys do not match the "
5946                            + "previously installed version");
5947                } else {
5948                    // We just determined the app is signed correctly, so bring
5949                    // over the latest parsed certs.
5950                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5951                }
5952            }
5953            // Verify that this new package doesn't have any content providers
5954            // that conflict with existing packages.  Only do this if the
5955            // package isn't already installed, since we don't want to break
5956            // things that are installed.
5957            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5958                final int N = pkg.providers.size();
5959                int i;
5960                for (i=0; i<N; i++) {
5961                    PackageParser.Provider p = pkg.providers.get(i);
5962                    if (p.info.authority != null) {
5963                        String names[] = p.info.authority.split(";");
5964                        for (int j = 0; j < names.length; j++) {
5965                            if (mProvidersByAuthority.containsKey(names[j])) {
5966                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5967                                final String otherPackageName =
5968                                        ((other != null && other.getComponentName() != null) ?
5969                                                other.getComponentName().getPackageName() : "?");
5970                                throw new PackageManagerException(
5971                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5972                                                "Can't install because provider name " + names[j]
5973                                                + " (in package " + pkg.applicationInfo.packageName
5974                                                + ") is already used by " + otherPackageName);
5975                            }
5976                        }
5977                    }
5978                }
5979            }
5980
5981            if (pkg.mAdoptPermissions != null) {
5982                // This package wants to adopt ownership of permissions from
5983                // another package.
5984                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5985                    final String origName = pkg.mAdoptPermissions.get(i);
5986                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5987                    if (orig != null) {
5988                        if (verifyPackageUpdateLPr(orig, pkg)) {
5989                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5990                                    + pkg.packageName);
5991                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5992                        }
5993                    }
5994                }
5995            }
5996        }
5997
5998        final String pkgName = pkg.packageName;
5999
6000        final long scanFileTime = scanFile.lastModified();
6001        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6002        pkg.applicationInfo.processName = fixProcessName(
6003                pkg.applicationInfo.packageName,
6004                pkg.applicationInfo.processName,
6005                pkg.applicationInfo.uid);
6006
6007        File dataPath;
6008        if (mPlatformPackage == pkg) {
6009            // The system package is special.
6010            dataPath = new File(Environment.getDataDirectory(), "system");
6011
6012            pkg.applicationInfo.dataDir = dataPath.getPath();
6013
6014        } else {
6015            // This is a normal package, need to make its data directory.
6016            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6017                    UserHandle.USER_OWNER);
6018
6019            boolean uidError = false;
6020            if (dataPath.exists()) {
6021                int currentUid = 0;
6022                try {
6023                    StructStat stat = Os.stat(dataPath.getPath());
6024                    currentUid = stat.st_uid;
6025                } catch (ErrnoException e) {
6026                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6027                }
6028
6029                // If we have mismatched owners for the data path, we have a problem.
6030                if (currentUid != pkg.applicationInfo.uid) {
6031                    boolean recovered = false;
6032                    if (currentUid == 0) {
6033                        // The directory somehow became owned by root.  Wow.
6034                        // This is probably because the system was stopped while
6035                        // installd was in the middle of messing with its libs
6036                        // directory.  Ask installd to fix that.
6037                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6038                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6039                        if (ret >= 0) {
6040                            recovered = true;
6041                            String msg = "Package " + pkg.packageName
6042                                    + " unexpectedly changed to uid 0; recovered to " +
6043                                    + pkg.applicationInfo.uid;
6044                            reportSettingsProblem(Log.WARN, msg);
6045                        }
6046                    }
6047                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6048                            || (scanFlags&SCAN_BOOTING) != 0)) {
6049                        // If this is a system app, we can at least delete its
6050                        // current data so the application will still work.
6051                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6052                        if (ret >= 0) {
6053                            // TODO: Kill the processes first
6054                            // Old data gone!
6055                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6056                                    ? "System package " : "Third party package ";
6057                            String msg = prefix + pkg.packageName
6058                                    + " has changed from uid: "
6059                                    + currentUid + " to "
6060                                    + pkg.applicationInfo.uid + "; old data erased";
6061                            reportSettingsProblem(Log.WARN, msg);
6062                            recovered = true;
6063
6064                            // And now re-install the app.
6065                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6066                                    pkg.applicationInfo.seinfo);
6067                            if (ret == -1) {
6068                                // Ack should not happen!
6069                                msg = prefix + pkg.packageName
6070                                        + " could not have data directory re-created after delete.";
6071                                reportSettingsProblem(Log.WARN, msg);
6072                                throw new PackageManagerException(
6073                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6074                            }
6075                        }
6076                        if (!recovered) {
6077                            mHasSystemUidErrors = true;
6078                        }
6079                    } else if (!recovered) {
6080                        // If we allow this install to proceed, we will be broken.
6081                        // Abort, abort!
6082                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6083                                "scanPackageLI");
6084                    }
6085                    if (!recovered) {
6086                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6087                            + pkg.applicationInfo.uid + "/fs_"
6088                            + currentUid;
6089                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6090                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6091                        String msg = "Package " + pkg.packageName
6092                                + " has mismatched uid: "
6093                                + currentUid + " on disk, "
6094                                + pkg.applicationInfo.uid + " in settings";
6095                        // writer
6096                        synchronized (mPackages) {
6097                            mSettings.mReadMessages.append(msg);
6098                            mSettings.mReadMessages.append('\n');
6099                            uidError = true;
6100                            if (!pkgSetting.uidError) {
6101                                reportSettingsProblem(Log.ERROR, msg);
6102                            }
6103                        }
6104                    }
6105                }
6106                pkg.applicationInfo.dataDir = dataPath.getPath();
6107                if (mShouldRestoreconData) {
6108                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6109                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6110                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6111                }
6112            } else {
6113                if (DEBUG_PACKAGE_SCANNING) {
6114                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6115                        Log.v(TAG, "Want this data dir: " + dataPath);
6116                }
6117                //invoke installer to do the actual installation
6118                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6119                        pkg.applicationInfo.seinfo);
6120                if (ret < 0) {
6121                    // Error from installer
6122                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6123                            "Unable to create data dirs [errorCode=" + ret + "]");
6124                }
6125
6126                if (dataPath.exists()) {
6127                    pkg.applicationInfo.dataDir = dataPath.getPath();
6128                } else {
6129                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6130                    pkg.applicationInfo.dataDir = null;
6131                }
6132            }
6133
6134            pkgSetting.uidError = uidError;
6135        }
6136
6137        final String path = scanFile.getPath();
6138        final String codePath = pkg.applicationInfo.getCodePath();
6139        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6140        if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6141            setBundledAppAbisAndRoots(pkg, pkgSetting);
6142
6143            // If we haven't found any native libraries for the app, check if it has
6144            // renderscript code. We'll need to force the app to 32 bit if it has
6145            // renderscript bitcode.
6146            if (pkg.applicationInfo.primaryCpuAbi == null
6147                    && pkg.applicationInfo.secondaryCpuAbi == null
6148                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
6149                NativeLibraryHelper.Handle handle = null;
6150                try {
6151                    handle = NativeLibraryHelper.Handle.create(scanFile);
6152                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6153                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6154                    }
6155                } catch (IOException ioe) {
6156                    Slog.w(TAG, "Error scanning system app : " + ioe);
6157                } finally {
6158                    IoUtils.closeQuietly(handle);
6159                }
6160            }
6161
6162            setNativeLibraryPaths(pkg);
6163        } else {
6164            // TODO: We can probably be smarter about this stuff. For installed apps,
6165            // we can calculate this information at install time once and for all. For
6166            // system apps, we can probably assume that this information doesn't change
6167            // after the first boot scan. As things stand, we do lots of unnecessary work.
6168
6169            // Give ourselves some initial paths; we'll come back for another
6170            // pass once we've determined ABI below.
6171            setNativeLibraryPaths(pkg);
6172
6173            final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg);
6174            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6175            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6176
6177            NativeLibraryHelper.Handle handle = null;
6178            try {
6179                handle = NativeLibraryHelper.Handle.create(scanFile);
6180                // TODO(multiArch): This can be null for apps that didn't go through the
6181                // usual installation process. We can calculate it again, like we
6182                // do during install time.
6183                //
6184                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6185                // unnecessary.
6186                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6187
6188                // Null out the abis so that they can be recalculated.
6189                pkg.applicationInfo.primaryCpuAbi = null;
6190                pkg.applicationInfo.secondaryCpuAbi = null;
6191                if (isMultiArch(pkg.applicationInfo)) {
6192                    // Warn if we've set an abiOverride for multi-lib packages..
6193                    // By definition, we need to copy both 32 and 64 bit libraries for
6194                    // such packages.
6195                    if (pkg.cpuAbiOverride != null
6196                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
6197                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
6198                    }
6199
6200                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
6201                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
6202                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
6203                        if (isAsec) {
6204                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
6205                        } else {
6206                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6207                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
6208                                    useIsaSpecificSubdirs);
6209                        }
6210                    }
6211
6212                    maybeThrowExceptionForMultiArchCopy(
6213                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
6214
6215                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
6216                        if (isAsec) {
6217                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
6218                        } else {
6219                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6220                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
6221                                    useIsaSpecificSubdirs);
6222                        }
6223                    }
6224
6225                    maybeThrowExceptionForMultiArchCopy(
6226                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
6227
6228                    if (abi64 >= 0) {
6229                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
6230                    }
6231
6232                    if (abi32 >= 0) {
6233                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
6234                        if (abi64 >= 0) {
6235                            pkg.applicationInfo.secondaryCpuAbi = abi;
6236                        } else {
6237                            pkg.applicationInfo.primaryCpuAbi = abi;
6238                        }
6239                    }
6240                } else {
6241                    String[] abiList = (cpuAbiOverride != null) ?
6242                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
6243
6244                    // Enable gross and lame hacks for apps that are built with old
6245                    // SDK tools. We must scan their APKs for renderscript bitcode and
6246                    // not launch them if it's present. Don't bother checking on devices
6247                    // that don't have 64 bit support.
6248                    boolean needsRenderScriptOverride = false;
6249                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
6250                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6251                        abiList = Build.SUPPORTED_32_BIT_ABIS;
6252                        needsRenderScriptOverride = true;
6253                    }
6254
6255                    final int copyRet;
6256                    if (isAsec) {
6257                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6258                    } else {
6259                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6260                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
6261                    }
6262
6263                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
6264                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6265                                "Error unpackaging native libs for app, errorCode=" + copyRet);
6266                    }
6267
6268                    if (copyRet >= 0) {
6269                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
6270                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
6271                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
6272                    } else if (needsRenderScriptOverride) {
6273                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
6274                    }
6275                }
6276            } catch (IOException ioe) {
6277                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
6278            } finally {
6279                IoUtils.closeQuietly(handle);
6280            }
6281
6282            // Now that we've calculated the ABIs and determined if it's an internal app,
6283            // we will go ahead and populate the nativeLibraryPath.
6284            setNativeLibraryPaths(pkg);
6285
6286            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6287            final int[] userIds = sUserManager.getUserIds();
6288            synchronized (mInstallLock) {
6289                // Create a native library symlink only if we have native libraries
6290                // and if the native libraries are 32 bit libraries. We do not provide
6291                // this symlink for 64 bit libraries.
6292                if (pkg.applicationInfo.primaryCpuAbi != null &&
6293                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6294                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6295                    for (int userId : userIds) {
6296                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6297                                nativeLibPath, userId) < 0) {
6298                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6299                                    "Failed linking native library dir (user=" + userId + ")");
6300                        }
6301                    }
6302                }
6303            }
6304        }
6305
6306        // This is a special case for the "system" package, where the ABI is
6307        // dictated by the zygote configuration (and init.rc). We should keep track
6308        // of this ABI so that we can deal with "normal" applications that run under
6309        // the same UID correctly.
6310        if (mPlatformPackage == pkg) {
6311            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6312                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6313        }
6314
6315        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6316        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6317        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6318        // Copy the derived override back to the parsed package, so that we can
6319        // update the package settings accordingly.
6320        pkg.cpuAbiOverride = cpuAbiOverride;
6321
6322        if (DEBUG_ABI_SELECTION) {
6323            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6324                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6325                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6326        }
6327
6328        // Push the derived path down into PackageSettings so we know what to
6329        // clean up at uninstall time.
6330        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6331
6332        if (DEBUG_ABI_SELECTION) {
6333            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6334                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6335                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6336        }
6337
6338        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6339            // We don't do this here during boot because we can do it all
6340            // at once after scanning all existing packages.
6341            //
6342            // We also do this *before* we perform dexopt on this package, so that
6343            // we can avoid redundant dexopts, and also to make sure we've got the
6344            // code and package path correct.
6345            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6346                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6347        }
6348
6349        if ((scanFlags & SCAN_NO_DEX) == 0) {
6350            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6351                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6352            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6353                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6354            }
6355        }
6356        if (mFactoryTest && pkg.requestedPermissions.contains(
6357                android.Manifest.permission.FACTORY_TEST)) {
6358            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6359        }
6360
6361        ArrayList<PackageParser.Package> clientLibPkgs = null;
6362
6363        // writer
6364        synchronized (mPackages) {
6365            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6366                // Only system apps can add new shared libraries.
6367                if (pkg.libraryNames != null) {
6368                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6369                        String name = pkg.libraryNames.get(i);
6370                        boolean allowed = false;
6371                        if (pkg.isUpdatedSystemApp()) {
6372                            // New library entries can only be added through the
6373                            // system image.  This is important to get rid of a lot
6374                            // of nasty edge cases: for example if we allowed a non-
6375                            // system update of the app to add a library, then uninstalling
6376                            // the update would make the library go away, and assumptions
6377                            // we made such as through app install filtering would now
6378                            // have allowed apps on the device which aren't compatible
6379                            // with it.  Better to just have the restriction here, be
6380                            // conservative, and create many fewer cases that can negatively
6381                            // impact the user experience.
6382                            final PackageSetting sysPs = mSettings
6383                                    .getDisabledSystemPkgLPr(pkg.packageName);
6384                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6385                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6386                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6387                                        allowed = true;
6388                                        allowed = true;
6389                                        break;
6390                                    }
6391                                }
6392                            }
6393                        } else {
6394                            allowed = true;
6395                        }
6396                        if (allowed) {
6397                            if (!mSharedLibraries.containsKey(name)) {
6398                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6399                            } else if (!name.equals(pkg.packageName)) {
6400                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6401                                        + name + " already exists; skipping");
6402                            }
6403                        } else {
6404                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6405                                    + name + " that is not declared on system image; skipping");
6406                        }
6407                    }
6408                    if ((scanFlags&SCAN_BOOTING) == 0) {
6409                        // If we are not booting, we need to update any applications
6410                        // that are clients of our shared library.  If we are booting,
6411                        // this will all be done once the scan is complete.
6412                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6413                    }
6414                }
6415            }
6416        }
6417
6418        // We also need to dexopt any apps that are dependent on this library.  Note that
6419        // if these fail, we should abort the install since installing the library will
6420        // result in some apps being broken.
6421        if (clientLibPkgs != null) {
6422            if ((scanFlags & SCAN_NO_DEX) == 0) {
6423                for (int i = 0; i < clientLibPkgs.size(); i++) {
6424                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6425                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6426                            null /* instruction sets */, forceDex,
6427                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6428                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6429                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6430                                "scanPackageLI failed to dexopt clientLibPkgs");
6431                    }
6432                }
6433            }
6434        }
6435
6436        // Request the ActivityManager to kill the process(only for existing packages)
6437        // so that we do not end up in a confused state while the user is still using the older
6438        // version of the application while the new one gets installed.
6439        if ((scanFlags & SCAN_REPLACING) != 0) {
6440            killApplication(pkg.applicationInfo.packageName,
6441                        pkg.applicationInfo.uid, "update pkg");
6442        }
6443
6444        // Also need to kill any apps that are dependent on the library.
6445        if (clientLibPkgs != null) {
6446            for (int i=0; i<clientLibPkgs.size(); i++) {
6447                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6448                killApplication(clientPkg.applicationInfo.packageName,
6449                        clientPkg.applicationInfo.uid, "update lib");
6450            }
6451        }
6452
6453        // writer
6454        synchronized (mPackages) {
6455            // We don't expect installation to fail beyond this point
6456
6457            // Add the new setting to mSettings
6458            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6459            // Add the new setting to mPackages
6460            mPackages.put(pkg.applicationInfo.packageName, pkg);
6461            // Make sure we don't accidentally delete its data.
6462            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6463            while (iter.hasNext()) {
6464                PackageCleanItem item = iter.next();
6465                if (pkgName.equals(item.packageName)) {
6466                    iter.remove();
6467                }
6468            }
6469
6470            // Take care of first install / last update times.
6471            if (currentTime != 0) {
6472                if (pkgSetting.firstInstallTime == 0) {
6473                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6474                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6475                    pkgSetting.lastUpdateTime = currentTime;
6476                }
6477            } else if (pkgSetting.firstInstallTime == 0) {
6478                // We need *something*.  Take time time stamp of the file.
6479                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6480            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6481                if (scanFileTime != pkgSetting.timeStamp) {
6482                    // A package on the system image has changed; consider this
6483                    // to be an update.
6484                    pkgSetting.lastUpdateTime = scanFileTime;
6485                }
6486            }
6487
6488            // Add the package's KeySets to the global KeySetManagerService
6489            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6490            try {
6491                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6492                if (pkg.mKeySetMapping != null) {
6493                    ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping);
6494                    if (pkg.mUpgradeKeySets != null) {
6495                        ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets);
6496                    }
6497                }
6498            } catch (NullPointerException e) {
6499                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6500            } catch (IllegalArgumentException e) {
6501                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6502            }
6503
6504            int N = pkg.providers.size();
6505            StringBuilder r = null;
6506            int i;
6507            for (i=0; i<N; i++) {
6508                PackageParser.Provider p = pkg.providers.get(i);
6509                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6510                        p.info.processName, pkg.applicationInfo.uid);
6511                mProviders.addProvider(p);
6512                p.syncable = p.info.isSyncable;
6513                if (p.info.authority != null) {
6514                    String names[] = p.info.authority.split(";");
6515                    p.info.authority = null;
6516                    for (int j = 0; j < names.length; j++) {
6517                        if (j == 1 && p.syncable) {
6518                            // We only want the first authority for a provider to possibly be
6519                            // syncable, so if we already added this provider using a different
6520                            // authority clear the syncable flag. We copy the provider before
6521                            // changing it because the mProviders object contains a reference
6522                            // to a provider that we don't want to change.
6523                            // Only do this for the second authority since the resulting provider
6524                            // object can be the same for all future authorities for this provider.
6525                            p = new PackageParser.Provider(p);
6526                            p.syncable = false;
6527                        }
6528                        if (!mProvidersByAuthority.containsKey(names[j])) {
6529                            mProvidersByAuthority.put(names[j], p);
6530                            if (p.info.authority == null) {
6531                                p.info.authority = names[j];
6532                            } else {
6533                                p.info.authority = p.info.authority + ";" + names[j];
6534                            }
6535                            if (DEBUG_PACKAGE_SCANNING) {
6536                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6537                                    Log.d(TAG, "Registered content provider: " + names[j]
6538                                            + ", className = " + p.info.name + ", isSyncable = "
6539                                            + p.info.isSyncable);
6540                            }
6541                        } else {
6542                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6543                            Slog.w(TAG, "Skipping provider name " + names[j] +
6544                                    " (in package " + pkg.applicationInfo.packageName +
6545                                    "): name already used by "
6546                                    + ((other != null && other.getComponentName() != null)
6547                                            ? other.getComponentName().getPackageName() : "?"));
6548                        }
6549                    }
6550                }
6551                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6552                    if (r == null) {
6553                        r = new StringBuilder(256);
6554                    } else {
6555                        r.append(' ');
6556                    }
6557                    r.append(p.info.name);
6558                }
6559            }
6560            if (r != null) {
6561                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6562            }
6563
6564            N = pkg.services.size();
6565            r = null;
6566            for (i=0; i<N; i++) {
6567                PackageParser.Service s = pkg.services.get(i);
6568                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6569                        s.info.processName, pkg.applicationInfo.uid);
6570                mServices.addService(s);
6571                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6572                    if (r == null) {
6573                        r = new StringBuilder(256);
6574                    } else {
6575                        r.append(' ');
6576                    }
6577                    r.append(s.info.name);
6578                }
6579            }
6580            if (r != null) {
6581                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6582            }
6583
6584            N = pkg.receivers.size();
6585            r = null;
6586            for (i=0; i<N; i++) {
6587                PackageParser.Activity a = pkg.receivers.get(i);
6588                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6589                        a.info.processName, pkg.applicationInfo.uid);
6590                mReceivers.addActivity(a, "receiver");
6591                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6592                    if (r == null) {
6593                        r = new StringBuilder(256);
6594                    } else {
6595                        r.append(' ');
6596                    }
6597                    r.append(a.info.name);
6598                }
6599            }
6600            if (r != null) {
6601                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6602            }
6603
6604            N = pkg.activities.size();
6605            r = null;
6606            for (i=0; i<N; i++) {
6607                PackageParser.Activity a = pkg.activities.get(i);
6608                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6609                        a.info.processName, pkg.applicationInfo.uid);
6610                mActivities.addActivity(a, "activity");
6611                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6612                    if (r == null) {
6613                        r = new StringBuilder(256);
6614                    } else {
6615                        r.append(' ');
6616                    }
6617                    r.append(a.info.name);
6618                }
6619            }
6620            if (r != null) {
6621                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6622            }
6623
6624            N = pkg.permissionGroups.size();
6625            r = null;
6626            for (i=0; i<N; i++) {
6627                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6628                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6629                if (cur == null) {
6630                    mPermissionGroups.put(pg.info.name, pg);
6631                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6632                        if (r == null) {
6633                            r = new StringBuilder(256);
6634                        } else {
6635                            r.append(' ');
6636                        }
6637                        r.append(pg.info.name);
6638                    }
6639                } else {
6640                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6641                            + pg.info.packageName + " ignored: original from "
6642                            + cur.info.packageName);
6643                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6644                        if (r == null) {
6645                            r = new StringBuilder(256);
6646                        } else {
6647                            r.append(' ');
6648                        }
6649                        r.append("DUP:");
6650                        r.append(pg.info.name);
6651                    }
6652                }
6653            }
6654            if (r != null) {
6655                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6656            }
6657
6658            N = pkg.permissions.size();
6659            r = null;
6660            for (i=0; i<N; i++) {
6661                PackageParser.Permission p = pkg.permissions.get(i);
6662
6663                // Now that permission groups have a special meaning, we ignore permission
6664                // groups for legacy apps to prevent unexpected behavior. In particular,
6665                // permissions for one app being granted to someone just becuase they happen
6666                // to be in a group defined by another app (before this had no implications).
6667                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6668                    p.group = mPermissionGroups.get(p.info.group);
6669                    // Warn for a permission in an unknown group.
6670                    if (p.info.group != null && p.group == null) {
6671                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6672                                + p.info.packageName + " in an unknown group " + p.info.group);
6673                    }
6674                }
6675
6676                ArrayMap<String, BasePermission> permissionMap =
6677                        p.tree ? mSettings.mPermissionTrees
6678                                : mSettings.mPermissions;
6679                BasePermission bp = permissionMap.get(p.info.name);
6680
6681                // Allow system apps to redefine non-system permissions
6682                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6683                    final boolean currentOwnerIsSystem = (bp.perm != null
6684                            && isSystemApp(bp.perm.owner));
6685                    if (isSystemApp(p.owner)) {
6686                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6687                            // It's a built-in permission and no owner, take ownership now
6688                            bp.packageSetting = pkgSetting;
6689                            bp.perm = p;
6690                            bp.uid = pkg.applicationInfo.uid;
6691                            bp.sourcePackage = p.info.packageName;
6692                        } else if (!currentOwnerIsSystem) {
6693                            String msg = "New decl " + p.owner + " of permission  "
6694                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6695                            reportSettingsProblem(Log.WARN, msg);
6696                            bp = null;
6697                        }
6698                    }
6699                }
6700
6701                if (bp == null) {
6702                    bp = new BasePermission(p.info.name, p.info.packageName,
6703                            BasePermission.TYPE_NORMAL);
6704                    permissionMap.put(p.info.name, bp);
6705                }
6706
6707                if (bp.perm == null) {
6708                    if (bp.sourcePackage == null
6709                            || bp.sourcePackage.equals(p.info.packageName)) {
6710                        BasePermission tree = findPermissionTreeLP(p.info.name);
6711                        if (tree == null
6712                                || tree.sourcePackage.equals(p.info.packageName)) {
6713                            bp.packageSetting = pkgSetting;
6714                            bp.perm = p;
6715                            bp.uid = pkg.applicationInfo.uid;
6716                            bp.sourcePackage = p.info.packageName;
6717                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6718                                if (r == null) {
6719                                    r = new StringBuilder(256);
6720                                } else {
6721                                    r.append(' ');
6722                                }
6723                                r.append(p.info.name);
6724                            }
6725                        } else {
6726                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6727                                    + p.info.packageName + " ignored: base tree "
6728                                    + tree.name + " is from package "
6729                                    + tree.sourcePackage);
6730                        }
6731                    } else {
6732                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6733                                + p.info.packageName + " ignored: original from "
6734                                + bp.sourcePackage);
6735                    }
6736                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6737                    if (r == null) {
6738                        r = new StringBuilder(256);
6739                    } else {
6740                        r.append(' ');
6741                    }
6742                    r.append("DUP:");
6743                    r.append(p.info.name);
6744                }
6745                if (bp.perm == p) {
6746                    bp.protectionLevel = p.info.protectionLevel;
6747                }
6748            }
6749
6750            if (r != null) {
6751                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6752            }
6753
6754            N = pkg.instrumentation.size();
6755            r = null;
6756            for (i=0; i<N; i++) {
6757                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6758                a.info.packageName = pkg.applicationInfo.packageName;
6759                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6760                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6761                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6762                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6763                a.info.dataDir = pkg.applicationInfo.dataDir;
6764
6765                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6766                // need other information about the application, like the ABI and what not ?
6767                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6768                mInstrumentation.put(a.getComponentName(), a);
6769                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6770                    if (r == null) {
6771                        r = new StringBuilder(256);
6772                    } else {
6773                        r.append(' ');
6774                    }
6775                    r.append(a.info.name);
6776                }
6777            }
6778            if (r != null) {
6779                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6780            }
6781
6782            if (pkg.protectedBroadcasts != null) {
6783                N = pkg.protectedBroadcasts.size();
6784                for (i=0; i<N; i++) {
6785                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6786                }
6787            }
6788
6789            pkgSetting.setTimeStamp(scanFileTime);
6790
6791            // Create idmap files for pairs of (packages, overlay packages).
6792            // Note: "android", ie framework-res.apk, is handled by native layers.
6793            if (pkg.mOverlayTarget != null) {
6794                // This is an overlay package.
6795                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6796                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6797                        mOverlays.put(pkg.mOverlayTarget,
6798                                new ArrayMap<String, PackageParser.Package>());
6799                    }
6800                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6801                    map.put(pkg.packageName, pkg);
6802                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6803                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6804                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6805                                "scanPackageLI failed to createIdmap");
6806                    }
6807                }
6808            } else if (mOverlays.containsKey(pkg.packageName) &&
6809                    !pkg.packageName.equals("android")) {
6810                // This is a regular package, with one or more known overlay packages.
6811                createIdmapsForPackageLI(pkg);
6812            }
6813        }
6814
6815        return pkg;
6816    }
6817
6818    /**
6819     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6820     * i.e, so that all packages can be run inside a single process if required.
6821     *
6822     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6823     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6824     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6825     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6826     * updating a package that belongs to a shared user.
6827     *
6828     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6829     * adds unnecessary complexity.
6830     */
6831    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6832            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6833        String requiredInstructionSet = null;
6834        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6835            requiredInstructionSet = VMRuntime.getInstructionSet(
6836                     scannedPackage.applicationInfo.primaryCpuAbi);
6837        }
6838
6839        PackageSetting requirer = null;
6840        for (PackageSetting ps : packagesForUser) {
6841            // If packagesForUser contains scannedPackage, we skip it. This will happen
6842            // when scannedPackage is an update of an existing package. Without this check,
6843            // we will never be able to change the ABI of any package belonging to a shared
6844            // user, even if it's compatible with other packages.
6845            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6846                if (ps.primaryCpuAbiString == null) {
6847                    continue;
6848                }
6849
6850                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6851                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6852                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6853                    // this but there's not much we can do.
6854                    String errorMessage = "Instruction set mismatch, "
6855                            + ((requirer == null) ? "[caller]" : requirer)
6856                            + " requires " + requiredInstructionSet + " whereas " + ps
6857                            + " requires " + instructionSet;
6858                    Slog.w(TAG, errorMessage);
6859                }
6860
6861                if (requiredInstructionSet == null) {
6862                    requiredInstructionSet = instructionSet;
6863                    requirer = ps;
6864                }
6865            }
6866        }
6867
6868        if (requiredInstructionSet != null) {
6869            String adjustedAbi;
6870            if (requirer != null) {
6871                // requirer != null implies that either scannedPackage was null or that scannedPackage
6872                // did not require an ABI, in which case we have to adjust scannedPackage to match
6873                // the ABI of the set (which is the same as requirer's ABI)
6874                adjustedAbi = requirer.primaryCpuAbiString;
6875                if (scannedPackage != null) {
6876                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6877                }
6878            } else {
6879                // requirer == null implies that we're updating all ABIs in the set to
6880                // match scannedPackage.
6881                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6882            }
6883
6884            for (PackageSetting ps : packagesForUser) {
6885                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6886                    if (ps.primaryCpuAbiString != null) {
6887                        continue;
6888                    }
6889
6890                    ps.primaryCpuAbiString = adjustedAbi;
6891                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6892                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6893                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6894
6895                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
6896                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
6897                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6898                            ps.primaryCpuAbiString = null;
6899                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6900                            return;
6901                        } else {
6902                            mInstaller.rmdex(ps.codePathString,
6903                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
6904                        }
6905                    }
6906                }
6907            }
6908        }
6909    }
6910
6911    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6912        synchronized (mPackages) {
6913            mResolverReplaced = true;
6914            // Set up information for custom user intent resolution activity.
6915            mResolveActivity.applicationInfo = pkg.applicationInfo;
6916            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6917            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6918            mResolveActivity.processName = pkg.applicationInfo.packageName;
6919            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6920            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6921                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6922            mResolveActivity.theme = 0;
6923            mResolveActivity.exported = true;
6924            mResolveActivity.enabled = true;
6925            mResolveInfo.activityInfo = mResolveActivity;
6926            mResolveInfo.priority = 0;
6927            mResolveInfo.preferredOrder = 0;
6928            mResolveInfo.match = 0;
6929            mResolveComponentName = mCustomResolverComponentName;
6930            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6931                    mResolveComponentName);
6932        }
6933    }
6934
6935    private static String calculateBundledApkRoot(final String codePathString) {
6936        final File codePath = new File(codePathString);
6937        final File codeRoot;
6938        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6939            codeRoot = Environment.getRootDirectory();
6940        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6941            codeRoot = Environment.getOemDirectory();
6942        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6943            codeRoot = Environment.getVendorDirectory();
6944        } else {
6945            // Unrecognized code path; take its top real segment as the apk root:
6946            // e.g. /something/app/blah.apk => /something
6947            try {
6948                File f = codePath.getCanonicalFile();
6949                File parent = f.getParentFile();    // non-null because codePath is a file
6950                File tmp;
6951                while ((tmp = parent.getParentFile()) != null) {
6952                    f = parent;
6953                    parent = tmp;
6954                }
6955                codeRoot = f;
6956                Slog.w(TAG, "Unrecognized code path "
6957                        + codePath + " - using " + codeRoot);
6958            } catch (IOException e) {
6959                // Can't canonicalize the code path -- shenanigans?
6960                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6961                return Environment.getRootDirectory().getPath();
6962            }
6963        }
6964        return codeRoot.getPath();
6965    }
6966
6967    /**
6968     * Derive and set the location of native libraries for the given package,
6969     * which varies depending on where and how the package was installed.
6970     */
6971    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6972        final ApplicationInfo info = pkg.applicationInfo;
6973        final String codePath = pkg.codePath;
6974        final File codeFile = new File(codePath);
6975        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
6976        final boolean asecApp = info.isForwardLocked() || isExternal(info);
6977
6978        info.nativeLibraryRootDir = null;
6979        info.nativeLibraryRootRequiresIsa = false;
6980        info.nativeLibraryDir = null;
6981        info.secondaryNativeLibraryDir = null;
6982
6983        if (isApkFile(codeFile)) {
6984            // Monolithic install
6985            if (bundledApp) {
6986                // If "/system/lib64/apkname" exists, assume that is the per-package
6987                // native library directory to use; otherwise use "/system/lib/apkname".
6988                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6989                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6990                        getPrimaryInstructionSet(info));
6991
6992                // This is a bundled system app so choose the path based on the ABI.
6993                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6994                // is just the default path.
6995                final String apkName = deriveCodePathName(codePath);
6996                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6997                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6998                        apkName).getAbsolutePath();
6999
7000                if (info.secondaryCpuAbi != null) {
7001                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7002                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7003                            secondaryLibDir, apkName).getAbsolutePath();
7004                }
7005            } else if (asecApp) {
7006                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7007                        .getAbsolutePath();
7008            } else {
7009                final String apkName = deriveCodePathName(codePath);
7010                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7011                        .getAbsolutePath();
7012            }
7013
7014            info.nativeLibraryRootRequiresIsa = false;
7015            info.nativeLibraryDir = info.nativeLibraryRootDir;
7016        } else {
7017            // Cluster install
7018            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7019            info.nativeLibraryRootRequiresIsa = true;
7020
7021            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7022                    getPrimaryInstructionSet(info)).getAbsolutePath();
7023
7024            if (info.secondaryCpuAbi != null) {
7025                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7026                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7027            }
7028        }
7029    }
7030
7031    /**
7032     * Calculate the abis and roots for a bundled app. These can uniquely
7033     * be determined from the contents of the system partition, i.e whether
7034     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7035     * of this information, and instead assume that the system was built
7036     * sensibly.
7037     */
7038    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7039                                           PackageSetting pkgSetting) {
7040        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7041
7042        // If "/system/lib64/apkname" exists, assume that is the per-package
7043        // native library directory to use; otherwise use "/system/lib/apkname".
7044        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7045        setBundledAppAbi(pkg, apkRoot, apkName);
7046        // pkgSetting might be null during rescan following uninstall of updates
7047        // to a bundled app, so accommodate that possibility.  The settings in
7048        // that case will be established later from the parsed package.
7049        //
7050        // If the settings aren't null, sync them up with what we've just derived.
7051        // note that apkRoot isn't stored in the package settings.
7052        if (pkgSetting != null) {
7053            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7054            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7055        }
7056    }
7057
7058    /**
7059     * Deduces the ABI of a bundled app and sets the relevant fields on the
7060     * parsed pkg object.
7061     *
7062     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7063     *        under which system libraries are installed.
7064     * @param apkName the name of the installed package.
7065     */
7066    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7067        final File codeFile = new File(pkg.codePath);
7068
7069        final boolean has64BitLibs;
7070        final boolean has32BitLibs;
7071        if (isApkFile(codeFile)) {
7072            // Monolithic install
7073            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7074            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7075        } else {
7076            // Cluster install
7077            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7078            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7079                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7080                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7081                has64BitLibs = (new File(rootDir, isa)).exists();
7082            } else {
7083                has64BitLibs = false;
7084            }
7085            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7086                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7087                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7088                has32BitLibs = (new File(rootDir, isa)).exists();
7089            } else {
7090                has32BitLibs = false;
7091            }
7092        }
7093
7094        if (has64BitLibs && !has32BitLibs) {
7095            // The package has 64 bit libs, but not 32 bit libs. Its primary
7096            // ABI should be 64 bit. We can safely assume here that the bundled
7097            // native libraries correspond to the most preferred ABI in the list.
7098
7099            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7100            pkg.applicationInfo.secondaryCpuAbi = null;
7101        } else if (has32BitLibs && !has64BitLibs) {
7102            // The package has 32 bit libs but not 64 bit libs. Its primary
7103            // ABI should be 32 bit.
7104
7105            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7106            pkg.applicationInfo.secondaryCpuAbi = null;
7107        } else if (has32BitLibs && has64BitLibs) {
7108            // The application has both 64 and 32 bit bundled libraries. We check
7109            // here that the app declares multiArch support, and warn if it doesn't.
7110            //
7111            // We will be lenient here and record both ABIs. The primary will be the
7112            // ABI that's higher on the list, i.e, a device that's configured to prefer
7113            // 64 bit apps will see a 64 bit primary ABI,
7114
7115            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7116                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7117            }
7118
7119            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7120                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7121                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7122            } else {
7123                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7124                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7125            }
7126        } else {
7127            pkg.applicationInfo.primaryCpuAbi = null;
7128            pkg.applicationInfo.secondaryCpuAbi = null;
7129        }
7130    }
7131
7132    private void killApplication(String pkgName, int appId, String reason) {
7133        // Request the ActivityManager to kill the process(only for existing packages)
7134        // so that we do not end up in a confused state while the user is still using the older
7135        // version of the application while the new one gets installed.
7136        IActivityManager am = ActivityManagerNative.getDefault();
7137        if (am != null) {
7138            try {
7139                am.killApplicationWithAppId(pkgName, appId, reason);
7140            } catch (RemoteException e) {
7141            }
7142        }
7143    }
7144
7145    void removePackageLI(PackageSetting ps, boolean chatty) {
7146        if (DEBUG_INSTALL) {
7147            if (chatty)
7148                Log.d(TAG, "Removing package " + ps.name);
7149        }
7150
7151        // writer
7152        synchronized (mPackages) {
7153            mPackages.remove(ps.name);
7154            final PackageParser.Package pkg = ps.pkg;
7155            if (pkg != null) {
7156                cleanPackageDataStructuresLILPw(pkg, chatty);
7157            }
7158        }
7159    }
7160
7161    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7162        if (DEBUG_INSTALL) {
7163            if (chatty)
7164                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7165        }
7166
7167        // writer
7168        synchronized (mPackages) {
7169            mPackages.remove(pkg.applicationInfo.packageName);
7170            cleanPackageDataStructuresLILPw(pkg, chatty);
7171        }
7172    }
7173
7174    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7175        int N = pkg.providers.size();
7176        StringBuilder r = null;
7177        int i;
7178        for (i=0; i<N; i++) {
7179            PackageParser.Provider p = pkg.providers.get(i);
7180            mProviders.removeProvider(p);
7181            if (p.info.authority == null) {
7182
7183                /* There was another ContentProvider with this authority when
7184                 * this app was installed so this authority is null,
7185                 * Ignore it as we don't have to unregister the provider.
7186                 */
7187                continue;
7188            }
7189            String names[] = p.info.authority.split(";");
7190            for (int j = 0; j < names.length; j++) {
7191                if (mProvidersByAuthority.get(names[j]) == p) {
7192                    mProvidersByAuthority.remove(names[j]);
7193                    if (DEBUG_REMOVE) {
7194                        if (chatty)
7195                            Log.d(TAG, "Unregistered content provider: " + names[j]
7196                                    + ", className = " + p.info.name + ", isSyncable = "
7197                                    + p.info.isSyncable);
7198                    }
7199                }
7200            }
7201            if (DEBUG_REMOVE && chatty) {
7202                if (r == null) {
7203                    r = new StringBuilder(256);
7204                } else {
7205                    r.append(' ');
7206                }
7207                r.append(p.info.name);
7208            }
7209        }
7210        if (r != null) {
7211            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7212        }
7213
7214        N = pkg.services.size();
7215        r = null;
7216        for (i=0; i<N; i++) {
7217            PackageParser.Service s = pkg.services.get(i);
7218            mServices.removeService(s);
7219            if (chatty) {
7220                if (r == null) {
7221                    r = new StringBuilder(256);
7222                } else {
7223                    r.append(' ');
7224                }
7225                r.append(s.info.name);
7226            }
7227        }
7228        if (r != null) {
7229            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7230        }
7231
7232        N = pkg.receivers.size();
7233        r = null;
7234        for (i=0; i<N; i++) {
7235            PackageParser.Activity a = pkg.receivers.get(i);
7236            mReceivers.removeActivity(a, "receiver");
7237            if (DEBUG_REMOVE && chatty) {
7238                if (r == null) {
7239                    r = new StringBuilder(256);
7240                } else {
7241                    r.append(' ');
7242                }
7243                r.append(a.info.name);
7244            }
7245        }
7246        if (r != null) {
7247            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7248        }
7249
7250        N = pkg.activities.size();
7251        r = null;
7252        for (i=0; i<N; i++) {
7253            PackageParser.Activity a = pkg.activities.get(i);
7254            mActivities.removeActivity(a, "activity");
7255            if (DEBUG_REMOVE && chatty) {
7256                if (r == null) {
7257                    r = new StringBuilder(256);
7258                } else {
7259                    r.append(' ');
7260                }
7261                r.append(a.info.name);
7262            }
7263        }
7264        if (r != null) {
7265            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7266        }
7267
7268        N = pkg.permissions.size();
7269        r = null;
7270        for (i=0; i<N; i++) {
7271            PackageParser.Permission p = pkg.permissions.get(i);
7272            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7273            if (bp == null) {
7274                bp = mSettings.mPermissionTrees.get(p.info.name);
7275            }
7276            if (bp != null && bp.perm == p) {
7277                bp.perm = null;
7278                if (DEBUG_REMOVE && chatty) {
7279                    if (r == null) {
7280                        r = new StringBuilder(256);
7281                    } else {
7282                        r.append(' ');
7283                    }
7284                    r.append(p.info.name);
7285                }
7286            }
7287            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7288                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7289                if (appOpPerms != null) {
7290                    appOpPerms.remove(pkg.packageName);
7291                }
7292            }
7293        }
7294        if (r != null) {
7295            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7296        }
7297
7298        N = pkg.requestedPermissions.size();
7299        r = null;
7300        for (i=0; i<N; i++) {
7301            String perm = pkg.requestedPermissions.get(i);
7302            BasePermission bp = mSettings.mPermissions.get(perm);
7303            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7304                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7305                if (appOpPerms != null) {
7306                    appOpPerms.remove(pkg.packageName);
7307                    if (appOpPerms.isEmpty()) {
7308                        mAppOpPermissionPackages.remove(perm);
7309                    }
7310                }
7311            }
7312        }
7313        if (r != null) {
7314            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7315        }
7316
7317        N = pkg.instrumentation.size();
7318        r = null;
7319        for (i=0; i<N; i++) {
7320            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7321            mInstrumentation.remove(a.getComponentName());
7322            if (DEBUG_REMOVE && chatty) {
7323                if (r == null) {
7324                    r = new StringBuilder(256);
7325                } else {
7326                    r.append(' ');
7327                }
7328                r.append(a.info.name);
7329            }
7330        }
7331        if (r != null) {
7332            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7333        }
7334
7335        r = null;
7336        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7337            // Only system apps can hold shared libraries.
7338            if (pkg.libraryNames != null) {
7339                for (i=0; i<pkg.libraryNames.size(); i++) {
7340                    String name = pkg.libraryNames.get(i);
7341                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7342                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7343                        mSharedLibraries.remove(name);
7344                        if (DEBUG_REMOVE && chatty) {
7345                            if (r == null) {
7346                                r = new StringBuilder(256);
7347                            } else {
7348                                r.append(' ');
7349                            }
7350                            r.append(name);
7351                        }
7352                    }
7353                }
7354            }
7355        }
7356        if (r != null) {
7357            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7358        }
7359    }
7360
7361    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7362        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7363            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7364                return true;
7365            }
7366        }
7367        return false;
7368    }
7369
7370    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7371    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7372    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7373
7374    private void updatePermissionsLPw(String changingPkg,
7375            PackageParser.Package pkgInfo, int flags) {
7376        // Make sure there are no dangling permission trees.
7377        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7378        while (it.hasNext()) {
7379            final BasePermission bp = it.next();
7380            if (bp.packageSetting == null) {
7381                // We may not yet have parsed the package, so just see if
7382                // we still know about its settings.
7383                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7384            }
7385            if (bp.packageSetting == null) {
7386                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7387                        + " from package " + bp.sourcePackage);
7388                it.remove();
7389            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7390                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7391                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7392                            + " from package " + bp.sourcePackage);
7393                    flags |= UPDATE_PERMISSIONS_ALL;
7394                    it.remove();
7395                }
7396            }
7397        }
7398
7399        // Make sure all dynamic permissions have been assigned to a package,
7400        // and make sure there are no dangling permissions.
7401        it = mSettings.mPermissions.values().iterator();
7402        while (it.hasNext()) {
7403            final BasePermission bp = it.next();
7404            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7405                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7406                        + bp.name + " pkg=" + bp.sourcePackage
7407                        + " info=" + bp.pendingInfo);
7408                if (bp.packageSetting == null && bp.pendingInfo != null) {
7409                    final BasePermission tree = findPermissionTreeLP(bp.name);
7410                    if (tree != null && tree.perm != null) {
7411                        bp.packageSetting = tree.packageSetting;
7412                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7413                                new PermissionInfo(bp.pendingInfo));
7414                        bp.perm.info.packageName = tree.perm.info.packageName;
7415                        bp.perm.info.name = bp.name;
7416                        bp.uid = tree.uid;
7417                    }
7418                }
7419            }
7420            if (bp.packageSetting == null) {
7421                // We may not yet have parsed the package, so just see if
7422                // we still know about its settings.
7423                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7424            }
7425            if (bp.packageSetting == null) {
7426                Slog.w(TAG, "Removing dangling permission: " + bp.name
7427                        + " from package " + bp.sourcePackage);
7428                it.remove();
7429            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7430                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7431                    Slog.i(TAG, "Removing old permission: " + bp.name
7432                            + " from package " + bp.sourcePackage);
7433                    flags |= UPDATE_PERMISSIONS_ALL;
7434                    it.remove();
7435                }
7436            }
7437        }
7438
7439        // Now update the permissions for all packages, in particular
7440        // replace the granted permissions of the system packages.
7441        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7442            for (PackageParser.Package pkg : mPackages.values()) {
7443                if (pkg != pkgInfo) {
7444                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7445                            changingPkg);
7446                }
7447            }
7448        }
7449
7450        if (pkgInfo != null) {
7451            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7452        }
7453    }
7454
7455    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7456            String packageOfInterest) {
7457        // IMPORTANT: There are two types of permissions: install and runtime.
7458        // Install time permissions are granted when the app is installed to
7459        // all device users and users added in the future. Runtime permissions
7460        // are granted at runtime explicitly to specific users. Normal and signature
7461        // protected permissions are install time permissions. Dangerous permissions
7462        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7463        // otherwise they are runtime permissions. This function does not manage
7464        // runtime permissions except for the case an app targeting Lollipop MR1
7465        // being upgraded to target a newer SDK, in which case dangerous permissions
7466        // are transformed from install time to runtime ones.
7467
7468        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7469        if (ps == null) {
7470            return;
7471        }
7472
7473        PermissionsState permissionsState = ps.getPermissionsState();
7474        PermissionsState origPermissions = permissionsState;
7475
7476        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7477
7478        int[] upgradeUserIds = PermissionsState.USERS_NONE;
7479        int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE;
7480
7481        boolean changedInstallPermission = false;
7482
7483        if (replace) {
7484            ps.installPermissionsFixed = false;
7485            if (!ps.isSharedUser()) {
7486                origPermissions = new PermissionsState(permissionsState);
7487                permissionsState.reset();
7488            }
7489        }
7490
7491        permissionsState.setGlobalGids(mGlobalGids);
7492
7493        final int N = pkg.requestedPermissions.size();
7494        for (int i=0; i<N; i++) {
7495            final String name = pkg.requestedPermissions.get(i);
7496            final BasePermission bp = mSettings.mPermissions.get(name);
7497
7498            if (DEBUG_INSTALL) {
7499                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7500            }
7501
7502            if (bp == null || bp.packageSetting == null) {
7503                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7504                    Slog.w(TAG, "Unknown permission " + name
7505                            + " in package " + pkg.packageName);
7506                }
7507                continue;
7508            }
7509
7510            final String perm = bp.name;
7511            boolean allowedSig = false;
7512            int grant = GRANT_DENIED;
7513
7514            // Keep track of app op permissions.
7515            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7516                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7517                if (pkgs == null) {
7518                    pkgs = new ArraySet<>();
7519                    mAppOpPermissionPackages.put(bp.name, pkgs);
7520                }
7521                pkgs.add(pkg.packageName);
7522            }
7523
7524            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7525            switch (level) {
7526                case PermissionInfo.PROTECTION_NORMAL: {
7527                    // For all apps normal permissions are install time ones.
7528                    grant = GRANT_INSTALL;
7529                } break;
7530
7531                case PermissionInfo.PROTECTION_DANGEROUS: {
7532                    if (!RUNTIME_PERMISSIONS_ENABLED
7533                            || pkg.applicationInfo.targetSdkVersion
7534                                    <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7535                        // For legacy apps dangerous permissions are install time ones.
7536                        grant = GRANT_INSTALL;
7537                    } else if (ps.isSystem()) {
7538                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7539                        if (origPermissions.hasInstallPermission(bp.name)) {
7540                            // If a system app had an install permission, then the app was
7541                            // upgraded and we grant the permissions as runtime to all users.
7542                            grant = GRANT_UPGRADE;
7543                            upgradeUserIds = currentUserIds;
7544                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7545                            // If users changed since the last permissions update for a
7546                            // system app, we grant the permission as runtime to the new users.
7547                            grant = GRANT_UPGRADE;
7548                            upgradeUserIds = currentUserIds;
7549                            for (int userId : updatedUserIds) {
7550                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7551                            }
7552                        } else {
7553                            // Otherwise, we grant the permission as runtime if the app
7554                            // already had it, i.e. we preserve runtime permissions.
7555                            grant = GRANT_RUNTIME;
7556                        }
7557                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7558                        // For legacy apps that became modern, install becomes runtime.
7559                        grant = GRANT_UPGRADE;
7560                        upgradeUserIds = currentUserIds;
7561                    } else if (replace) {
7562                        // For upgraded modern apps keep runtime permissions unchanged.
7563                        grant = GRANT_RUNTIME;
7564                    }
7565                } break;
7566
7567                case PermissionInfo.PROTECTION_SIGNATURE: {
7568                    // For all apps signature permissions are install time ones.
7569                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7570                    if (allowedSig) {
7571                        grant = GRANT_INSTALL;
7572                    }
7573                } break;
7574            }
7575
7576            if (DEBUG_INSTALL) {
7577                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7578            }
7579
7580            if (grant != GRANT_DENIED) {
7581                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7582                    // If this is an existing, non-system package, then
7583                    // we can't add any new permissions to it.
7584                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7585                        // Except...  if this is a permission that was added
7586                        // to the platform (note: need to only do this when
7587                        // updating the platform).
7588                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7589                            grant = GRANT_DENIED;
7590                        }
7591                    }
7592                }
7593
7594                switch (grant) {
7595                    case GRANT_INSTALL: {
7596                        // Grant an install permission.
7597                        if (permissionsState.grantInstallPermission(bp) !=
7598                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7599                            changedInstallPermission = true;
7600                        }
7601                    } break;
7602
7603                    case GRANT_RUNTIME: {
7604                        // Grant previously granted runtime permissions.
7605                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7606                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7607                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7608                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7609                                    // If we cannot put the permission as it was, we have to write.
7610                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7611                                            changedRuntimePermissionUserIds, userId);
7612                                }
7613                            }
7614                        }
7615                    } break;
7616
7617                    case GRANT_UPGRADE: {
7618                        // Grant runtime permissions for a previously held install permission.
7619                        permissionsState.revokeInstallPermission(bp);
7620                        for (int userId : upgradeUserIds) {
7621                            if (permissionsState.grantRuntimePermission(bp, userId) !=
7622                                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
7623                                // If we granted the permission, we have to write.
7624                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7625                                        changedRuntimePermissionUserIds, userId);
7626                            }
7627                        }
7628                    } break;
7629
7630                    default: {
7631                        if (packageOfInterest == null
7632                                || packageOfInterest.equals(pkg.packageName)) {
7633                            Slog.w(TAG, "Not granting permission " + perm
7634                                    + " to package " + pkg.packageName
7635                                    + " because it was previously installed without");
7636                        }
7637                    } break;
7638                }
7639            } else {
7640                if (permissionsState.revokeInstallPermission(bp) !=
7641                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7642                    changedInstallPermission = true;
7643                    Slog.i(TAG, "Un-granting permission " + perm
7644                            + " from package " + pkg.packageName
7645                            + " (protectionLevel=" + bp.protectionLevel
7646                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7647                            + ")");
7648                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7649                    // Don't print warning for app op permissions, since it is fine for them
7650                    // not to be granted, there is a UI for the user to decide.
7651                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7652                        Slog.w(TAG, "Not granting permission " + perm
7653                                + " to package " + pkg.packageName
7654                                + " (protectionLevel=" + bp.protectionLevel
7655                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7656                                + ")");
7657                    }
7658                }
7659            }
7660        }
7661
7662        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7663                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7664            // This is the first that we have heard about this package, so the
7665            // permissions we have now selected are fixed until explicitly
7666            // changed.
7667            ps.installPermissionsFixed = true;
7668        }
7669
7670        ps.setPermissionsUpdatedForUserIds(currentUserIds);
7671
7672        // Persist the runtime permissions state for users with changes.
7673        if (RUNTIME_PERMISSIONS_ENABLED) {
7674            for (int userId : changedRuntimePermissionUserIds) {
7675                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
7676            }
7677        }
7678    }
7679
7680    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7681        boolean allowed = false;
7682        final int NP = PackageParser.NEW_PERMISSIONS.length;
7683        for (int ip=0; ip<NP; ip++) {
7684            final PackageParser.NewPermissionInfo npi
7685                    = PackageParser.NEW_PERMISSIONS[ip];
7686            if (npi.name.equals(perm)
7687                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7688                allowed = true;
7689                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7690                        + pkg.packageName);
7691                break;
7692            }
7693        }
7694        return allowed;
7695    }
7696
7697    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7698            BasePermission bp, PermissionsState origPermissions) {
7699        boolean allowed;
7700        allowed = (compareSignatures(
7701                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7702                        == PackageManager.SIGNATURE_MATCH)
7703                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7704                        == PackageManager.SIGNATURE_MATCH);
7705        if (!allowed && (bp.protectionLevel
7706                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7707            if (isSystemApp(pkg)) {
7708                // For updated system applications, a system permission
7709                // is granted only if it had been defined by the original application.
7710                if (pkg.isUpdatedSystemApp()) {
7711                    final PackageSetting sysPs = mSettings
7712                            .getDisabledSystemPkgLPr(pkg.packageName);
7713                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
7714                        // If the original was granted this permission, we take
7715                        // that grant decision as read and propagate it to the
7716                        // update.
7717                        if (sysPs.isPrivileged()) {
7718                            allowed = true;
7719                        }
7720                    } else {
7721                        // The system apk may have been updated with an older
7722                        // version of the one on the data partition, but which
7723                        // granted a new system permission that it didn't have
7724                        // before.  In this case we do want to allow the app to
7725                        // now get the new permission if the ancestral apk is
7726                        // privileged to get it.
7727                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7728                            for (int j=0;
7729                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7730                                if (perm.equals(
7731                                        sysPs.pkg.requestedPermissions.get(j))) {
7732                                    allowed = true;
7733                                    break;
7734                                }
7735                            }
7736                        }
7737                    }
7738                } else {
7739                    allowed = isPrivilegedApp(pkg);
7740                }
7741            }
7742        }
7743        if (!allowed && (bp.protectionLevel
7744                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7745            // For development permissions, a development permission
7746            // is granted only if it was already granted.
7747            allowed = origPermissions.hasInstallPermission(perm);
7748        }
7749        return allowed;
7750    }
7751
7752    final class ActivityIntentResolver
7753            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7754        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7755                boolean defaultOnly, int userId) {
7756            if (!sUserManager.exists(userId)) return null;
7757            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7758            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7759        }
7760
7761        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7762                int userId) {
7763            if (!sUserManager.exists(userId)) return null;
7764            mFlags = flags;
7765            return super.queryIntent(intent, resolvedType,
7766                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7767        }
7768
7769        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7770                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7771            if (!sUserManager.exists(userId)) return null;
7772            if (packageActivities == null) {
7773                return null;
7774            }
7775            mFlags = flags;
7776            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7777            final int N = packageActivities.size();
7778            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7779                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7780
7781            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7782            for (int i = 0; i < N; ++i) {
7783                intentFilters = packageActivities.get(i).intents;
7784                if (intentFilters != null && intentFilters.size() > 0) {
7785                    PackageParser.ActivityIntentInfo[] array =
7786                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7787                    intentFilters.toArray(array);
7788                    listCut.add(array);
7789                }
7790            }
7791            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7792        }
7793
7794        public final void addActivity(PackageParser.Activity a, String type) {
7795            final boolean systemApp = a.info.applicationInfo.isSystemApp();
7796            mActivities.put(a.getComponentName(), a);
7797            if (DEBUG_SHOW_INFO)
7798                Log.v(
7799                TAG, "  " + type + " " +
7800                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7801            if (DEBUG_SHOW_INFO)
7802                Log.v(TAG, "    Class=" + a.info.name);
7803            final int NI = a.intents.size();
7804            for (int j=0; j<NI; j++) {
7805                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7806                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7807                    intent.setPriority(0);
7808                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7809                            + a.className + " with priority > 0, forcing to 0");
7810                }
7811                if (DEBUG_SHOW_INFO) {
7812                    Log.v(TAG, "    IntentFilter:");
7813                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7814                }
7815                if (!intent.debugCheck()) {
7816                    Log.w(TAG, "==> For Activity " + a.info.name);
7817                }
7818                addFilter(intent);
7819            }
7820        }
7821
7822        public final void removeActivity(PackageParser.Activity a, String type) {
7823            mActivities.remove(a.getComponentName());
7824            if (DEBUG_SHOW_INFO) {
7825                Log.v(TAG, "  " + type + " "
7826                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7827                                : a.info.name) + ":");
7828                Log.v(TAG, "    Class=" + a.info.name);
7829            }
7830            final int NI = a.intents.size();
7831            for (int j=0; j<NI; j++) {
7832                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7833                if (DEBUG_SHOW_INFO) {
7834                    Log.v(TAG, "    IntentFilter:");
7835                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7836                }
7837                removeFilter(intent);
7838            }
7839        }
7840
7841        @Override
7842        protected boolean allowFilterResult(
7843                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7844            ActivityInfo filterAi = filter.activity.info;
7845            for (int i=dest.size()-1; i>=0; i--) {
7846                ActivityInfo destAi = dest.get(i).activityInfo;
7847                if (destAi.name == filterAi.name
7848                        && destAi.packageName == filterAi.packageName) {
7849                    return false;
7850                }
7851            }
7852            return true;
7853        }
7854
7855        @Override
7856        protected ActivityIntentInfo[] newArray(int size) {
7857            return new ActivityIntentInfo[size];
7858        }
7859
7860        @Override
7861        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7862            if (!sUserManager.exists(userId)) return true;
7863            PackageParser.Package p = filter.activity.owner;
7864            if (p != null) {
7865                PackageSetting ps = (PackageSetting)p.mExtras;
7866                if (ps != null) {
7867                    // System apps are never considered stopped for purposes of
7868                    // filtering, because there may be no way for the user to
7869                    // actually re-launch them.
7870                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7871                            && ps.getStopped(userId);
7872                }
7873            }
7874            return false;
7875        }
7876
7877        @Override
7878        protected boolean isPackageForFilter(String packageName,
7879                PackageParser.ActivityIntentInfo info) {
7880            return packageName.equals(info.activity.owner.packageName);
7881        }
7882
7883        @Override
7884        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7885                int match, int userId) {
7886            if (!sUserManager.exists(userId)) return null;
7887            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7888                return null;
7889            }
7890            final PackageParser.Activity activity = info.activity;
7891            if (mSafeMode && (activity.info.applicationInfo.flags
7892                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7893                return null;
7894            }
7895            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7896            if (ps == null) {
7897                return null;
7898            }
7899            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7900                    ps.readUserState(userId), userId);
7901            if (ai == null) {
7902                return null;
7903            }
7904            final ResolveInfo res = new ResolveInfo();
7905            res.activityInfo = ai;
7906            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7907                res.filter = info;
7908            }
7909            if (info != null) {
7910                res.handleAllWebDataURI = info.handleAllWebDataURI();
7911            }
7912            res.priority = info.getPriority();
7913            res.preferredOrder = activity.owner.mPreferredOrder;
7914            //System.out.println("Result: " + res.activityInfo.className +
7915            //                   " = " + res.priority);
7916            res.match = match;
7917            res.isDefault = info.hasDefault;
7918            res.labelRes = info.labelRes;
7919            res.nonLocalizedLabel = info.nonLocalizedLabel;
7920            if (userNeedsBadging(userId)) {
7921                res.noResourceId = true;
7922            } else {
7923                res.icon = info.icon;
7924            }
7925            res.system = res.activityInfo.applicationInfo.isSystemApp();
7926            return res;
7927        }
7928
7929        @Override
7930        protected void sortResults(List<ResolveInfo> results) {
7931            Collections.sort(results, mResolvePrioritySorter);
7932        }
7933
7934        @Override
7935        protected void dumpFilter(PrintWriter out, String prefix,
7936                PackageParser.ActivityIntentInfo filter) {
7937            out.print(prefix); out.print(
7938                    Integer.toHexString(System.identityHashCode(filter.activity)));
7939                    out.print(' ');
7940                    filter.activity.printComponentShortName(out);
7941                    out.print(" filter ");
7942                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7943        }
7944
7945        @Override
7946        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
7947            return filter.activity;
7948        }
7949
7950        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7951            PackageParser.Activity activity = (PackageParser.Activity)label;
7952            out.print(prefix); out.print(
7953                    Integer.toHexString(System.identityHashCode(activity)));
7954                    out.print(' ');
7955                    activity.printComponentShortName(out);
7956            if (count > 1) {
7957                out.print(" ("); out.print(count); out.print(" filters)");
7958            }
7959            out.println();
7960        }
7961
7962//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7963//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7964//            final List<ResolveInfo> retList = Lists.newArrayList();
7965//            while (i.hasNext()) {
7966//                final ResolveInfo resolveInfo = i.next();
7967//                if (isEnabledLP(resolveInfo.activityInfo)) {
7968//                    retList.add(resolveInfo);
7969//                }
7970//            }
7971//            return retList;
7972//        }
7973
7974        // Keys are String (activity class name), values are Activity.
7975        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
7976                = new ArrayMap<ComponentName, PackageParser.Activity>();
7977        private int mFlags;
7978    }
7979
7980    private final class ServiceIntentResolver
7981            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7982        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7983                boolean defaultOnly, int userId) {
7984            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7985            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7986        }
7987
7988        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7989                int userId) {
7990            if (!sUserManager.exists(userId)) return null;
7991            mFlags = flags;
7992            return super.queryIntent(intent, resolvedType,
7993                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7994        }
7995
7996        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7997                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7998            if (!sUserManager.exists(userId)) return null;
7999            if (packageServices == null) {
8000                return null;
8001            }
8002            mFlags = flags;
8003            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8004            final int N = packageServices.size();
8005            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8006                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8007
8008            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8009            for (int i = 0; i < N; ++i) {
8010                intentFilters = packageServices.get(i).intents;
8011                if (intentFilters != null && intentFilters.size() > 0) {
8012                    PackageParser.ServiceIntentInfo[] array =
8013                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8014                    intentFilters.toArray(array);
8015                    listCut.add(array);
8016                }
8017            }
8018            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8019        }
8020
8021        public final void addService(PackageParser.Service s) {
8022            mServices.put(s.getComponentName(), s);
8023            if (DEBUG_SHOW_INFO) {
8024                Log.v(TAG, "  "
8025                        + (s.info.nonLocalizedLabel != null
8026                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8027                Log.v(TAG, "    Class=" + s.info.name);
8028            }
8029            final int NI = s.intents.size();
8030            int j;
8031            for (j=0; j<NI; j++) {
8032                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8033                if (DEBUG_SHOW_INFO) {
8034                    Log.v(TAG, "    IntentFilter:");
8035                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8036                }
8037                if (!intent.debugCheck()) {
8038                    Log.w(TAG, "==> For Service " + s.info.name);
8039                }
8040                addFilter(intent);
8041            }
8042        }
8043
8044        public final void removeService(PackageParser.Service s) {
8045            mServices.remove(s.getComponentName());
8046            if (DEBUG_SHOW_INFO) {
8047                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8048                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8049                Log.v(TAG, "    Class=" + s.info.name);
8050            }
8051            final int NI = s.intents.size();
8052            int j;
8053            for (j=0; j<NI; j++) {
8054                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8055                if (DEBUG_SHOW_INFO) {
8056                    Log.v(TAG, "    IntentFilter:");
8057                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8058                }
8059                removeFilter(intent);
8060            }
8061        }
8062
8063        @Override
8064        protected boolean allowFilterResult(
8065                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8066            ServiceInfo filterSi = filter.service.info;
8067            for (int i=dest.size()-1; i>=0; i--) {
8068                ServiceInfo destAi = dest.get(i).serviceInfo;
8069                if (destAi.name == filterSi.name
8070                        && destAi.packageName == filterSi.packageName) {
8071                    return false;
8072                }
8073            }
8074            return true;
8075        }
8076
8077        @Override
8078        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8079            return new PackageParser.ServiceIntentInfo[size];
8080        }
8081
8082        @Override
8083        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8084            if (!sUserManager.exists(userId)) return true;
8085            PackageParser.Package p = filter.service.owner;
8086            if (p != null) {
8087                PackageSetting ps = (PackageSetting)p.mExtras;
8088                if (ps != null) {
8089                    // System apps are never considered stopped for purposes of
8090                    // filtering, because there may be no way for the user to
8091                    // actually re-launch them.
8092                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8093                            && ps.getStopped(userId);
8094                }
8095            }
8096            return false;
8097        }
8098
8099        @Override
8100        protected boolean isPackageForFilter(String packageName,
8101                PackageParser.ServiceIntentInfo info) {
8102            return packageName.equals(info.service.owner.packageName);
8103        }
8104
8105        @Override
8106        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8107                int match, int userId) {
8108            if (!sUserManager.exists(userId)) return null;
8109            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8110            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8111                return null;
8112            }
8113            final PackageParser.Service service = info.service;
8114            if (mSafeMode && (service.info.applicationInfo.flags
8115                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8116                return null;
8117            }
8118            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8119            if (ps == null) {
8120                return null;
8121            }
8122            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8123                    ps.readUserState(userId), userId);
8124            if (si == null) {
8125                return null;
8126            }
8127            final ResolveInfo res = new ResolveInfo();
8128            res.serviceInfo = si;
8129            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8130                res.filter = filter;
8131            }
8132            res.priority = info.getPriority();
8133            res.preferredOrder = service.owner.mPreferredOrder;
8134            res.match = match;
8135            res.isDefault = info.hasDefault;
8136            res.labelRes = info.labelRes;
8137            res.nonLocalizedLabel = info.nonLocalizedLabel;
8138            res.icon = info.icon;
8139            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8140            return res;
8141        }
8142
8143        @Override
8144        protected void sortResults(List<ResolveInfo> results) {
8145            Collections.sort(results, mResolvePrioritySorter);
8146        }
8147
8148        @Override
8149        protected void dumpFilter(PrintWriter out, String prefix,
8150                PackageParser.ServiceIntentInfo filter) {
8151            out.print(prefix); out.print(
8152                    Integer.toHexString(System.identityHashCode(filter.service)));
8153                    out.print(' ');
8154                    filter.service.printComponentShortName(out);
8155                    out.print(" filter ");
8156                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8157        }
8158
8159        @Override
8160        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8161            return filter.service;
8162        }
8163
8164        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8165            PackageParser.Service service = (PackageParser.Service)label;
8166            out.print(prefix); out.print(
8167                    Integer.toHexString(System.identityHashCode(service)));
8168                    out.print(' ');
8169                    service.printComponentShortName(out);
8170            if (count > 1) {
8171                out.print(" ("); out.print(count); out.print(" filters)");
8172            }
8173            out.println();
8174        }
8175
8176//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8177//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8178//            final List<ResolveInfo> retList = Lists.newArrayList();
8179//            while (i.hasNext()) {
8180//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8181//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8182//                    retList.add(resolveInfo);
8183//                }
8184//            }
8185//            return retList;
8186//        }
8187
8188        // Keys are String (activity class name), values are Activity.
8189        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8190                = new ArrayMap<ComponentName, PackageParser.Service>();
8191        private int mFlags;
8192    };
8193
8194    private final class ProviderIntentResolver
8195            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8196        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8197                boolean defaultOnly, int userId) {
8198            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8199            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8200        }
8201
8202        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8203                int userId) {
8204            if (!sUserManager.exists(userId))
8205                return null;
8206            mFlags = flags;
8207            return super.queryIntent(intent, resolvedType,
8208                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8209        }
8210
8211        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8212                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8213            if (!sUserManager.exists(userId))
8214                return null;
8215            if (packageProviders == null) {
8216                return null;
8217            }
8218            mFlags = flags;
8219            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8220            final int N = packageProviders.size();
8221            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8222                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8223
8224            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8225            for (int i = 0; i < N; ++i) {
8226                intentFilters = packageProviders.get(i).intents;
8227                if (intentFilters != null && intentFilters.size() > 0) {
8228                    PackageParser.ProviderIntentInfo[] array =
8229                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8230                    intentFilters.toArray(array);
8231                    listCut.add(array);
8232                }
8233            }
8234            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8235        }
8236
8237        public final void addProvider(PackageParser.Provider p) {
8238            if (mProviders.containsKey(p.getComponentName())) {
8239                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8240                return;
8241            }
8242
8243            mProviders.put(p.getComponentName(), p);
8244            if (DEBUG_SHOW_INFO) {
8245                Log.v(TAG, "  "
8246                        + (p.info.nonLocalizedLabel != null
8247                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8248                Log.v(TAG, "    Class=" + p.info.name);
8249            }
8250            final int NI = p.intents.size();
8251            int j;
8252            for (j = 0; j < NI; j++) {
8253                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8254                if (DEBUG_SHOW_INFO) {
8255                    Log.v(TAG, "    IntentFilter:");
8256                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8257                }
8258                if (!intent.debugCheck()) {
8259                    Log.w(TAG, "==> For Provider " + p.info.name);
8260                }
8261                addFilter(intent);
8262            }
8263        }
8264
8265        public final void removeProvider(PackageParser.Provider p) {
8266            mProviders.remove(p.getComponentName());
8267            if (DEBUG_SHOW_INFO) {
8268                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8269                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8270                Log.v(TAG, "    Class=" + p.info.name);
8271            }
8272            final int NI = p.intents.size();
8273            int j;
8274            for (j = 0; j < NI; j++) {
8275                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8276                if (DEBUG_SHOW_INFO) {
8277                    Log.v(TAG, "    IntentFilter:");
8278                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8279                }
8280                removeFilter(intent);
8281            }
8282        }
8283
8284        @Override
8285        protected boolean allowFilterResult(
8286                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8287            ProviderInfo filterPi = filter.provider.info;
8288            for (int i = dest.size() - 1; i >= 0; i--) {
8289                ProviderInfo destPi = dest.get(i).providerInfo;
8290                if (destPi.name == filterPi.name
8291                        && destPi.packageName == filterPi.packageName) {
8292                    return false;
8293                }
8294            }
8295            return true;
8296        }
8297
8298        @Override
8299        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8300            return new PackageParser.ProviderIntentInfo[size];
8301        }
8302
8303        @Override
8304        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8305            if (!sUserManager.exists(userId))
8306                return true;
8307            PackageParser.Package p = filter.provider.owner;
8308            if (p != null) {
8309                PackageSetting ps = (PackageSetting) p.mExtras;
8310                if (ps != null) {
8311                    // System apps are never considered stopped for purposes of
8312                    // filtering, because there may be no way for the user to
8313                    // actually re-launch them.
8314                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8315                            && ps.getStopped(userId);
8316                }
8317            }
8318            return false;
8319        }
8320
8321        @Override
8322        protected boolean isPackageForFilter(String packageName,
8323                PackageParser.ProviderIntentInfo info) {
8324            return packageName.equals(info.provider.owner.packageName);
8325        }
8326
8327        @Override
8328        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8329                int match, int userId) {
8330            if (!sUserManager.exists(userId))
8331                return null;
8332            final PackageParser.ProviderIntentInfo info = filter;
8333            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8334                return null;
8335            }
8336            final PackageParser.Provider provider = info.provider;
8337            if (mSafeMode && (provider.info.applicationInfo.flags
8338                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8339                return null;
8340            }
8341            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8342            if (ps == null) {
8343                return null;
8344            }
8345            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8346                    ps.readUserState(userId), userId);
8347            if (pi == null) {
8348                return null;
8349            }
8350            final ResolveInfo res = new ResolveInfo();
8351            res.providerInfo = pi;
8352            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8353                res.filter = filter;
8354            }
8355            res.priority = info.getPriority();
8356            res.preferredOrder = provider.owner.mPreferredOrder;
8357            res.match = match;
8358            res.isDefault = info.hasDefault;
8359            res.labelRes = info.labelRes;
8360            res.nonLocalizedLabel = info.nonLocalizedLabel;
8361            res.icon = info.icon;
8362            res.system = res.providerInfo.applicationInfo.isSystemApp();
8363            return res;
8364        }
8365
8366        @Override
8367        protected void sortResults(List<ResolveInfo> results) {
8368            Collections.sort(results, mResolvePrioritySorter);
8369        }
8370
8371        @Override
8372        protected void dumpFilter(PrintWriter out, String prefix,
8373                PackageParser.ProviderIntentInfo filter) {
8374            out.print(prefix);
8375            out.print(
8376                    Integer.toHexString(System.identityHashCode(filter.provider)));
8377            out.print(' ');
8378            filter.provider.printComponentShortName(out);
8379            out.print(" filter ");
8380            out.println(Integer.toHexString(System.identityHashCode(filter)));
8381        }
8382
8383        @Override
8384        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8385            return filter.provider;
8386        }
8387
8388        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8389            PackageParser.Provider provider = (PackageParser.Provider)label;
8390            out.print(prefix); out.print(
8391                    Integer.toHexString(System.identityHashCode(provider)));
8392                    out.print(' ');
8393                    provider.printComponentShortName(out);
8394            if (count > 1) {
8395                out.print(" ("); out.print(count); out.print(" filters)");
8396            }
8397            out.println();
8398        }
8399
8400        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8401                = new ArrayMap<ComponentName, PackageParser.Provider>();
8402        private int mFlags;
8403    };
8404
8405    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8406            new Comparator<ResolveInfo>() {
8407        public int compare(ResolveInfo r1, ResolveInfo r2) {
8408            int v1 = r1.priority;
8409            int v2 = r2.priority;
8410            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8411            if (v1 != v2) {
8412                return (v1 > v2) ? -1 : 1;
8413            }
8414            v1 = r1.preferredOrder;
8415            v2 = r2.preferredOrder;
8416            if (v1 != v2) {
8417                return (v1 > v2) ? -1 : 1;
8418            }
8419            if (r1.isDefault != r2.isDefault) {
8420                return r1.isDefault ? -1 : 1;
8421            }
8422            v1 = r1.match;
8423            v2 = r2.match;
8424            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8425            if (v1 != v2) {
8426                return (v1 > v2) ? -1 : 1;
8427            }
8428            if (r1.system != r2.system) {
8429                return r1.system ? -1 : 1;
8430            }
8431            return 0;
8432        }
8433    };
8434
8435    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8436            new Comparator<ProviderInfo>() {
8437        public int compare(ProviderInfo p1, ProviderInfo p2) {
8438            final int v1 = p1.initOrder;
8439            final int v2 = p2.initOrder;
8440            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8441        }
8442    };
8443
8444    static final void sendPackageBroadcast(String action, String pkg,
8445            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
8446            int[] userIds) {
8447        IActivityManager am = ActivityManagerNative.getDefault();
8448        if (am != null) {
8449            try {
8450                if (userIds == null) {
8451                    userIds = am.getRunningUserIds();
8452                }
8453                for (int id : userIds) {
8454                    final Intent intent = new Intent(action,
8455                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
8456                    if (extras != null) {
8457                        intent.putExtras(extras);
8458                    }
8459                    if (targetPkg != null) {
8460                        intent.setPackage(targetPkg);
8461                    }
8462                    // Modify the UID when posting to other users
8463                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8464                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
8465                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8466                        intent.putExtra(Intent.EXTRA_UID, uid);
8467                    }
8468                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8469                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8470                    if (DEBUG_BROADCASTS) {
8471                        RuntimeException here = new RuntimeException("here");
8472                        here.fillInStackTrace();
8473                        Slog.d(TAG, "Sending to user " + id + ": "
8474                                + intent.toShortString(false, true, false, false)
8475                                + " " + intent.getExtras(), here);
8476                    }
8477                    am.broadcastIntent(null, intent, null, finishedReceiver,
8478                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
8479                            finishedReceiver != null, false, id);
8480                }
8481            } catch (RemoteException ex) {
8482            }
8483        }
8484    }
8485
8486    /**
8487     * Check if the external storage media is available. This is true if there
8488     * is a mounted external storage medium or if the external storage is
8489     * emulated.
8490     */
8491    private boolean isExternalMediaAvailable() {
8492        return mMediaMounted || Environment.isExternalStorageEmulated();
8493    }
8494
8495    @Override
8496    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8497        // writer
8498        synchronized (mPackages) {
8499            if (!isExternalMediaAvailable()) {
8500                // If the external storage is no longer mounted at this point,
8501                // the caller may not have been able to delete all of this
8502                // packages files and can not delete any more.  Bail.
8503                return null;
8504            }
8505            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8506            if (lastPackage != null) {
8507                pkgs.remove(lastPackage);
8508            }
8509            if (pkgs.size() > 0) {
8510                return pkgs.get(0);
8511            }
8512        }
8513        return null;
8514    }
8515
8516    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8517        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8518                userId, andCode ? 1 : 0, packageName);
8519        if (mSystemReady) {
8520            msg.sendToTarget();
8521        } else {
8522            if (mPostSystemReadyMessages == null) {
8523                mPostSystemReadyMessages = new ArrayList<>();
8524            }
8525            mPostSystemReadyMessages.add(msg);
8526        }
8527    }
8528
8529    void startCleaningPackages() {
8530        // reader
8531        synchronized (mPackages) {
8532            if (!isExternalMediaAvailable()) {
8533                return;
8534            }
8535            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8536                return;
8537            }
8538        }
8539        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8540        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8541        IActivityManager am = ActivityManagerNative.getDefault();
8542        if (am != null) {
8543            try {
8544                am.startService(null, intent, null, UserHandle.USER_OWNER);
8545            } catch (RemoteException e) {
8546            }
8547        }
8548    }
8549
8550    @Override
8551    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8552            int installFlags, String installerPackageName, VerificationParams verificationParams,
8553            String packageAbiOverride) {
8554        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8555                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8556    }
8557
8558    @Override
8559    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8560            int installFlags, String installerPackageName, VerificationParams verificationParams,
8561            String packageAbiOverride, int userId) {
8562        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8563
8564        final int callingUid = Binder.getCallingUid();
8565        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8566
8567        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8568            try {
8569                if (observer != null) {
8570                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8571                }
8572            } catch (RemoteException re) {
8573            }
8574            return;
8575        }
8576
8577        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8578            installFlags |= PackageManager.INSTALL_FROM_ADB;
8579
8580        } else {
8581            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8582            // about installerPackageName.
8583
8584            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8585            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8586        }
8587
8588        UserHandle user;
8589        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8590            user = UserHandle.ALL;
8591        } else {
8592            user = new UserHandle(userId);
8593        }
8594
8595        // Only system components can circumvent runtime permissions when installing.
8596        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
8597                && mContext.checkCallingOrSelfPermission(Manifest.permission
8598                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
8599            throw new SecurityException("You need the "
8600                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
8601                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
8602        }
8603
8604        verificationParams.setInstallerUid(callingUid);
8605
8606        final File originFile = new File(originPath);
8607        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8608
8609        final Message msg = mHandler.obtainMessage(INIT_COPY);
8610        msg.obj = new InstallParams(origin, observer, installFlags,
8611                installerPackageName, null, verificationParams, user, packageAbiOverride);
8612        mHandler.sendMessage(msg);
8613    }
8614
8615    void installStage(String packageName, File stagedDir, String stagedCid,
8616            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8617            String installerPackageName, int installerUid, UserHandle user) {
8618        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8619                params.referrerUri, installerUid, null);
8620
8621        final OriginInfo origin;
8622        if (stagedDir != null) {
8623            origin = OriginInfo.fromStagedFile(stagedDir);
8624        } else {
8625            origin = OriginInfo.fromStagedContainer(stagedCid);
8626        }
8627
8628        final Message msg = mHandler.obtainMessage(INIT_COPY);
8629        msg.obj = new InstallParams(origin, observer, params.installFlags,
8630                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8631        mHandler.sendMessage(msg);
8632    }
8633
8634    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8635        Bundle extras = new Bundle(1);
8636        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8637
8638        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8639                packageName, extras, null, null, new int[] {userId});
8640        try {
8641            IActivityManager am = ActivityManagerNative.getDefault();
8642            final boolean isSystem =
8643                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8644            if (isSystem && am.isUserRunning(userId, false)) {
8645                // The just-installed/enabled app is bundled on the system, so presumed
8646                // to be able to run automatically without needing an explicit launch.
8647                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8648                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8649                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8650                        .setPackage(packageName);
8651                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8652                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8653            }
8654        } catch (RemoteException e) {
8655            // shouldn't happen
8656            Slog.w(TAG, "Unable to bootstrap installed package", e);
8657        }
8658    }
8659
8660    @Override
8661    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8662            int userId) {
8663        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8664        PackageSetting pkgSetting;
8665        final int uid = Binder.getCallingUid();
8666        enforceCrossUserPermission(uid, userId, true, true,
8667                "setApplicationHiddenSetting for user " + userId);
8668
8669        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8670            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8671            return false;
8672        }
8673
8674        long callingId = Binder.clearCallingIdentity();
8675        try {
8676            boolean sendAdded = false;
8677            boolean sendRemoved = false;
8678            // writer
8679            synchronized (mPackages) {
8680                pkgSetting = mSettings.mPackages.get(packageName);
8681                if (pkgSetting == null) {
8682                    return false;
8683                }
8684                if (pkgSetting.getHidden(userId) != hidden) {
8685                    pkgSetting.setHidden(hidden, userId);
8686                    mSettings.writePackageRestrictionsLPr(userId);
8687                    if (hidden) {
8688                        sendRemoved = true;
8689                    } else {
8690                        sendAdded = true;
8691                    }
8692                }
8693            }
8694            if (sendAdded) {
8695                sendPackageAddedForUser(packageName, pkgSetting, userId);
8696                return true;
8697            }
8698            if (sendRemoved) {
8699                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8700                        "hiding pkg");
8701                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8702            }
8703        } finally {
8704            Binder.restoreCallingIdentity(callingId);
8705        }
8706        return false;
8707    }
8708
8709    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8710            int userId) {
8711        final PackageRemovedInfo info = new PackageRemovedInfo();
8712        info.removedPackage = packageName;
8713        info.removedUsers = new int[] {userId};
8714        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8715        info.sendBroadcast(false, false, false);
8716    }
8717
8718    /**
8719     * Returns true if application is not found or there was an error. Otherwise it returns
8720     * the hidden state of the package for the given user.
8721     */
8722    @Override
8723    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8724        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8725        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8726                false, "getApplicationHidden for user " + userId);
8727        PackageSetting pkgSetting;
8728        long callingId = Binder.clearCallingIdentity();
8729        try {
8730            // writer
8731            synchronized (mPackages) {
8732                pkgSetting = mSettings.mPackages.get(packageName);
8733                if (pkgSetting == null) {
8734                    return true;
8735                }
8736                return pkgSetting.getHidden(userId);
8737            }
8738        } finally {
8739            Binder.restoreCallingIdentity(callingId);
8740        }
8741    }
8742
8743    /**
8744     * @hide
8745     */
8746    @Override
8747    public int installExistingPackageAsUser(String packageName, int userId) {
8748        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8749                null);
8750        PackageSetting pkgSetting;
8751        final int uid = Binder.getCallingUid();
8752        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8753                + userId);
8754        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8755            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8756        }
8757
8758        long callingId = Binder.clearCallingIdentity();
8759        try {
8760            boolean sendAdded = false;
8761
8762            // writer
8763            synchronized (mPackages) {
8764                pkgSetting = mSettings.mPackages.get(packageName);
8765                if (pkgSetting == null) {
8766                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8767                }
8768                if (!pkgSetting.getInstalled(userId)) {
8769                    pkgSetting.setInstalled(true, userId);
8770                    pkgSetting.setHidden(false, userId);
8771                    mSettings.writePackageRestrictionsLPr(userId);
8772                    sendAdded = true;
8773                }
8774            }
8775
8776            if (sendAdded) {
8777                sendPackageAddedForUser(packageName, pkgSetting, userId);
8778            }
8779        } finally {
8780            Binder.restoreCallingIdentity(callingId);
8781        }
8782
8783        return PackageManager.INSTALL_SUCCEEDED;
8784    }
8785
8786    boolean isUserRestricted(int userId, String restrictionKey) {
8787        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8788        if (restrictions.getBoolean(restrictionKey, false)) {
8789            Log.w(TAG, "User is restricted: " + restrictionKey);
8790            return true;
8791        }
8792        return false;
8793    }
8794
8795    @Override
8796    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8797        mContext.enforceCallingOrSelfPermission(
8798                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8799                "Only package verification agents can verify applications");
8800
8801        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8802        final PackageVerificationResponse response = new PackageVerificationResponse(
8803                verificationCode, Binder.getCallingUid());
8804        msg.arg1 = id;
8805        msg.obj = response;
8806        mHandler.sendMessage(msg);
8807    }
8808
8809    @Override
8810    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8811            long millisecondsToDelay) {
8812        mContext.enforceCallingOrSelfPermission(
8813                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8814                "Only package verification agents can extend verification timeouts");
8815
8816        final PackageVerificationState state = mPendingVerification.get(id);
8817        final PackageVerificationResponse response = new PackageVerificationResponse(
8818                verificationCodeAtTimeout, Binder.getCallingUid());
8819
8820        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8821            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8822        }
8823        if (millisecondsToDelay < 0) {
8824            millisecondsToDelay = 0;
8825        }
8826        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8827                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8828            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8829        }
8830
8831        if ((state != null) && !state.timeoutExtended()) {
8832            state.extendTimeout();
8833
8834            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8835            msg.arg1 = id;
8836            msg.obj = response;
8837            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8838        }
8839    }
8840
8841    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8842            int verificationCode, UserHandle user) {
8843        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8844        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8845        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8846        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8847        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8848
8849        mContext.sendBroadcastAsUser(intent, user,
8850                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8851    }
8852
8853    private ComponentName matchComponentForVerifier(String packageName,
8854            List<ResolveInfo> receivers) {
8855        ActivityInfo targetReceiver = null;
8856
8857        final int NR = receivers.size();
8858        for (int i = 0; i < NR; i++) {
8859            final ResolveInfo info = receivers.get(i);
8860            if (info.activityInfo == null) {
8861                continue;
8862            }
8863
8864            if (packageName.equals(info.activityInfo.packageName)) {
8865                targetReceiver = info.activityInfo;
8866                break;
8867            }
8868        }
8869
8870        if (targetReceiver == null) {
8871            return null;
8872        }
8873
8874        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8875    }
8876
8877    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8878            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8879        if (pkgInfo.verifiers.length == 0) {
8880            return null;
8881        }
8882
8883        final int N = pkgInfo.verifiers.length;
8884        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8885        for (int i = 0; i < N; i++) {
8886            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8887
8888            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8889                    receivers);
8890            if (comp == null) {
8891                continue;
8892            }
8893
8894            final int verifierUid = getUidForVerifier(verifierInfo);
8895            if (verifierUid == -1) {
8896                continue;
8897            }
8898
8899            if (DEBUG_VERIFY) {
8900                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8901                        + " with the correct signature");
8902            }
8903            sufficientVerifiers.add(comp);
8904            verificationState.addSufficientVerifier(verifierUid);
8905        }
8906
8907        return sufficientVerifiers;
8908    }
8909
8910    private int getUidForVerifier(VerifierInfo verifierInfo) {
8911        synchronized (mPackages) {
8912            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8913            if (pkg == null) {
8914                return -1;
8915            } else if (pkg.mSignatures.length != 1) {
8916                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8917                        + " has more than one signature; ignoring");
8918                return -1;
8919            }
8920
8921            /*
8922             * If the public key of the package's signature does not match
8923             * our expected public key, then this is a different package and
8924             * we should skip.
8925             */
8926
8927            final byte[] expectedPublicKey;
8928            try {
8929                final Signature verifierSig = pkg.mSignatures[0];
8930                final PublicKey publicKey = verifierSig.getPublicKey();
8931                expectedPublicKey = publicKey.getEncoded();
8932            } catch (CertificateException e) {
8933                return -1;
8934            }
8935
8936            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8937
8938            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8939                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8940                        + " does not have the expected public key; ignoring");
8941                return -1;
8942            }
8943
8944            return pkg.applicationInfo.uid;
8945        }
8946    }
8947
8948    @Override
8949    public void finishPackageInstall(int token) {
8950        enforceSystemOrRoot("Only the system is allowed to finish installs");
8951
8952        if (DEBUG_INSTALL) {
8953            Slog.v(TAG, "BM finishing package install for " + token);
8954        }
8955
8956        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8957        mHandler.sendMessage(msg);
8958    }
8959
8960    /**
8961     * Get the verification agent timeout.
8962     *
8963     * @return verification timeout in milliseconds
8964     */
8965    private long getVerificationTimeout() {
8966        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8967                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8968                DEFAULT_VERIFICATION_TIMEOUT);
8969    }
8970
8971    /**
8972     * Get the default verification agent response code.
8973     *
8974     * @return default verification response code
8975     */
8976    private int getDefaultVerificationResponse() {
8977        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8978                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8979                DEFAULT_VERIFICATION_RESPONSE);
8980    }
8981
8982    /**
8983     * Check whether or not package verification has been enabled.
8984     *
8985     * @return true if verification should be performed
8986     */
8987    private boolean isVerificationEnabled(int userId, int installFlags) {
8988        if (!DEFAULT_VERIFY_ENABLE) {
8989            return false;
8990        }
8991
8992        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8993
8994        // Check if installing from ADB
8995        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8996            // Do not run verification in a test harness environment
8997            if (ActivityManager.isRunningInTestHarness()) {
8998                return false;
8999            }
9000            if (ensureVerifyAppsEnabled) {
9001                return true;
9002            }
9003            // Check if the developer does not want package verification for ADB installs
9004            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9005                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9006                return false;
9007            }
9008        }
9009
9010        if (ensureVerifyAppsEnabled) {
9011            return true;
9012        }
9013
9014        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9015                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9016    }
9017
9018    @Override
9019    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9020            throws RemoteException {
9021        mContext.enforceCallingOrSelfPermission(
9022                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9023                "Only intentfilter verification agents can verify applications");
9024
9025        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9026        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9027                Binder.getCallingUid(), verificationCode, failedDomains);
9028        msg.arg1 = id;
9029        msg.obj = response;
9030        mHandler.sendMessage(msg);
9031    }
9032
9033    @Override
9034    public int getIntentVerificationStatus(String packageName, int userId) {
9035        synchronized (mPackages) {
9036            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9037        }
9038    }
9039
9040    @Override
9041    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9042        boolean result = false;
9043        synchronized (mPackages) {
9044            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9045        }
9046        scheduleWritePackageRestrictionsLocked(userId);
9047        return result;
9048    }
9049
9050    @Override
9051    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9052        synchronized (mPackages) {
9053            return mSettings.getIntentFilterVerificationsLPr(packageName);
9054        }
9055    }
9056
9057    @Override
9058    public List<IntentFilter> getAllIntentFilters(String packageName) {
9059        if (TextUtils.isEmpty(packageName)) {
9060            return Collections.<IntentFilter>emptyList();
9061        }
9062        synchronized (mPackages) {
9063            PackageParser.Package pkg = mPackages.get(packageName);
9064            if (pkg == null || pkg.activities == null) {
9065                return Collections.<IntentFilter>emptyList();
9066            }
9067            final int count = pkg.activities.size();
9068            ArrayList<IntentFilter> result = new ArrayList<>();
9069            for (int n=0; n<count; n++) {
9070                PackageParser.Activity activity = pkg.activities.get(n);
9071                if (activity.intents != null || activity.intents.size() > 0) {
9072                    result.addAll(activity.intents);
9073                }
9074            }
9075            return result;
9076        }
9077    }
9078
9079    @Override
9080    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9081        synchronized (mPackages) {
9082            return mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9083        }
9084    }
9085
9086    @Override
9087    public String getDefaultBrowserPackageName(int userId) {
9088        synchronized (mPackages) {
9089            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9090        }
9091    }
9092
9093    /**
9094     * Get the "allow unknown sources" setting.
9095     *
9096     * @return the current "allow unknown sources" setting
9097     */
9098    private int getUnknownSourcesSettings() {
9099        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9100                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9101                -1);
9102    }
9103
9104    @Override
9105    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9106        final int uid = Binder.getCallingUid();
9107        // writer
9108        synchronized (mPackages) {
9109            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9110            if (targetPackageSetting == null) {
9111                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9112            }
9113
9114            PackageSetting installerPackageSetting;
9115            if (installerPackageName != null) {
9116                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9117                if (installerPackageSetting == null) {
9118                    throw new IllegalArgumentException("Unknown installer package: "
9119                            + installerPackageName);
9120                }
9121            } else {
9122                installerPackageSetting = null;
9123            }
9124
9125            Signature[] callerSignature;
9126            Object obj = mSettings.getUserIdLPr(uid);
9127            if (obj != null) {
9128                if (obj instanceof SharedUserSetting) {
9129                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9130                } else if (obj instanceof PackageSetting) {
9131                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9132                } else {
9133                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9134                }
9135            } else {
9136                throw new SecurityException("Unknown calling uid " + uid);
9137            }
9138
9139            // Verify: can't set installerPackageName to a package that is
9140            // not signed with the same cert as the caller.
9141            if (installerPackageSetting != null) {
9142                if (compareSignatures(callerSignature,
9143                        installerPackageSetting.signatures.mSignatures)
9144                        != PackageManager.SIGNATURE_MATCH) {
9145                    throw new SecurityException(
9146                            "Caller does not have same cert as new installer package "
9147                            + installerPackageName);
9148                }
9149            }
9150
9151            // Verify: if target already has an installer package, it must
9152            // be signed with the same cert as the caller.
9153            if (targetPackageSetting.installerPackageName != null) {
9154                PackageSetting setting = mSettings.mPackages.get(
9155                        targetPackageSetting.installerPackageName);
9156                // If the currently set package isn't valid, then it's always
9157                // okay to change it.
9158                if (setting != null) {
9159                    if (compareSignatures(callerSignature,
9160                            setting.signatures.mSignatures)
9161                            != PackageManager.SIGNATURE_MATCH) {
9162                        throw new SecurityException(
9163                                "Caller does not have same cert as old installer package "
9164                                + targetPackageSetting.installerPackageName);
9165                    }
9166                }
9167            }
9168
9169            // Okay!
9170            targetPackageSetting.installerPackageName = installerPackageName;
9171            scheduleWriteSettingsLocked();
9172        }
9173    }
9174
9175    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9176        // Queue up an async operation since the package installation may take a little while.
9177        mHandler.post(new Runnable() {
9178            public void run() {
9179                mHandler.removeCallbacks(this);
9180                 // Result object to be returned
9181                PackageInstalledInfo res = new PackageInstalledInfo();
9182                res.returnCode = currentStatus;
9183                res.uid = -1;
9184                res.pkg = null;
9185                res.removedInfo = new PackageRemovedInfo();
9186                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9187                    args.doPreInstall(res.returnCode);
9188                    synchronized (mInstallLock) {
9189                        installPackageLI(args, res);
9190                    }
9191                    args.doPostInstall(res.returnCode, res.uid);
9192                }
9193
9194                // A restore should be performed at this point if (a) the install
9195                // succeeded, (b) the operation is not an update, and (c) the new
9196                // package has not opted out of backup participation.
9197                final boolean update = res.removedInfo.removedPackage != null;
9198                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9199                boolean doRestore = !update
9200                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9201
9202                // Set up the post-install work request bookkeeping.  This will be used
9203                // and cleaned up by the post-install event handling regardless of whether
9204                // there's a restore pass performed.  Token values are >= 1.
9205                int token;
9206                if (mNextInstallToken < 0) mNextInstallToken = 1;
9207                token = mNextInstallToken++;
9208
9209                PostInstallData data = new PostInstallData(args, res);
9210                mRunningInstalls.put(token, data);
9211                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9212
9213                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9214                    // Pass responsibility to the Backup Manager.  It will perform a
9215                    // restore if appropriate, then pass responsibility back to the
9216                    // Package Manager to run the post-install observer callbacks
9217                    // and broadcasts.
9218                    IBackupManager bm = IBackupManager.Stub.asInterface(
9219                            ServiceManager.getService(Context.BACKUP_SERVICE));
9220                    if (bm != null) {
9221                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9222                                + " to BM for possible restore");
9223                        try {
9224                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9225                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9226                            } else {
9227                                doRestore = false;
9228                            }
9229                        } catch (RemoteException e) {
9230                            // can't happen; the backup manager is local
9231                        } catch (Exception e) {
9232                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9233                            doRestore = false;
9234                        }
9235                    } else {
9236                        Slog.e(TAG, "Backup Manager not found!");
9237                        doRestore = false;
9238                    }
9239                }
9240
9241                if (!doRestore) {
9242                    // No restore possible, or the Backup Manager was mysteriously not
9243                    // available -- just fire the post-install work request directly.
9244                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9245                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9246                    mHandler.sendMessage(msg);
9247                }
9248            }
9249        });
9250    }
9251
9252    private abstract class HandlerParams {
9253        private static final int MAX_RETRIES = 4;
9254
9255        /**
9256         * Number of times startCopy() has been attempted and had a non-fatal
9257         * error.
9258         */
9259        private int mRetries = 0;
9260
9261        /** User handle for the user requesting the information or installation. */
9262        private final UserHandle mUser;
9263
9264        HandlerParams(UserHandle user) {
9265            mUser = user;
9266        }
9267
9268        UserHandle getUser() {
9269            return mUser;
9270        }
9271
9272        final boolean startCopy() {
9273            boolean res;
9274            try {
9275                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9276
9277                if (++mRetries > MAX_RETRIES) {
9278                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9279                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9280                    handleServiceError();
9281                    return false;
9282                } else {
9283                    handleStartCopy();
9284                    res = true;
9285                }
9286            } catch (RemoteException e) {
9287                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9288                mHandler.sendEmptyMessage(MCS_RECONNECT);
9289                res = false;
9290            }
9291            handleReturnCode();
9292            return res;
9293        }
9294
9295        final void serviceError() {
9296            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9297            handleServiceError();
9298            handleReturnCode();
9299        }
9300
9301        abstract void handleStartCopy() throws RemoteException;
9302        abstract void handleServiceError();
9303        abstract void handleReturnCode();
9304    }
9305
9306    class MeasureParams extends HandlerParams {
9307        private final PackageStats mStats;
9308        private boolean mSuccess;
9309
9310        private final IPackageStatsObserver mObserver;
9311
9312        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9313            super(new UserHandle(stats.userHandle));
9314            mObserver = observer;
9315            mStats = stats;
9316        }
9317
9318        @Override
9319        public String toString() {
9320            return "MeasureParams{"
9321                + Integer.toHexString(System.identityHashCode(this))
9322                + " " + mStats.packageName + "}";
9323        }
9324
9325        @Override
9326        void handleStartCopy() throws RemoteException {
9327            synchronized (mInstallLock) {
9328                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9329            }
9330
9331            if (mSuccess) {
9332                final boolean mounted;
9333                if (Environment.isExternalStorageEmulated()) {
9334                    mounted = true;
9335                } else {
9336                    final String status = Environment.getExternalStorageState();
9337                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9338                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9339                }
9340
9341                if (mounted) {
9342                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9343
9344                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9345                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9346
9347                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9348                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9349
9350                    // Always subtract cache size, since it's a subdirectory
9351                    mStats.externalDataSize -= mStats.externalCacheSize;
9352
9353                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9354                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9355
9356                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9357                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9358                }
9359            }
9360        }
9361
9362        @Override
9363        void handleReturnCode() {
9364            if (mObserver != null) {
9365                try {
9366                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9367                } catch (RemoteException e) {
9368                    Slog.i(TAG, "Observer no longer exists.");
9369                }
9370            }
9371        }
9372
9373        @Override
9374        void handleServiceError() {
9375            Slog.e(TAG, "Could not measure application " + mStats.packageName
9376                            + " external storage");
9377        }
9378    }
9379
9380    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9381            throws RemoteException {
9382        long result = 0;
9383        for (File path : paths) {
9384            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9385        }
9386        return result;
9387    }
9388
9389    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9390        for (File path : paths) {
9391            try {
9392                mcs.clearDirectory(path.getAbsolutePath());
9393            } catch (RemoteException e) {
9394            }
9395        }
9396    }
9397
9398    static class OriginInfo {
9399        /**
9400         * Location where install is coming from, before it has been
9401         * copied/renamed into place. This could be a single monolithic APK
9402         * file, or a cluster directory. This location may be untrusted.
9403         */
9404        final File file;
9405        final String cid;
9406
9407        /**
9408         * Flag indicating that {@link #file} or {@link #cid} has already been
9409         * staged, meaning downstream users don't need to defensively copy the
9410         * contents.
9411         */
9412        final boolean staged;
9413
9414        /**
9415         * Flag indicating that {@link #file} or {@link #cid} is an already
9416         * installed app that is being moved.
9417         */
9418        final boolean existing;
9419
9420        final String resolvedPath;
9421        final File resolvedFile;
9422
9423        static OriginInfo fromNothing() {
9424            return new OriginInfo(null, null, false, false);
9425        }
9426
9427        static OriginInfo fromUntrustedFile(File file) {
9428            return new OriginInfo(file, null, false, false);
9429        }
9430
9431        static OriginInfo fromExistingFile(File file) {
9432            return new OriginInfo(file, null, false, true);
9433        }
9434
9435        static OriginInfo fromStagedFile(File file) {
9436            return new OriginInfo(file, null, true, false);
9437        }
9438
9439        static OriginInfo fromStagedContainer(String cid) {
9440            return new OriginInfo(null, cid, true, false);
9441        }
9442
9443        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9444            this.file = file;
9445            this.cid = cid;
9446            this.staged = staged;
9447            this.existing = existing;
9448
9449            if (cid != null) {
9450                resolvedPath = PackageHelper.getSdDir(cid);
9451                resolvedFile = new File(resolvedPath);
9452            } else if (file != null) {
9453                resolvedPath = file.getAbsolutePath();
9454                resolvedFile = file;
9455            } else {
9456                resolvedPath = null;
9457                resolvedFile = null;
9458            }
9459        }
9460    }
9461
9462    class InstallParams extends HandlerParams {
9463        final OriginInfo origin;
9464        final IPackageInstallObserver2 observer;
9465        int installFlags;
9466        final String installerPackageName;
9467        final String volumeUuid;
9468        final VerificationParams verificationParams;
9469        private InstallArgs mArgs;
9470        private int mRet;
9471        final String packageAbiOverride;
9472
9473        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9474                String installerPackageName, String volumeUuid,
9475                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9476            super(user);
9477            this.origin = origin;
9478            this.observer = observer;
9479            this.installFlags = installFlags;
9480            this.installerPackageName = installerPackageName;
9481            this.volumeUuid = volumeUuid;
9482            this.verificationParams = verificationParams;
9483            this.packageAbiOverride = packageAbiOverride;
9484        }
9485
9486        @Override
9487        public String toString() {
9488            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9489                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9490        }
9491
9492        public ManifestDigest getManifestDigest() {
9493            if (verificationParams == null) {
9494                return null;
9495            }
9496            return verificationParams.getManifestDigest();
9497        }
9498
9499        private int installLocationPolicy(PackageInfoLite pkgLite) {
9500            String packageName = pkgLite.packageName;
9501            int installLocation = pkgLite.installLocation;
9502            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9503            // reader
9504            synchronized (mPackages) {
9505                PackageParser.Package pkg = mPackages.get(packageName);
9506                if (pkg != null) {
9507                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9508                        // Check for downgrading.
9509                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9510                            try {
9511                                checkDowngrade(pkg, pkgLite);
9512                            } catch (PackageManagerException e) {
9513                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9514                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9515                            }
9516                        }
9517                        // Check for updated system application.
9518                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9519                            if (onSd) {
9520                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9521                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9522                            }
9523                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9524                        } else {
9525                            if (onSd) {
9526                                // Install flag overrides everything.
9527                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9528                            }
9529                            // If current upgrade specifies particular preference
9530                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9531                                // Application explicitly specified internal.
9532                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9533                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9534                                // App explictly prefers external. Let policy decide
9535                            } else {
9536                                // Prefer previous location
9537                                if (isExternal(pkg)) {
9538                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9539                                }
9540                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9541                            }
9542                        }
9543                    } else {
9544                        // Invalid install. Return error code
9545                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9546                    }
9547                }
9548            }
9549            // All the special cases have been taken care of.
9550            // Return result based on recommended install location.
9551            if (onSd) {
9552                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9553            }
9554            return pkgLite.recommendedInstallLocation;
9555        }
9556
9557        /*
9558         * Invoke remote method to get package information and install
9559         * location values. Override install location based on default
9560         * policy if needed and then create install arguments based
9561         * on the install location.
9562         */
9563        public void handleStartCopy() throws RemoteException {
9564            int ret = PackageManager.INSTALL_SUCCEEDED;
9565
9566            // If we're already staged, we've firmly committed to an install location
9567            if (origin.staged) {
9568                if (origin.file != null) {
9569                    installFlags |= PackageManager.INSTALL_INTERNAL;
9570                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9571                } else if (origin.cid != null) {
9572                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9573                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9574                } else {
9575                    throw new IllegalStateException("Invalid stage location");
9576                }
9577            }
9578
9579            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9580            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9581
9582            PackageInfoLite pkgLite = null;
9583
9584            if (onInt && onSd) {
9585                // Check if both bits are set.
9586                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9587                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9588            } else {
9589                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9590                        packageAbiOverride);
9591
9592                /*
9593                 * If we have too little free space, try to free cache
9594                 * before giving up.
9595                 */
9596                if (!origin.staged && pkgLite.recommendedInstallLocation
9597                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9598                    // TODO: focus freeing disk space on the target device
9599                    final StorageManager storage = StorageManager.from(mContext);
9600                    final long lowThreshold = storage.getStorageLowBytes(
9601                            Environment.getDataDirectory());
9602
9603                    final long sizeBytes = mContainerService.calculateInstalledSize(
9604                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9605
9606                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
9607                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9608                                installFlags, packageAbiOverride);
9609                    }
9610
9611                    /*
9612                     * The cache free must have deleted the file we
9613                     * downloaded to install.
9614                     *
9615                     * TODO: fix the "freeCache" call to not delete
9616                     *       the file we care about.
9617                     */
9618                    if (pkgLite.recommendedInstallLocation
9619                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9620                        pkgLite.recommendedInstallLocation
9621                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9622                    }
9623                }
9624            }
9625
9626            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9627                int loc = pkgLite.recommendedInstallLocation;
9628                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9629                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9630                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9631                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9632                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9633                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9634                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9635                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9636                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9637                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9638                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9639                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9640                } else {
9641                    // Override with defaults if needed.
9642                    loc = installLocationPolicy(pkgLite);
9643                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9644                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9645                    } else if (!onSd && !onInt) {
9646                        // Override install location with flags
9647                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9648                            // Set the flag to install on external media.
9649                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9650                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9651                        } else {
9652                            // Make sure the flag for installing on external
9653                            // media is unset
9654                            installFlags |= PackageManager.INSTALL_INTERNAL;
9655                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9656                        }
9657                    }
9658                }
9659            }
9660
9661            final InstallArgs args = createInstallArgs(this);
9662            mArgs = args;
9663
9664            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9665                 /*
9666                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9667                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9668                 */
9669                int userIdentifier = getUser().getIdentifier();
9670                if (userIdentifier == UserHandle.USER_ALL
9671                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9672                    userIdentifier = UserHandle.USER_OWNER;
9673                }
9674
9675                /*
9676                 * Determine if we have any installed package verifiers. If we
9677                 * do, then we'll defer to them to verify the packages.
9678                 */
9679                final int requiredUid = mRequiredVerifierPackage == null ? -1
9680                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9681                if (!origin.existing && requiredUid != -1
9682                        && isVerificationEnabled(userIdentifier, installFlags)) {
9683                    final Intent verification = new Intent(
9684                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9685                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9686                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9687                            PACKAGE_MIME_TYPE);
9688                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9689
9690                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9691                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9692                            0 /* TODO: Which userId? */);
9693
9694                    if (DEBUG_VERIFY) {
9695                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9696                                + verification.toString() + " with " + pkgLite.verifiers.length
9697                                + " optional verifiers");
9698                    }
9699
9700                    final int verificationId = mPendingVerificationToken++;
9701
9702                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9703
9704                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9705                            installerPackageName);
9706
9707                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9708                            installFlags);
9709
9710                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9711                            pkgLite.packageName);
9712
9713                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9714                            pkgLite.versionCode);
9715
9716                    if (verificationParams != null) {
9717                        if (verificationParams.getVerificationURI() != null) {
9718                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9719                                 verificationParams.getVerificationURI());
9720                        }
9721                        if (verificationParams.getOriginatingURI() != null) {
9722                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9723                                  verificationParams.getOriginatingURI());
9724                        }
9725                        if (verificationParams.getReferrer() != null) {
9726                            verification.putExtra(Intent.EXTRA_REFERRER,
9727                                  verificationParams.getReferrer());
9728                        }
9729                        if (verificationParams.getOriginatingUid() >= 0) {
9730                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9731                                  verificationParams.getOriginatingUid());
9732                        }
9733                        if (verificationParams.getInstallerUid() >= 0) {
9734                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9735                                  verificationParams.getInstallerUid());
9736                        }
9737                    }
9738
9739                    final PackageVerificationState verificationState = new PackageVerificationState(
9740                            requiredUid, args);
9741
9742                    mPendingVerification.append(verificationId, verificationState);
9743
9744                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9745                            receivers, verificationState);
9746
9747                    /*
9748                     * If any sufficient verifiers were listed in the package
9749                     * manifest, attempt to ask them.
9750                     */
9751                    if (sufficientVerifiers != null) {
9752                        final int N = sufficientVerifiers.size();
9753                        if (N == 0) {
9754                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9755                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9756                        } else {
9757                            for (int i = 0; i < N; i++) {
9758                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9759
9760                                final Intent sufficientIntent = new Intent(verification);
9761                                sufficientIntent.setComponent(verifierComponent);
9762
9763                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9764                            }
9765                        }
9766                    }
9767
9768                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9769                            mRequiredVerifierPackage, receivers);
9770                    if (ret == PackageManager.INSTALL_SUCCEEDED
9771                            && mRequiredVerifierPackage != null) {
9772                        /*
9773                         * Send the intent to the required verification agent,
9774                         * but only start the verification timeout after the
9775                         * target BroadcastReceivers have run.
9776                         */
9777                        verification.setComponent(requiredVerifierComponent);
9778                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9779                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9780                                new BroadcastReceiver() {
9781                                    @Override
9782                                    public void onReceive(Context context, Intent intent) {
9783                                        final Message msg = mHandler
9784                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9785                                        msg.arg1 = verificationId;
9786                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9787                                    }
9788                                }, null, 0, null, null);
9789
9790                        /*
9791                         * We don't want the copy to proceed until verification
9792                         * succeeds, so null out this field.
9793                         */
9794                        mArgs = null;
9795                    }
9796                } else {
9797                    /*
9798                     * No package verification is enabled, so immediately start
9799                     * the remote call to initiate copy using temporary file.
9800                     */
9801                    ret = args.copyApk(mContainerService, true);
9802                }
9803            }
9804
9805            mRet = ret;
9806        }
9807
9808        @Override
9809        void handleReturnCode() {
9810            // If mArgs is null, then MCS couldn't be reached. When it
9811            // reconnects, it will try again to install. At that point, this
9812            // will succeed.
9813            if (mArgs != null) {
9814                processPendingInstall(mArgs, mRet);
9815            }
9816        }
9817
9818        @Override
9819        void handleServiceError() {
9820            mArgs = createInstallArgs(this);
9821            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9822        }
9823
9824        public boolean isForwardLocked() {
9825            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9826        }
9827    }
9828
9829    /**
9830     * Used during creation of InstallArgs
9831     *
9832     * @param installFlags package installation flags
9833     * @return true if should be installed on external storage
9834     */
9835    private static boolean installOnExternalAsec(int installFlags) {
9836        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9837            return false;
9838        }
9839        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9840            return true;
9841        }
9842        return false;
9843    }
9844
9845    /**
9846     * Used during creation of InstallArgs
9847     *
9848     * @param installFlags package installation flags
9849     * @return true if should be installed as forward locked
9850     */
9851    private static boolean installForwardLocked(int installFlags) {
9852        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9853    }
9854
9855    private InstallArgs createInstallArgs(InstallParams params) {
9856        if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
9857            return new AsecInstallArgs(params);
9858        } else {
9859            return new FileInstallArgs(params);
9860        }
9861    }
9862
9863    /**
9864     * Create args that describe an existing installed package. Typically used
9865     * when cleaning up old installs, or used as a move source.
9866     */
9867    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9868            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9869        final boolean isInAsec;
9870        if (installOnExternalAsec(installFlags)) {
9871            /* Apps on SD card are always in ASEC containers. */
9872            isInAsec = true;
9873        } else if (installForwardLocked(installFlags)
9874                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9875            /*
9876             * Forward-locked apps are only in ASEC containers if they're the
9877             * new style
9878             */
9879            isInAsec = true;
9880        } else {
9881            isInAsec = false;
9882        }
9883
9884        if (isInAsec) {
9885            return new AsecInstallArgs(codePath, instructionSets,
9886                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
9887        } else {
9888            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9889                    instructionSets);
9890        }
9891    }
9892
9893    static abstract class InstallArgs {
9894        /** @see InstallParams#origin */
9895        final OriginInfo origin;
9896
9897        final IPackageInstallObserver2 observer;
9898        // Always refers to PackageManager flags only
9899        final int installFlags;
9900        final String installerPackageName;
9901        final String volumeUuid;
9902        final ManifestDigest manifestDigest;
9903        final UserHandle user;
9904        final String abiOverride;
9905
9906        // The list of instruction sets supported by this app. This is currently
9907        // only used during the rmdex() phase to clean up resources. We can get rid of this
9908        // if we move dex files under the common app path.
9909        /* nullable */ String[] instructionSets;
9910
9911        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9912                String installerPackageName, String volumeUuid, ManifestDigest manifestDigest,
9913                UserHandle user, String[] instructionSets, String abiOverride) {
9914            this.origin = origin;
9915            this.installFlags = installFlags;
9916            this.observer = observer;
9917            this.installerPackageName = installerPackageName;
9918            this.volumeUuid = volumeUuid;
9919            this.manifestDigest = manifestDigest;
9920            this.user = user;
9921            this.instructionSets = instructionSets;
9922            this.abiOverride = abiOverride;
9923        }
9924
9925        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9926        abstract int doPreInstall(int status);
9927
9928        /**
9929         * Rename package into final resting place. All paths on the given
9930         * scanned package should be updated to reflect the rename.
9931         */
9932        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9933        abstract int doPostInstall(int status, int uid);
9934
9935        /** @see PackageSettingBase#codePathString */
9936        abstract String getCodePath();
9937        /** @see PackageSettingBase#resourcePathString */
9938        abstract String getResourcePath();
9939        abstract String getLegacyNativeLibraryPath();
9940
9941        // Need installer lock especially for dex file removal.
9942        abstract void cleanUpResourcesLI();
9943        abstract boolean doPostDeleteLI(boolean delete);
9944        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9945
9946        /**
9947         * Called before the source arguments are copied. This is used mostly
9948         * for MoveParams when it needs to read the source file to put it in the
9949         * destination.
9950         */
9951        int doPreCopy() {
9952            return PackageManager.INSTALL_SUCCEEDED;
9953        }
9954
9955        /**
9956         * Called after the source arguments are copied. This is used mostly for
9957         * MoveParams when it needs to read the source file to put it in the
9958         * destination.
9959         *
9960         * @return
9961         */
9962        int doPostCopy(int uid) {
9963            return PackageManager.INSTALL_SUCCEEDED;
9964        }
9965
9966        protected boolean isFwdLocked() {
9967            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9968        }
9969
9970        protected boolean isExternalAsec() {
9971            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9972        }
9973
9974        UserHandle getUser() {
9975            return user;
9976        }
9977    }
9978
9979    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
9980        if (!allCodePaths.isEmpty()) {
9981            if (instructionSets == null) {
9982                throw new IllegalStateException("instructionSet == null");
9983            }
9984            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9985            for (String codePath : allCodePaths) {
9986                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9987                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9988                    if (retCode < 0) {
9989                        Slog.w(TAG, "Couldn't remove dex file for package: "
9990                                + " at location " + codePath + ", retcode=" + retCode);
9991                        // we don't consider this to be a failure of the core package deletion
9992                    }
9993                }
9994            }
9995        }
9996    }
9997
9998    /**
9999     * Logic to handle installation of non-ASEC applications, including copying
10000     * and renaming logic.
10001     */
10002    class FileInstallArgs extends InstallArgs {
10003        private File codeFile;
10004        private File resourceFile;
10005        private File legacyNativeLibraryPath;
10006
10007        // Example topology:
10008        // /data/app/com.example/base.apk
10009        // /data/app/com.example/split_foo.apk
10010        // /data/app/com.example/lib/arm/libfoo.so
10011        // /data/app/com.example/lib/arm64/libfoo.so
10012        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10013
10014        /** New install */
10015        FileInstallArgs(InstallParams params) {
10016            super(params.origin, params.observer, params.installFlags,
10017                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10018                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10019            if (isFwdLocked()) {
10020                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10021            }
10022        }
10023
10024        /** Existing install */
10025        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
10026                String[] instructionSets) {
10027            super(OriginInfo.fromNothing(), null, 0, null, null, null, null, instructionSets, null);
10028            this.codeFile = (codePath != null) ? new File(codePath) : null;
10029            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10030            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
10031                    new File(legacyNativeLibraryPath) : null;
10032        }
10033
10034        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
10035            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
10036                    isFwdLocked(), abiOverride);
10037
10038            final StorageManager storage = StorageManager.from(mContext);
10039            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
10040        }
10041
10042        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10043            if (origin.staged) {
10044                Slog.d(TAG, origin.file + " already staged; skipping copy");
10045                codeFile = origin.file;
10046                resourceFile = origin.file;
10047                return PackageManager.INSTALL_SUCCEEDED;
10048            }
10049
10050            try {
10051                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10052                codeFile = tempDir;
10053                resourceFile = tempDir;
10054            } catch (IOException e) {
10055                Slog.w(TAG, "Failed to create copy file: " + e);
10056                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10057            }
10058
10059            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10060                @Override
10061                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10062                    if (!FileUtils.isValidExtFilename(name)) {
10063                        throw new IllegalArgumentException("Invalid filename: " + name);
10064                    }
10065                    try {
10066                        final File file = new File(codeFile, name);
10067                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10068                                O_RDWR | O_CREAT, 0644);
10069                        Os.chmod(file.getAbsolutePath(), 0644);
10070                        return new ParcelFileDescriptor(fd);
10071                    } catch (ErrnoException e) {
10072                        throw new RemoteException("Failed to open: " + e.getMessage());
10073                    }
10074                }
10075            };
10076
10077            int ret = PackageManager.INSTALL_SUCCEEDED;
10078            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10079            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10080                Slog.e(TAG, "Failed to copy package");
10081                return ret;
10082            }
10083
10084            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10085            NativeLibraryHelper.Handle handle = null;
10086            try {
10087                handle = NativeLibraryHelper.Handle.create(codeFile);
10088                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10089                        abiOverride);
10090            } catch (IOException e) {
10091                Slog.e(TAG, "Copying native libraries failed", e);
10092                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10093            } finally {
10094                IoUtils.closeQuietly(handle);
10095            }
10096
10097            return ret;
10098        }
10099
10100        int doPreInstall(int status) {
10101            if (status != PackageManager.INSTALL_SUCCEEDED) {
10102                cleanUp();
10103            }
10104            return status;
10105        }
10106
10107        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10108            if (status != PackageManager.INSTALL_SUCCEEDED) {
10109                cleanUp();
10110                return false;
10111            } else {
10112                final File targetDir = codeFile.getParentFile();
10113                final File beforeCodeFile = codeFile;
10114                final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10115
10116                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10117                try {
10118                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10119                } catch (ErrnoException e) {
10120                    Slog.d(TAG, "Failed to rename", e);
10121                    return false;
10122                }
10123
10124                if (!SELinux.restoreconRecursive(afterCodeFile)) {
10125                    Slog.d(TAG, "Failed to restorecon");
10126                    return false;
10127                }
10128
10129                // Reflect the rename internally
10130                codeFile = afterCodeFile;
10131                resourceFile = afterCodeFile;
10132
10133                // Reflect the rename in scanned details
10134                pkg.codePath = afterCodeFile.getAbsolutePath();
10135                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10136                        pkg.baseCodePath);
10137                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10138                        pkg.splitCodePaths);
10139
10140                // Reflect the rename in app info
10141                pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10142                pkg.applicationInfo.setCodePath(pkg.codePath);
10143                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10144                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10145                pkg.applicationInfo.setResourcePath(pkg.codePath);
10146                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10147                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10148
10149                return true;
10150            }
10151        }
10152
10153        int doPostInstall(int status, int uid) {
10154            if (status != PackageManager.INSTALL_SUCCEEDED) {
10155                cleanUp();
10156            }
10157            return status;
10158        }
10159
10160        @Override
10161        String getCodePath() {
10162            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10163        }
10164
10165        @Override
10166        String getResourcePath() {
10167            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10168        }
10169
10170        @Override
10171        String getLegacyNativeLibraryPath() {
10172            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
10173        }
10174
10175        private boolean cleanUp() {
10176            if (codeFile == null || !codeFile.exists()) {
10177                return false;
10178            }
10179
10180            if (codeFile.isDirectory()) {
10181                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10182            } else {
10183                codeFile.delete();
10184            }
10185
10186            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10187                resourceFile.delete();
10188            }
10189
10190            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
10191                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
10192                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
10193                }
10194                legacyNativeLibraryPath.delete();
10195            }
10196
10197            return true;
10198        }
10199
10200        void cleanUpResourcesLI() {
10201            // Try enumerating all code paths before deleting
10202            List<String> allCodePaths = Collections.EMPTY_LIST;
10203            if (codeFile != null && codeFile.exists()) {
10204                try {
10205                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10206                    allCodePaths = pkg.getAllCodePaths();
10207                } catch (PackageParserException e) {
10208                    // Ignored; we tried our best
10209                }
10210            }
10211
10212            cleanUp();
10213            removeDexFiles(allCodePaths, instructionSets);
10214        }
10215
10216        boolean doPostDeleteLI(boolean delete) {
10217            // XXX err, shouldn't we respect the delete flag?
10218            cleanUpResourcesLI();
10219            return true;
10220        }
10221    }
10222
10223    private boolean isAsecExternal(String cid) {
10224        final String asecPath = PackageHelper.getSdFilesystem(cid);
10225        return !asecPath.startsWith(mAsecInternalPath);
10226    }
10227
10228    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10229            PackageManagerException {
10230        if (copyRet < 0) {
10231            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10232                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10233                throw new PackageManagerException(copyRet, message);
10234            }
10235        }
10236    }
10237
10238    /**
10239     * Extract the MountService "container ID" from the full code path of an
10240     * .apk.
10241     */
10242    static String cidFromCodePath(String fullCodePath) {
10243        int eidx = fullCodePath.lastIndexOf("/");
10244        String subStr1 = fullCodePath.substring(0, eidx);
10245        int sidx = subStr1.lastIndexOf("/");
10246        return subStr1.substring(sidx+1, eidx);
10247    }
10248
10249    /**
10250     * Logic to handle installation of ASEC applications, including copying and
10251     * renaming logic.
10252     */
10253    class AsecInstallArgs extends InstallArgs {
10254        static final String RES_FILE_NAME = "pkg.apk";
10255        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10256
10257        String cid;
10258        String packagePath;
10259        String resourcePath;
10260        String legacyNativeLibraryDir;
10261
10262        /** New install */
10263        AsecInstallArgs(InstallParams params) {
10264            super(params.origin, params.observer, params.installFlags,
10265                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10266                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10267        }
10268
10269        /** Existing install */
10270        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10271                        boolean isExternal, boolean isForwardLocked) {
10272            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
10273                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10274                    instructionSets, null);
10275            // Hackily pretend we're still looking at a full code path
10276            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10277                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10278            }
10279
10280            // Extract cid from fullCodePath
10281            int eidx = fullCodePath.lastIndexOf("/");
10282            String subStr1 = fullCodePath.substring(0, eidx);
10283            int sidx = subStr1.lastIndexOf("/");
10284            cid = subStr1.substring(sidx+1, eidx);
10285            setMountPath(subStr1);
10286        }
10287
10288        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10289            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10290                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10291                    instructionSets, null);
10292            this.cid = cid;
10293            setMountPath(PackageHelper.getSdDir(cid));
10294        }
10295
10296        void createCopyFile() {
10297            cid = mInstallerService.allocateExternalStageCidLegacy();
10298        }
10299
10300        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
10301            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
10302                    abiOverride);
10303
10304            final File target;
10305            if (isExternalAsec()) {
10306                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
10307            } else {
10308                target = Environment.getDataDirectory();
10309            }
10310
10311            final StorageManager storage = StorageManager.from(mContext);
10312            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
10313        }
10314
10315        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10316            if (origin.staged) {
10317                Slog.d(TAG, origin.cid + " already staged; skipping copy");
10318                cid = origin.cid;
10319                setMountPath(PackageHelper.getSdDir(cid));
10320                return PackageManager.INSTALL_SUCCEEDED;
10321            }
10322
10323            if (temp) {
10324                createCopyFile();
10325            } else {
10326                /*
10327                 * Pre-emptively destroy the container since it's destroyed if
10328                 * copying fails due to it existing anyway.
10329                 */
10330                PackageHelper.destroySdDir(cid);
10331            }
10332
10333            final String newMountPath = imcs.copyPackageToContainer(
10334                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10335                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10336
10337            if (newMountPath != null) {
10338                setMountPath(newMountPath);
10339                return PackageManager.INSTALL_SUCCEEDED;
10340            } else {
10341                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10342            }
10343        }
10344
10345        @Override
10346        String getCodePath() {
10347            return packagePath;
10348        }
10349
10350        @Override
10351        String getResourcePath() {
10352            return resourcePath;
10353        }
10354
10355        @Override
10356        String getLegacyNativeLibraryPath() {
10357            return legacyNativeLibraryDir;
10358        }
10359
10360        int doPreInstall(int status) {
10361            if (status != PackageManager.INSTALL_SUCCEEDED) {
10362                // Destroy container
10363                PackageHelper.destroySdDir(cid);
10364            } else {
10365                boolean mounted = PackageHelper.isContainerMounted(cid);
10366                if (!mounted) {
10367                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10368                            Process.SYSTEM_UID);
10369                    if (newMountPath != null) {
10370                        setMountPath(newMountPath);
10371                    } else {
10372                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10373                    }
10374                }
10375            }
10376            return status;
10377        }
10378
10379        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10380            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10381            String newMountPath = null;
10382            if (PackageHelper.isContainerMounted(cid)) {
10383                // Unmount the container
10384                if (!PackageHelper.unMountSdDir(cid)) {
10385                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10386                    return false;
10387                }
10388            }
10389            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10390                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10391                        " which might be stale. Will try to clean up.");
10392                // Clean up the stale container and proceed to recreate.
10393                if (!PackageHelper.destroySdDir(newCacheId)) {
10394                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10395                    return false;
10396                }
10397                // Successfully cleaned up stale container. Try to rename again.
10398                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10399                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10400                            + " inspite of cleaning it up.");
10401                    return false;
10402                }
10403            }
10404            if (!PackageHelper.isContainerMounted(newCacheId)) {
10405                Slog.w(TAG, "Mounting container " + newCacheId);
10406                newMountPath = PackageHelper.mountSdDir(newCacheId,
10407                        getEncryptKey(), Process.SYSTEM_UID);
10408            } else {
10409                newMountPath = PackageHelper.getSdDir(newCacheId);
10410            }
10411            if (newMountPath == null) {
10412                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10413                return false;
10414            }
10415            Log.i(TAG, "Succesfully renamed " + cid +
10416                    " to " + newCacheId +
10417                    " at new path: " + newMountPath);
10418            cid = newCacheId;
10419
10420            final File beforeCodeFile = new File(packagePath);
10421            setMountPath(newMountPath);
10422            final File afterCodeFile = new File(packagePath);
10423
10424            // Reflect the rename in scanned details
10425            pkg.codePath = afterCodeFile.getAbsolutePath();
10426            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10427                    pkg.baseCodePath);
10428            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10429                    pkg.splitCodePaths);
10430
10431            // Reflect the rename in app info
10432            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10433            pkg.applicationInfo.setCodePath(pkg.codePath);
10434            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10435            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10436            pkg.applicationInfo.setResourcePath(pkg.codePath);
10437            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10438            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10439
10440            return true;
10441        }
10442
10443        private void setMountPath(String mountPath) {
10444            final File mountFile = new File(mountPath);
10445
10446            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10447            if (monolithicFile.exists()) {
10448                packagePath = monolithicFile.getAbsolutePath();
10449                if (isFwdLocked()) {
10450                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10451                } else {
10452                    resourcePath = packagePath;
10453                }
10454            } else {
10455                packagePath = mountFile.getAbsolutePath();
10456                resourcePath = packagePath;
10457            }
10458
10459            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
10460        }
10461
10462        int doPostInstall(int status, int uid) {
10463            if (status != PackageManager.INSTALL_SUCCEEDED) {
10464                cleanUp();
10465            } else {
10466                final int groupOwner;
10467                final String protectedFile;
10468                if (isFwdLocked()) {
10469                    groupOwner = UserHandle.getSharedAppGid(uid);
10470                    protectedFile = RES_FILE_NAME;
10471                } else {
10472                    groupOwner = -1;
10473                    protectedFile = null;
10474                }
10475
10476                if (uid < Process.FIRST_APPLICATION_UID
10477                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10478                    Slog.e(TAG, "Failed to finalize " + cid);
10479                    PackageHelper.destroySdDir(cid);
10480                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10481                }
10482
10483                boolean mounted = PackageHelper.isContainerMounted(cid);
10484                if (!mounted) {
10485                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10486                }
10487            }
10488            return status;
10489        }
10490
10491        private void cleanUp() {
10492            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10493
10494            // Destroy secure container
10495            PackageHelper.destroySdDir(cid);
10496        }
10497
10498        private List<String> getAllCodePaths() {
10499            final File codeFile = new File(getCodePath());
10500            if (codeFile != null && codeFile.exists()) {
10501                try {
10502                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10503                    return pkg.getAllCodePaths();
10504                } catch (PackageParserException e) {
10505                    // Ignored; we tried our best
10506                }
10507            }
10508            return Collections.EMPTY_LIST;
10509        }
10510
10511        void cleanUpResourcesLI() {
10512            // Enumerate all code paths before deleting
10513            cleanUpResourcesLI(getAllCodePaths());
10514        }
10515
10516        private void cleanUpResourcesLI(List<String> allCodePaths) {
10517            cleanUp();
10518            removeDexFiles(allCodePaths, instructionSets);
10519        }
10520
10521
10522
10523        String getPackageName() {
10524            return getAsecPackageName(cid);
10525        }
10526
10527        boolean doPostDeleteLI(boolean delete) {
10528            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10529            final List<String> allCodePaths = getAllCodePaths();
10530            boolean mounted = PackageHelper.isContainerMounted(cid);
10531            if (mounted) {
10532                // Unmount first
10533                if (PackageHelper.unMountSdDir(cid)) {
10534                    mounted = false;
10535                }
10536            }
10537            if (!mounted && delete) {
10538                cleanUpResourcesLI(allCodePaths);
10539            }
10540            return !mounted;
10541        }
10542
10543        @Override
10544        int doPreCopy() {
10545            if (isFwdLocked()) {
10546                if (!PackageHelper.fixSdPermissions(cid,
10547                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10548                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10549                }
10550            }
10551
10552            return PackageManager.INSTALL_SUCCEEDED;
10553        }
10554
10555        @Override
10556        int doPostCopy(int uid) {
10557            if (isFwdLocked()) {
10558                if (uid < Process.FIRST_APPLICATION_UID
10559                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10560                                RES_FILE_NAME)) {
10561                    Slog.e(TAG, "Failed to finalize " + cid);
10562                    PackageHelper.destroySdDir(cid);
10563                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10564                }
10565            }
10566
10567            return PackageManager.INSTALL_SUCCEEDED;
10568        }
10569    }
10570
10571    static String getAsecPackageName(String packageCid) {
10572        int idx = packageCid.lastIndexOf("-");
10573        if (idx == -1) {
10574            return packageCid;
10575        }
10576        return packageCid.substring(0, idx);
10577    }
10578
10579    // Utility method used to create code paths based on package name and available index.
10580    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
10581        String idxStr = "";
10582        int idx = 1;
10583        // Fall back to default value of idx=1 if prefix is not
10584        // part of oldCodePath
10585        if (oldCodePath != null) {
10586            String subStr = oldCodePath;
10587            // Drop the suffix right away
10588            if (suffix != null && subStr.endsWith(suffix)) {
10589                subStr = subStr.substring(0, subStr.length() - suffix.length());
10590            }
10591            // If oldCodePath already contains prefix find out the
10592            // ending index to either increment or decrement.
10593            int sidx = subStr.lastIndexOf(prefix);
10594            if (sidx != -1) {
10595                subStr = subStr.substring(sidx + prefix.length());
10596                if (subStr != null) {
10597                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10598                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10599                    }
10600                    try {
10601                        idx = Integer.parseInt(subStr);
10602                        if (idx <= 1) {
10603                            idx++;
10604                        } else {
10605                            idx--;
10606                        }
10607                    } catch(NumberFormatException e) {
10608                    }
10609                }
10610            }
10611        }
10612        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10613        return prefix + idxStr;
10614    }
10615
10616    private File getNextCodePath(File targetDir, String packageName) {
10617        int suffix = 1;
10618        File result;
10619        do {
10620            result = new File(targetDir, packageName + "-" + suffix);
10621            suffix++;
10622        } while (result.exists());
10623        return result;
10624    }
10625
10626    // Utility method that returns the relative package path with respect
10627    // to the installation directory. Like say for /data/data/com.test-1.apk
10628    // string com.test-1 is returned.
10629    static String deriveCodePathName(String codePath) {
10630        if (codePath == null) {
10631            return null;
10632        }
10633        final File codeFile = new File(codePath);
10634        final String name = codeFile.getName();
10635        if (codeFile.isDirectory()) {
10636            return name;
10637        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10638            final int lastDot = name.lastIndexOf('.');
10639            return name.substring(0, lastDot);
10640        } else {
10641            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10642            return null;
10643        }
10644    }
10645
10646    class PackageInstalledInfo {
10647        String name;
10648        int uid;
10649        // The set of users that originally had this package installed.
10650        int[] origUsers;
10651        // The set of users that now have this package installed.
10652        int[] newUsers;
10653        PackageParser.Package pkg;
10654        int returnCode;
10655        String returnMsg;
10656        PackageRemovedInfo removedInfo;
10657
10658        public void setError(int code, String msg) {
10659            returnCode = code;
10660            returnMsg = msg;
10661            Slog.w(TAG, msg);
10662        }
10663
10664        public void setError(String msg, PackageParserException e) {
10665            returnCode = e.error;
10666            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10667            Slog.w(TAG, msg, e);
10668        }
10669
10670        public void setError(String msg, PackageManagerException e) {
10671            returnCode = e.error;
10672            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10673            Slog.w(TAG, msg, e);
10674        }
10675
10676        // In some error cases we want to convey more info back to the observer
10677        String origPackage;
10678        String origPermission;
10679    }
10680
10681    /*
10682     * Install a non-existing package.
10683     */
10684    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
10685            UserHandle user, String installerPackageName, String volumeUuid,
10686            PackageInstalledInfo res) {
10687        // Remember this for later, in case we need to rollback this install
10688        String pkgName = pkg.packageName;
10689
10690        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10691        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
10692                UserHandle.USER_OWNER).exists();
10693        synchronized(mPackages) {
10694            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10695                // A package with the same name is already installed, though
10696                // it has been renamed to an older name.  The package we
10697                // are trying to install should be installed as an update to
10698                // the existing one, but that has not been requested, so bail.
10699                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10700                        + " without first uninstalling package running as "
10701                        + mSettings.mRenamedPackages.get(pkgName));
10702                return;
10703            }
10704            if (mPackages.containsKey(pkgName)) {
10705                // Don't allow installation over an existing package with the same name.
10706                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10707                        + " without first uninstalling.");
10708                return;
10709            }
10710        }
10711
10712        try {
10713            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10714                    System.currentTimeMillis(), user);
10715
10716            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
10717            // delete the partially installed application. the data directory will have to be
10718            // restored if it was already existing
10719            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10720                // remove package from internal structures.  Note that we want deletePackageX to
10721                // delete the package data and cache directories that it created in
10722                // scanPackageLocked, unless those directories existed before we even tried to
10723                // install.
10724                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10725                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10726                                res.removedInfo, true);
10727            }
10728
10729        } catch (PackageManagerException e) {
10730            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10731        }
10732    }
10733
10734    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10735        // Upgrade keysets are being used.  Determine if new package has a superset of the
10736        // required keys.
10737        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10738        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10739        for (int i = 0; i < upgradeKeySets.length; i++) {
10740            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10741            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10742                return true;
10743            }
10744        }
10745        return false;
10746    }
10747
10748    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
10749            UserHandle user, String installerPackageName, String volumeUuid,
10750            PackageInstalledInfo res) {
10751        PackageParser.Package oldPackage;
10752        String pkgName = pkg.packageName;
10753        int[] allUsers;
10754        boolean[] perUserInstalled;
10755
10756        // First find the old package info and check signatures
10757        synchronized(mPackages) {
10758            oldPackage = mPackages.get(pkgName);
10759            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10760            PackageSetting ps = mSettings.mPackages.get(pkgName);
10761            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10762                // default to original signature matching
10763                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10764                    != PackageManager.SIGNATURE_MATCH) {
10765                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10766                            "New package has a different signature: " + pkgName);
10767                    return;
10768                }
10769            } else {
10770                if(!checkUpgradeKeySetLP(ps, pkg)) {
10771                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10772                            "New package not signed by keys specified by upgrade-keysets: "
10773                            + pkgName);
10774                    return;
10775                }
10776            }
10777
10778            // In case of rollback, remember per-user/profile install state
10779            allUsers = sUserManager.getUserIds();
10780            perUserInstalled = new boolean[allUsers.length];
10781            for (int i = 0; i < allUsers.length; i++) {
10782                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10783            }
10784        }
10785
10786        boolean sysPkg = (isSystemApp(oldPackage));
10787        if (sysPkg) {
10788            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10789                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
10790        } else {
10791            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10792                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
10793        }
10794    }
10795
10796    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10797            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10798            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
10799            String volumeUuid, PackageInstalledInfo res) {
10800        String pkgName = deletedPackage.packageName;
10801        boolean deletedPkg = true;
10802        boolean updatedSettings = false;
10803
10804        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10805                + deletedPackage);
10806        long origUpdateTime;
10807        if (pkg.mExtras != null) {
10808            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10809        } else {
10810            origUpdateTime = 0;
10811        }
10812
10813        // First delete the existing package while retaining the data directory
10814        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10815                res.removedInfo, true)) {
10816            // If the existing package wasn't successfully deleted
10817            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10818            deletedPkg = false;
10819        } else {
10820            // Successfully deleted the old package; proceed with replace.
10821
10822            // If deleted package lived in a container, give users a chance to
10823            // relinquish resources before killing.
10824            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
10825                if (DEBUG_INSTALL) {
10826                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10827                }
10828                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10829                final ArrayList<String> pkgList = new ArrayList<String>(1);
10830                pkgList.add(deletedPackage.applicationInfo.packageName);
10831                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10832            }
10833
10834            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
10835            try {
10836                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10837                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10838                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
10839                        perUserInstalled, res, user);
10840                updatedSettings = true;
10841            } catch (PackageManagerException e) {
10842                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10843            }
10844        }
10845
10846        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10847            // remove package from internal structures.  Note that we want deletePackageX to
10848            // delete the package data and cache directories that it created in
10849            // scanPackageLocked, unless those directories existed before we even tried to
10850            // install.
10851            if(updatedSettings) {
10852                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10853                deletePackageLI(
10854                        pkgName, null, true, allUsers, perUserInstalled,
10855                        PackageManager.DELETE_KEEP_DATA,
10856                                res.removedInfo, true);
10857            }
10858            // Since we failed to install the new package we need to restore the old
10859            // package that we deleted.
10860            if (deletedPkg) {
10861                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10862                File restoreFile = new File(deletedPackage.codePath);
10863                // Parse old package
10864                boolean oldExternal = isExternal(deletedPackage);
10865                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10866                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10867                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
10868                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10869                try {
10870                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10871                } catch (PackageManagerException e) {
10872                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10873                            + e.getMessage());
10874                    return;
10875                }
10876                // Restore of old package succeeded. Update permissions.
10877                // writer
10878                synchronized (mPackages) {
10879                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10880                            UPDATE_PERMISSIONS_ALL);
10881                    // can downgrade to reader
10882                    mSettings.writeLPr();
10883                }
10884                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10885            }
10886        }
10887    }
10888
10889    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10890            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10891            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
10892            String volumeUuid, PackageInstalledInfo res) {
10893        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10894                + ", old=" + deletedPackage);
10895        boolean disabledSystem = false;
10896        boolean updatedSettings = false;
10897        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10898        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
10899                != 0) {
10900            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10901        }
10902        String packageName = deletedPackage.packageName;
10903        if (packageName == null) {
10904            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10905                    "Attempt to delete null packageName.");
10906            return;
10907        }
10908        PackageParser.Package oldPkg;
10909        PackageSetting oldPkgSetting;
10910        // reader
10911        synchronized (mPackages) {
10912            oldPkg = mPackages.get(packageName);
10913            oldPkgSetting = mSettings.mPackages.get(packageName);
10914            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10915                    (oldPkgSetting == null)) {
10916                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10917                        "Couldn't find package:" + packageName + " information");
10918                return;
10919            }
10920        }
10921
10922        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10923
10924        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10925        res.removedInfo.removedPackage = packageName;
10926        // Remove existing system package
10927        removePackageLI(oldPkgSetting, true);
10928        // writer
10929        synchronized (mPackages) {
10930            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10931            if (!disabledSystem && deletedPackage != null) {
10932                // We didn't need to disable the .apk as a current system package,
10933                // which means we are replacing another update that is already
10934                // installed.  We need to make sure to delete the older one's .apk.
10935                res.removedInfo.args = createInstallArgsForExisting(0,
10936                        deletedPackage.applicationInfo.getCodePath(),
10937                        deletedPackage.applicationInfo.getResourcePath(),
10938                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10939                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10940            } else {
10941                res.removedInfo.args = null;
10942            }
10943        }
10944
10945        // Successfully disabled the old package. Now proceed with re-installation
10946        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
10947
10948        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10949        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10950
10951        PackageParser.Package newPackage = null;
10952        try {
10953            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10954            if (newPackage.mExtras != null) {
10955                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10956                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10957                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10958
10959                // is the update attempting to change shared user? that isn't going to work...
10960                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10961                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10962                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10963                            + " to " + newPkgSetting.sharedUser);
10964                    updatedSettings = true;
10965                }
10966            }
10967
10968            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10969                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
10970                        perUserInstalled, res, user);
10971                updatedSettings = true;
10972            }
10973
10974        } catch (PackageManagerException e) {
10975            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10976        }
10977
10978        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10979            // Re installation failed. Restore old information
10980            // Remove new pkg information
10981            if (newPackage != null) {
10982                removeInstalledPackageLI(newPackage, true);
10983            }
10984            // Add back the old system package
10985            try {
10986                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10987            } catch (PackageManagerException e) {
10988                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10989            }
10990            // Restore the old system information in Settings
10991            synchronized (mPackages) {
10992                if (disabledSystem) {
10993                    mSettings.enableSystemPackageLPw(packageName);
10994                }
10995                if (updatedSettings) {
10996                    mSettings.setInstallerPackageName(packageName,
10997                            oldPkgSetting.installerPackageName);
10998                }
10999                mSettings.writeLPr();
11000            }
11001        }
11002    }
11003
11004    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11005            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11006            UserHandle user) {
11007        String pkgName = newPackage.packageName;
11008        synchronized (mPackages) {
11009            //write settings. the installStatus will be incomplete at this stage.
11010            //note that the new package setting would have already been
11011            //added to mPackages. It hasn't been persisted yet.
11012            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11013            mSettings.writeLPr();
11014        }
11015
11016        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11017
11018        synchronized (mPackages) {
11019            updatePermissionsLPw(newPackage.packageName, newPackage,
11020                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11021                            ? UPDATE_PERMISSIONS_ALL : 0));
11022            // For system-bundled packages, we assume that installing an upgraded version
11023            // of the package implies that the user actually wants to run that new code,
11024            // so we enable the package.
11025            PackageSetting ps = mSettings.mPackages.get(pkgName);
11026            if (ps != null) {
11027                if (isSystemApp(newPackage)) {
11028                    // NB: implicit assumption that system package upgrades apply to all users
11029                    if (DEBUG_INSTALL) {
11030                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11031                    }
11032                    if (res.origUsers != null) {
11033                        for (int userHandle : res.origUsers) {
11034                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11035                                    userHandle, installerPackageName);
11036                        }
11037                    }
11038                    // Also convey the prior install/uninstall state
11039                    if (allUsers != null && perUserInstalled != null) {
11040                        for (int i = 0; i < allUsers.length; i++) {
11041                            if (DEBUG_INSTALL) {
11042                                Slog.d(TAG, "    user " + allUsers[i]
11043                                        + " => " + perUserInstalled[i]);
11044                            }
11045                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11046                        }
11047                        // these install state changes will be persisted in the
11048                        // upcoming call to mSettings.writeLPr().
11049                    }
11050                }
11051                // It's implied that when a user requests installation, they want the app to be
11052                // installed and enabled.
11053                int userId = user.getIdentifier();
11054                if (userId != UserHandle.USER_ALL) {
11055                    ps.setInstalled(true, userId);
11056                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11057                }
11058            }
11059            res.name = pkgName;
11060            res.uid = newPackage.applicationInfo.uid;
11061            res.pkg = newPackage;
11062            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11063            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11064            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11065            //to update install status
11066            mSettings.writeLPr();
11067        }
11068    }
11069
11070    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11071        final int installFlags = args.installFlags;
11072        final String installerPackageName = args.installerPackageName;
11073        final String volumeUuid = args.volumeUuid;
11074        final File tmpPackageFile = new File(args.getCodePath());
11075        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11076        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11077                || (args.volumeUuid != null));
11078        boolean replace = false;
11079        int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
11080        // Result object to be returned
11081        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11082
11083        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11084        // Retrieve PackageSettings and parse package
11085        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11086                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11087                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11088        PackageParser pp = new PackageParser();
11089        pp.setSeparateProcesses(mSeparateProcesses);
11090        pp.setDisplayMetrics(mMetrics);
11091
11092        final PackageParser.Package pkg;
11093        try {
11094            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11095        } catch (PackageParserException e) {
11096            res.setError("Failed parse during installPackageLI", e);
11097            return;
11098        }
11099
11100        // Mark that we have an install time CPU ABI override.
11101        pkg.cpuAbiOverride = args.abiOverride;
11102
11103        String pkgName = res.name = pkg.packageName;
11104        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11105            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11106                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11107                return;
11108            }
11109        }
11110
11111        try {
11112            pp.collectCertificates(pkg, parseFlags);
11113            pp.collectManifestDigest(pkg);
11114        } catch (PackageParserException e) {
11115            res.setError("Failed collect during installPackageLI", e);
11116            return;
11117        }
11118
11119        /* If the installer passed in a manifest digest, compare it now. */
11120        if (args.manifestDigest != null) {
11121            if (DEBUG_INSTALL) {
11122                final String parsedManifest = pkg.manifestDigest == null ? "null"
11123                        : pkg.manifestDigest.toString();
11124                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11125                        + parsedManifest);
11126            }
11127
11128            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11129                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11130                return;
11131            }
11132        } else if (DEBUG_INSTALL) {
11133            final String parsedManifest = pkg.manifestDigest == null
11134                    ? "null" : pkg.manifestDigest.toString();
11135            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11136        }
11137
11138        // Get rid of all references to package scan path via parser.
11139        pp = null;
11140        String oldCodePath = null;
11141        boolean systemApp = false;
11142        synchronized (mPackages) {
11143            // Check if installing already existing package
11144            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11145                String oldName = mSettings.mRenamedPackages.get(pkgName);
11146                if (pkg.mOriginalPackages != null
11147                        && pkg.mOriginalPackages.contains(oldName)
11148                        && mPackages.containsKey(oldName)) {
11149                    // This package is derived from an original package,
11150                    // and this device has been updating from that original
11151                    // name.  We must continue using the original name, so
11152                    // rename the new package here.
11153                    pkg.setPackageName(oldName);
11154                    pkgName = pkg.packageName;
11155                    replace = true;
11156                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11157                            + oldName + " pkgName=" + pkgName);
11158                } else if (mPackages.containsKey(pkgName)) {
11159                    // This package, under its official name, already exists
11160                    // on the device; we should replace it.
11161                    replace = true;
11162                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11163                }
11164            }
11165
11166            PackageSetting ps = mSettings.mPackages.get(pkgName);
11167            if (ps != null) {
11168                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11169
11170                // Quick sanity check that we're signed correctly if updating;
11171                // we'll check this again later when scanning, but we want to
11172                // bail early here before tripping over redefined permissions.
11173                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11174                    try {
11175                        verifySignaturesLP(ps, pkg);
11176                    } catch (PackageManagerException e) {
11177                        res.setError(e.error, e.getMessage());
11178                        return;
11179                    }
11180                } else {
11181                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11182                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11183                                + pkg.packageName + " upgrade keys do not match the "
11184                                + "previously installed version");
11185                        return;
11186                    }
11187                }
11188
11189                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11190                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11191                    systemApp = (ps.pkg.applicationInfo.flags &
11192                            ApplicationInfo.FLAG_SYSTEM) != 0;
11193                }
11194                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11195            }
11196
11197            // Check whether the newly-scanned package wants to define an already-defined perm
11198            int N = pkg.permissions.size();
11199            for (int i = N-1; i >= 0; i--) {
11200                PackageParser.Permission perm = pkg.permissions.get(i);
11201                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11202                if (bp != null) {
11203                    // If the defining package is signed with our cert, it's okay.  This
11204                    // also includes the "updating the same package" case, of course.
11205                    // "updating same package" could also involve key-rotation.
11206                    final boolean sigsOk;
11207                    if (!bp.sourcePackage.equals(pkg.packageName)
11208                            || !(bp.packageSetting instanceof PackageSetting)
11209                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
11210                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
11211                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11212                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11213                    } else {
11214                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11215                    }
11216                    if (!sigsOk) {
11217                        // If the owning package is the system itself, we log but allow
11218                        // install to proceed; we fail the install on all other permission
11219                        // redefinitions.
11220                        if (!bp.sourcePackage.equals("android")) {
11221                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11222                                    + pkg.packageName + " attempting to redeclare permission "
11223                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11224                            res.origPermission = perm.info.name;
11225                            res.origPackage = bp.sourcePackage;
11226                            return;
11227                        } else {
11228                            Slog.w(TAG, "Package " + pkg.packageName
11229                                    + " attempting to redeclare system permission "
11230                                    + perm.info.name + "; ignoring new declaration");
11231                            pkg.permissions.remove(i);
11232                        }
11233                    }
11234                }
11235            }
11236
11237        }
11238
11239        if (systemApp && onExternal) {
11240            // Disable updates to system apps on sdcard
11241            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11242                    "Cannot install updates to system apps on sdcard");
11243            return;
11244        }
11245
11246        // If app directory is not writable, dexopt will be called after the rename
11247        if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11248            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11249            scanFlags |= SCAN_NO_DEX;
11250            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11251            int result = mPackageDexOptimizer
11252                    .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */,
11253                            false /* defer */, false /* inclDependencies */);
11254            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11255                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11256                return;
11257            }
11258        }
11259
11260        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11261            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11262            return;
11263        }
11264
11265        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11266
11267        if (replace) {
11268            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
11269                    installerPackageName, volumeUuid, res);
11270        } else {
11271            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11272                    args.user, installerPackageName, volumeUuid, res);
11273        }
11274        synchronized (mPackages) {
11275            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11276            if (ps != null) {
11277                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11278            }
11279        }
11280    }
11281
11282    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11283        if (mIntentFilterVerifierComponent == null) {
11284            Slog.d(TAG, "No IntentFilter verification will not be done as "
11285                    + "there is no IntentFilterVerifier available!");
11286            return;
11287        }
11288
11289        final int verifierUid = getPackageUid(
11290                mIntentFilterVerifierComponent.getPackageName(),
11291                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11292
11293        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11294        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11295        msg.obj = pkg;
11296        msg.arg1 = userId;
11297        msg.arg2 = verifierUid;
11298
11299        mHandler.sendMessage(msg);
11300    }
11301
11302    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11303            PackageParser.Package pkg) {
11304        int size = pkg.activities.size();
11305        if (size == 0) {
11306            Slog.d(TAG, "No activity, so no need to verify any IntentFilter!");
11307            return;
11308        }
11309
11310        final boolean hasDomainURLs = hasDomainURLs(pkg);
11311        if (!hasDomainURLs) {
11312            Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!");
11313            return;
11314        }
11315
11316        Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size
11317                + " Activities needs verification ...");
11318
11319        final int verificationId = mIntentFilterVerificationToken++;
11320        int count = 0;
11321        final String packageName = pkg.packageName;
11322        ArrayList<String> allHosts = new ArrayList<>();
11323
11324        synchronized (mPackages) {
11325            for (PackageParser.Activity a : pkg.activities) {
11326                for (ActivityIntentInfo filter : a.intents) {
11327                    boolean needsFilterVerification = filter.needsVerification();
11328                    if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11329                        Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString());
11330                        mIntentFilterVerifier.addOneIntentFilterVerification(
11331                                verifierUid, userId, verificationId, filter, packageName);
11332                        count++;
11333                    } else if (!needsFilterVerification) {
11334                        Slog.d(TAG, "No verification needed for IntentFilter:"
11335                                + filter.toString());
11336                        if (hasValidDomains(filter)) {
11337                            allHosts.addAll(filter.getHostsList());
11338                        }
11339                    } else {
11340                        Slog.d(TAG, "Verification already done for IntentFilter:"
11341                                + filter.toString());
11342                    }
11343                }
11344            }
11345        }
11346
11347        if (count > 0) {
11348            mIntentFilterVerifier.startVerifications(userId);
11349            Slog.d(TAG, "Started " + count + " IntentFilter verification"
11350                    + (count > 1 ? "s" : "") +  " for userId:" + userId + "!");
11351        } else {
11352            Slog.d(TAG, "No need to start any IntentFilter verification!");
11353            if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw(
11354                    packageName, allHosts) != null) {
11355                scheduleWriteSettingsLocked();
11356            }
11357        }
11358    }
11359
11360    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11361        final ComponentName cn  = filter.activity.getComponentName();
11362        final String packageName = cn.getPackageName();
11363
11364        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11365                packageName);
11366        if (ivi == null) {
11367            return true;
11368        }
11369        int status = ivi.getStatus();
11370        switch (status) {
11371            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11372            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11373                return true;
11374
11375            default:
11376                // Nothing to do
11377                return false;
11378        }
11379    }
11380
11381    private static boolean isMultiArch(PackageSetting ps) {
11382        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11383    }
11384
11385    private static boolean isMultiArch(ApplicationInfo info) {
11386        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11387    }
11388
11389    private static boolean isExternal(PackageParser.Package pkg) {
11390        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11391    }
11392
11393    private static boolean isExternal(PackageSetting ps) {
11394        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11395    }
11396
11397    private static boolean isExternal(ApplicationInfo info) {
11398        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11399    }
11400
11401    private static boolean isSystemApp(PackageParser.Package pkg) {
11402        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11403    }
11404
11405    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11406        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11407    }
11408
11409    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11410        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11411    }
11412
11413    private static boolean isSystemApp(PackageSetting ps) {
11414        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11415    }
11416
11417    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11418        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11419    }
11420
11421    private int packageFlagsToInstallFlags(PackageSetting ps) {
11422        int installFlags = 0;
11423        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11424            // This existing package was an external ASEC install when we have
11425            // the external flag without a UUID
11426            installFlags |= PackageManager.INSTALL_EXTERNAL;
11427        }
11428        if (ps.isForwardLocked()) {
11429            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11430        }
11431        return installFlags;
11432    }
11433
11434    private void deleteTempPackageFiles() {
11435        final FilenameFilter filter = new FilenameFilter() {
11436            public boolean accept(File dir, String name) {
11437                return name.startsWith("vmdl") && name.endsWith(".tmp");
11438            }
11439        };
11440        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11441            file.delete();
11442        }
11443    }
11444
11445    @Override
11446    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11447            int flags) {
11448        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11449                flags);
11450    }
11451
11452    @Override
11453    public void deletePackage(final String packageName,
11454            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11455        mContext.enforceCallingOrSelfPermission(
11456                android.Manifest.permission.DELETE_PACKAGES, null);
11457        final int uid = Binder.getCallingUid();
11458        if (UserHandle.getUserId(uid) != userId) {
11459            mContext.enforceCallingPermission(
11460                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11461                    "deletePackage for user " + userId);
11462        }
11463        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11464            try {
11465                observer.onPackageDeleted(packageName,
11466                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11467            } catch (RemoteException re) {
11468            }
11469            return;
11470        }
11471
11472        boolean uninstallBlocked = false;
11473        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11474            int[] users = sUserManager.getUserIds();
11475            for (int i = 0; i < users.length; ++i) {
11476                if (getBlockUninstallForUser(packageName, users[i])) {
11477                    uninstallBlocked = true;
11478                    break;
11479                }
11480            }
11481        } else {
11482            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11483        }
11484        if (uninstallBlocked) {
11485            try {
11486                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11487                        null);
11488            } catch (RemoteException re) {
11489            }
11490            return;
11491        }
11492
11493        if (DEBUG_REMOVE) {
11494            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
11495        }
11496        // Queue up an async operation since the package deletion may take a little while.
11497        mHandler.post(new Runnable() {
11498            public void run() {
11499                mHandler.removeCallbacks(this);
11500                final int returnCode = deletePackageX(packageName, userId, flags);
11501                if (observer != null) {
11502                    try {
11503                        observer.onPackageDeleted(packageName, returnCode, null);
11504                    } catch (RemoteException e) {
11505                        Log.i(TAG, "Observer no longer exists.");
11506                    } //end catch
11507                } //end if
11508            } //end run
11509        });
11510    }
11511
11512    private boolean isPackageDeviceAdmin(String packageName, int userId) {
11513        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
11514                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
11515        try {
11516            if (dpm != null) {
11517                if (dpm.isDeviceOwner(packageName)) {
11518                    return true;
11519                }
11520                int[] users;
11521                if (userId == UserHandle.USER_ALL) {
11522                    users = sUserManager.getUserIds();
11523                } else {
11524                    users = new int[]{userId};
11525                }
11526                for (int i = 0; i < users.length; ++i) {
11527                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
11528                        return true;
11529                    }
11530                }
11531            }
11532        } catch (RemoteException e) {
11533        }
11534        return false;
11535    }
11536
11537    /**
11538     *  This method is an internal method that could be get invoked either
11539     *  to delete an installed package or to clean up a failed installation.
11540     *  After deleting an installed package, a broadcast is sent to notify any
11541     *  listeners that the package has been installed. For cleaning up a failed
11542     *  installation, the broadcast is not necessary since the package's
11543     *  installation wouldn't have sent the initial broadcast either
11544     *  The key steps in deleting a package are
11545     *  deleting the package information in internal structures like mPackages,
11546     *  deleting the packages base directories through installd
11547     *  updating mSettings to reflect current status
11548     *  persisting settings for later use
11549     *  sending a broadcast if necessary
11550     */
11551    private int deletePackageX(String packageName, int userId, int flags) {
11552        final PackageRemovedInfo info = new PackageRemovedInfo();
11553        final boolean res;
11554
11555        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
11556                ? UserHandle.ALL : new UserHandle(userId);
11557
11558        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
11559            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
11560            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
11561        }
11562
11563        boolean removedForAllUsers = false;
11564        boolean systemUpdate = false;
11565
11566        // for the uninstall-updates case and restricted profiles, remember the per-
11567        // userhandle installed state
11568        int[] allUsers;
11569        boolean[] perUserInstalled;
11570        synchronized (mPackages) {
11571            PackageSetting ps = mSettings.mPackages.get(packageName);
11572            allUsers = sUserManager.getUserIds();
11573            perUserInstalled = new boolean[allUsers.length];
11574            for (int i = 0; i < allUsers.length; i++) {
11575                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11576            }
11577        }
11578
11579        synchronized (mInstallLock) {
11580            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
11581            res = deletePackageLI(packageName, removeForUser,
11582                    true, allUsers, perUserInstalled,
11583                    flags | REMOVE_CHATTY, info, true);
11584            systemUpdate = info.isRemovedPackageSystemUpdate;
11585            if (res && !systemUpdate && mPackages.get(packageName) == null) {
11586                removedForAllUsers = true;
11587            }
11588            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
11589                    + " removedForAllUsers=" + removedForAllUsers);
11590        }
11591
11592        if (res) {
11593            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
11594
11595            // If the removed package was a system update, the old system package
11596            // was re-enabled; we need to broadcast this information
11597            if (systemUpdate) {
11598                Bundle extras = new Bundle(1);
11599                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
11600                        ? info.removedAppId : info.uid);
11601                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11602
11603                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
11604                        extras, null, null, null);
11605                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
11606                        extras, null, null, null);
11607                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
11608                        null, packageName, null, null);
11609            }
11610        }
11611        // Force a gc here.
11612        Runtime.getRuntime().gc();
11613        // Delete the resources here after sending the broadcast to let
11614        // other processes clean up before deleting resources.
11615        if (info.args != null) {
11616            synchronized (mInstallLock) {
11617                info.args.doPostDeleteLI(true);
11618            }
11619        }
11620
11621        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
11622    }
11623
11624    static class PackageRemovedInfo {
11625        String removedPackage;
11626        int uid = -1;
11627        int removedAppId = -1;
11628        int[] removedUsers = null;
11629        boolean isRemovedPackageSystemUpdate = false;
11630        // Clean up resources deleted packages.
11631        InstallArgs args = null;
11632
11633        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
11634            Bundle extras = new Bundle(1);
11635            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
11636            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
11637            if (replacing) {
11638                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11639            }
11640            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
11641            if (removedPackage != null) {
11642                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
11643                        extras, null, null, removedUsers);
11644                if (fullRemove && !replacing) {
11645                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
11646                            extras, null, null, removedUsers);
11647                }
11648            }
11649            if (removedAppId >= 0) {
11650                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
11651                        removedUsers);
11652            }
11653        }
11654    }
11655
11656    /*
11657     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
11658     * flag is not set, the data directory is removed as well.
11659     * make sure this flag is set for partially installed apps. If not its meaningless to
11660     * delete a partially installed application.
11661     */
11662    private void removePackageDataLI(PackageSetting ps,
11663            int[] allUserHandles, boolean[] perUserInstalled,
11664            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
11665        String packageName = ps.name;
11666        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
11667        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
11668        // Retrieve object to delete permissions for shared user later on
11669        final PackageSetting deletedPs;
11670        // reader
11671        synchronized (mPackages) {
11672            deletedPs = mSettings.mPackages.get(packageName);
11673            if (outInfo != null) {
11674                outInfo.removedPackage = packageName;
11675                outInfo.removedUsers = deletedPs != null
11676                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
11677                        : null;
11678            }
11679        }
11680        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11681            removeDataDirsLI(ps.volumeUuid, packageName);
11682            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
11683        }
11684        // writer
11685        synchronized (mPackages) {
11686            if (deletedPs != null) {
11687                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11688                    if (outInfo != null) {
11689                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
11690                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
11691                    }
11692                    updatePermissionsLPw(deletedPs.name, null, 0);
11693                    if (deletedPs.sharedUser != null) {
11694                        // Remove permissions associated with package. Since runtime
11695                        // permissions are per user we have to kill the removed package
11696                        // or packages running under the shared user of the removed
11697                        // package if revoking the permissions requested only by the removed
11698                        // package is successful and this causes a change in gids.
11699                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11700                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
11701                                    userId);
11702                            if (userIdToKill == UserHandle.USER_ALL
11703                                    || userIdToKill >= UserHandle.USER_OWNER) {
11704                                // If gids changed for this user, kill all affected packages.
11705                                mHandler.post(new Runnable() {
11706                                    @Override
11707                                    public void run() {
11708                                        // This has to happen with no lock held.
11709                                        killSettingPackagesForUser(deletedPs, userIdToKill,
11710                                                KILL_APP_REASON_GIDS_CHANGED);
11711                                    }
11712                                });
11713                            break;
11714                            }
11715                        }
11716                    }
11717                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
11718                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
11719                }
11720                // make sure to preserve per-user disabled state if this removal was just
11721                // a downgrade of a system app to the factory package
11722                if (allUserHandles != null && perUserInstalled != null) {
11723                    if (DEBUG_REMOVE) {
11724                        Slog.d(TAG, "Propagating install state across downgrade");
11725                    }
11726                    for (int i = 0; i < allUserHandles.length; i++) {
11727                        if (DEBUG_REMOVE) {
11728                            Slog.d(TAG, "    user " + allUserHandles[i]
11729                                    + " => " + perUserInstalled[i]);
11730                        }
11731                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11732                    }
11733                }
11734            }
11735            // can downgrade to reader
11736            if (writeSettings) {
11737                // Save settings now
11738                mSettings.writeLPr();
11739            }
11740        }
11741        if (outInfo != null) {
11742            // A user ID was deleted here. Go through all users and remove it
11743            // from KeyStore.
11744            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
11745        }
11746    }
11747
11748    static boolean locationIsPrivileged(File path) {
11749        try {
11750            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
11751                    .getCanonicalPath();
11752            return path.getCanonicalPath().startsWith(privilegedAppDir);
11753        } catch (IOException e) {
11754            Slog.e(TAG, "Unable to access code path " + path);
11755        }
11756        return false;
11757    }
11758
11759    /*
11760     * Tries to delete system package.
11761     */
11762    private boolean deleteSystemPackageLI(PackageSetting newPs,
11763            int[] allUserHandles, boolean[] perUserInstalled,
11764            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
11765        final boolean applyUserRestrictions
11766                = (allUserHandles != null) && (perUserInstalled != null);
11767        PackageSetting disabledPs = null;
11768        // Confirm if the system package has been updated
11769        // An updated system app can be deleted. This will also have to restore
11770        // the system pkg from system partition
11771        // reader
11772        synchronized (mPackages) {
11773            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
11774        }
11775        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
11776                + " disabledPs=" + disabledPs);
11777        if (disabledPs == null) {
11778            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
11779            return false;
11780        } else if (DEBUG_REMOVE) {
11781            Slog.d(TAG, "Deleting system pkg from data partition");
11782        }
11783        if (DEBUG_REMOVE) {
11784            if (applyUserRestrictions) {
11785                Slog.d(TAG, "Remembering install states:");
11786                for (int i = 0; i < allUserHandles.length; i++) {
11787                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
11788                }
11789            }
11790        }
11791        // Delete the updated package
11792        outInfo.isRemovedPackageSystemUpdate = true;
11793        if (disabledPs.versionCode < newPs.versionCode) {
11794            // Delete data for downgrades
11795            flags &= ~PackageManager.DELETE_KEEP_DATA;
11796        } else {
11797            // Preserve data by setting flag
11798            flags |= PackageManager.DELETE_KEEP_DATA;
11799        }
11800        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
11801                allUserHandles, perUserInstalled, outInfo, writeSettings);
11802        if (!ret) {
11803            return false;
11804        }
11805        // writer
11806        synchronized (mPackages) {
11807            // Reinstate the old system package
11808            mSettings.enableSystemPackageLPw(newPs.name);
11809            // Remove any native libraries from the upgraded package.
11810            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
11811        }
11812        // Install the system package
11813        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
11814        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
11815        if (locationIsPrivileged(disabledPs.codePath)) {
11816            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11817        }
11818
11819        final PackageParser.Package newPkg;
11820        try {
11821            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
11822        } catch (PackageManagerException e) {
11823            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
11824            return false;
11825        }
11826
11827        // writer
11828        synchronized (mPackages) {
11829            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
11830            updatePermissionsLPw(newPkg.packageName, newPkg,
11831                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
11832            if (applyUserRestrictions) {
11833                if (DEBUG_REMOVE) {
11834                    Slog.d(TAG, "Propagating install state across reinstall");
11835                }
11836                for (int i = 0; i < allUserHandles.length; i++) {
11837                    if (DEBUG_REMOVE) {
11838                        Slog.d(TAG, "    user " + allUserHandles[i]
11839                                + " => " + perUserInstalled[i]);
11840                    }
11841                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11842                }
11843                // Regardless of writeSettings we need to ensure that this restriction
11844                // state propagation is persisted
11845                mSettings.writeAllUsersPackageRestrictionsLPr();
11846            }
11847            // can downgrade to reader here
11848            if (writeSettings) {
11849                mSettings.writeLPr();
11850            }
11851        }
11852        return true;
11853    }
11854
11855    private boolean deleteInstalledPackageLI(PackageSetting ps,
11856            boolean deleteCodeAndResources, int flags,
11857            int[] allUserHandles, boolean[] perUserInstalled,
11858            PackageRemovedInfo outInfo, boolean writeSettings) {
11859        if (outInfo != null) {
11860            outInfo.uid = ps.appId;
11861        }
11862
11863        // Delete package data from internal structures and also remove data if flag is set
11864        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
11865
11866        // Delete application code and resources
11867        if (deleteCodeAndResources && (outInfo != null)) {
11868            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
11869                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
11870                    getAppDexInstructionSets(ps));
11871            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
11872        }
11873        return true;
11874    }
11875
11876    @Override
11877    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
11878            int userId) {
11879        mContext.enforceCallingOrSelfPermission(
11880                android.Manifest.permission.DELETE_PACKAGES, null);
11881        synchronized (mPackages) {
11882            PackageSetting ps = mSettings.mPackages.get(packageName);
11883            if (ps == null) {
11884                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
11885                return false;
11886            }
11887            if (!ps.getInstalled(userId)) {
11888                // Can't block uninstall for an app that is not installed or enabled.
11889                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11890                return false;
11891            }
11892            ps.setBlockUninstall(blockUninstall, userId);
11893            mSettings.writePackageRestrictionsLPr(userId);
11894        }
11895        return true;
11896    }
11897
11898    @Override
11899    public boolean getBlockUninstallForUser(String packageName, int userId) {
11900        synchronized (mPackages) {
11901            PackageSetting ps = mSettings.mPackages.get(packageName);
11902            if (ps == null) {
11903                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11904                return false;
11905            }
11906            return ps.getBlockUninstall(userId);
11907        }
11908    }
11909
11910    /*
11911     * This method handles package deletion in general
11912     */
11913    private boolean deletePackageLI(String packageName, UserHandle user,
11914            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11915            int flags, PackageRemovedInfo outInfo,
11916            boolean writeSettings) {
11917        if (packageName == null) {
11918            Slog.w(TAG, "Attempt to delete null packageName.");
11919            return false;
11920        }
11921        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11922        PackageSetting ps;
11923        boolean dataOnly = false;
11924        int removeUser = -1;
11925        int appId = -1;
11926        synchronized (mPackages) {
11927            ps = mSettings.mPackages.get(packageName);
11928            if (ps == null) {
11929                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11930                return false;
11931            }
11932            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11933                    && user.getIdentifier() != UserHandle.USER_ALL) {
11934                // The caller is asking that the package only be deleted for a single
11935                // user.  To do this, we just mark its uninstalled state and delete
11936                // its data.  If this is a system app, we only allow this to happen if
11937                // they have set the special DELETE_SYSTEM_APP which requests different
11938                // semantics than normal for uninstalling system apps.
11939                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11940                ps.setUserState(user.getIdentifier(),
11941                        COMPONENT_ENABLED_STATE_DEFAULT,
11942                        false, //installed
11943                        true,  //stopped
11944                        true,  //notLaunched
11945                        false, //hidden
11946                        null, null, null,
11947                        false, // blockUninstall
11948                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
11949                if (!isSystemApp(ps)) {
11950                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11951                        // Other user still have this package installed, so all
11952                        // we need to do is clear this user's data and save that
11953                        // it is uninstalled.
11954                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11955                        removeUser = user.getIdentifier();
11956                        appId = ps.appId;
11957                        scheduleWritePackageRestrictionsLocked(removeUser);
11958                    } else {
11959                        // We need to set it back to 'installed' so the uninstall
11960                        // broadcasts will be sent correctly.
11961                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11962                        ps.setInstalled(true, user.getIdentifier());
11963                    }
11964                } else {
11965                    // This is a system app, so we assume that the
11966                    // other users still have this package installed, so all
11967                    // we need to do is clear this user's data and save that
11968                    // it is uninstalled.
11969                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11970                    removeUser = user.getIdentifier();
11971                    appId = ps.appId;
11972                    scheduleWritePackageRestrictionsLocked(removeUser);
11973                }
11974            }
11975        }
11976
11977        if (removeUser >= 0) {
11978            // From above, we determined that we are deleting this only
11979            // for a single user.  Continue the work here.
11980            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11981            if (outInfo != null) {
11982                outInfo.removedPackage = packageName;
11983                outInfo.removedAppId = appId;
11984                outInfo.removedUsers = new int[] {removeUser};
11985            }
11986            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
11987            removeKeystoreDataIfNeeded(removeUser, appId);
11988            schedulePackageCleaning(packageName, removeUser, false);
11989            synchronized (mPackages) {
11990                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
11991                    scheduleWritePackageRestrictionsLocked(removeUser);
11992                }
11993            }
11994            return true;
11995        }
11996
11997        if (dataOnly) {
11998            // Delete application data first
11999            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12000            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12001            return true;
12002        }
12003
12004        boolean ret = false;
12005        if (isSystemApp(ps)) {
12006            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12007            // When an updated system application is deleted we delete the existing resources as well and
12008            // fall back to existing code in system partition
12009            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12010                    flags, outInfo, writeSettings);
12011        } else {
12012            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12013            // Kill application pre-emptively especially for apps on sd.
12014            killApplication(packageName, ps.appId, "uninstall pkg");
12015            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12016                    allUserHandles, perUserInstalled,
12017                    outInfo, writeSettings);
12018        }
12019
12020        return ret;
12021    }
12022
12023    private final class ClearStorageConnection implements ServiceConnection {
12024        IMediaContainerService mContainerService;
12025
12026        @Override
12027        public void onServiceConnected(ComponentName name, IBinder service) {
12028            synchronized (this) {
12029                mContainerService = IMediaContainerService.Stub.asInterface(service);
12030                notifyAll();
12031            }
12032        }
12033
12034        @Override
12035        public void onServiceDisconnected(ComponentName name) {
12036        }
12037    }
12038
12039    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12040        final boolean mounted;
12041        if (Environment.isExternalStorageEmulated()) {
12042            mounted = true;
12043        } else {
12044            final String status = Environment.getExternalStorageState();
12045
12046            mounted = status.equals(Environment.MEDIA_MOUNTED)
12047                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12048        }
12049
12050        if (!mounted) {
12051            return;
12052        }
12053
12054        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12055        int[] users;
12056        if (userId == UserHandle.USER_ALL) {
12057            users = sUserManager.getUserIds();
12058        } else {
12059            users = new int[] { userId };
12060        }
12061        final ClearStorageConnection conn = new ClearStorageConnection();
12062        if (mContext.bindServiceAsUser(
12063                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12064            try {
12065                for (int curUser : users) {
12066                    long timeout = SystemClock.uptimeMillis() + 5000;
12067                    synchronized (conn) {
12068                        long now = SystemClock.uptimeMillis();
12069                        while (conn.mContainerService == null && now < timeout) {
12070                            try {
12071                                conn.wait(timeout - now);
12072                            } catch (InterruptedException e) {
12073                            }
12074                        }
12075                    }
12076                    if (conn.mContainerService == null) {
12077                        return;
12078                    }
12079
12080                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12081                    clearDirectory(conn.mContainerService,
12082                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12083                    if (allData) {
12084                        clearDirectory(conn.mContainerService,
12085                                userEnv.buildExternalStorageAppDataDirs(packageName));
12086                        clearDirectory(conn.mContainerService,
12087                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12088                    }
12089                }
12090            } finally {
12091                mContext.unbindService(conn);
12092            }
12093        }
12094    }
12095
12096    @Override
12097    public void clearApplicationUserData(final String packageName,
12098            final IPackageDataObserver observer, final int userId) {
12099        mContext.enforceCallingOrSelfPermission(
12100                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12101        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12102        // Queue up an async operation since the package deletion may take a little while.
12103        mHandler.post(new Runnable() {
12104            public void run() {
12105                mHandler.removeCallbacks(this);
12106                final boolean succeeded;
12107                synchronized (mInstallLock) {
12108                    succeeded = clearApplicationUserDataLI(packageName, userId);
12109                }
12110                clearExternalStorageDataSync(packageName, userId, true);
12111                if (succeeded) {
12112                    // invoke DeviceStorageMonitor's update method to clear any notifications
12113                    DeviceStorageMonitorInternal
12114                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12115                    if (dsm != null) {
12116                        dsm.checkMemory();
12117                    }
12118                }
12119                if(observer != null) {
12120                    try {
12121                        observer.onRemoveCompleted(packageName, succeeded);
12122                    } catch (RemoteException e) {
12123                        Log.i(TAG, "Observer no longer exists.");
12124                    }
12125                } //end if observer
12126            } //end run
12127        });
12128    }
12129
12130    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12131        if (packageName == null) {
12132            Slog.w(TAG, "Attempt to delete null packageName.");
12133            return false;
12134        }
12135
12136        // Try finding details about the requested package
12137        PackageParser.Package pkg;
12138        synchronized (mPackages) {
12139            pkg = mPackages.get(packageName);
12140            if (pkg == null) {
12141                final PackageSetting ps = mSettings.mPackages.get(packageName);
12142                if (ps != null) {
12143                    pkg = ps.pkg;
12144                }
12145            }
12146        }
12147
12148        if (pkg == null) {
12149            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12150        }
12151
12152        // Always delete data directories for package, even if we found no other
12153        // record of app. This helps users recover from UID mismatches without
12154        // resorting to a full data wipe.
12155        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12156        if (retCode < 0) {
12157            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12158            return false;
12159        }
12160
12161        if (pkg == null) {
12162            return false;
12163        }
12164
12165        if (pkg != null && pkg.applicationInfo != null) {
12166            final int appId = pkg.applicationInfo.uid;
12167            removeKeystoreDataIfNeeded(userId, appId);
12168        }
12169
12170        // Create a native library symlink only if we have native libraries
12171        // and if the native libraries are 32 bit libraries. We do not provide
12172        // this symlink for 64 bit libraries.
12173        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
12174                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12175            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12176            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12177                    nativeLibPath, userId) < 0) {
12178                Slog.w(TAG, "Failed linking native library dir");
12179                return false;
12180            }
12181        }
12182
12183        return true;
12184    }
12185
12186    /**
12187     * Remove entries from the keystore daemon. Will only remove it if the
12188     * {@code appId} is valid.
12189     */
12190    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12191        if (appId < 0) {
12192            return;
12193        }
12194
12195        final KeyStore keyStore = KeyStore.getInstance();
12196        if (keyStore != null) {
12197            if (userId == UserHandle.USER_ALL) {
12198                for (final int individual : sUserManager.getUserIds()) {
12199                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12200                }
12201            } else {
12202                keyStore.clearUid(UserHandle.getUid(userId, appId));
12203            }
12204        } else {
12205            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12206        }
12207    }
12208
12209    @Override
12210    public void deleteApplicationCacheFiles(final String packageName,
12211            final IPackageDataObserver observer) {
12212        mContext.enforceCallingOrSelfPermission(
12213                android.Manifest.permission.DELETE_CACHE_FILES, null);
12214        // Queue up an async operation since the package deletion may take a little while.
12215        final int userId = UserHandle.getCallingUserId();
12216        mHandler.post(new Runnable() {
12217            public void run() {
12218                mHandler.removeCallbacks(this);
12219                final boolean succeded;
12220                synchronized (mInstallLock) {
12221                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12222                }
12223                clearExternalStorageDataSync(packageName, userId, false);
12224                if(observer != null) {
12225                    try {
12226                        observer.onRemoveCompleted(packageName, succeded);
12227                    } catch (RemoteException e) {
12228                        Log.i(TAG, "Observer no longer exists.");
12229                    }
12230                } //end if observer
12231            } //end run
12232        });
12233    }
12234
12235    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12236        if (packageName == null) {
12237            Slog.w(TAG, "Attempt to delete null packageName.");
12238            return false;
12239        }
12240        PackageParser.Package p;
12241        synchronized (mPackages) {
12242            p = mPackages.get(packageName);
12243        }
12244        if (p == null) {
12245            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12246            return false;
12247        }
12248        final ApplicationInfo applicationInfo = p.applicationInfo;
12249        if (applicationInfo == null) {
12250            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12251            return false;
12252        }
12253        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12254        if (retCode < 0) {
12255            Slog.w(TAG, "Couldn't remove cache files for package: "
12256                       + packageName + " u" + userId);
12257            return false;
12258        }
12259        return true;
12260    }
12261
12262    @Override
12263    public void getPackageSizeInfo(final String packageName, int userHandle,
12264            final IPackageStatsObserver observer) {
12265        mContext.enforceCallingOrSelfPermission(
12266                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12267        if (packageName == null) {
12268            throw new IllegalArgumentException("Attempt to get size of null packageName");
12269        }
12270
12271        PackageStats stats = new PackageStats(packageName, userHandle);
12272
12273        /*
12274         * Queue up an async operation since the package measurement may take a
12275         * little while.
12276         */
12277        Message msg = mHandler.obtainMessage(INIT_COPY);
12278        msg.obj = new MeasureParams(stats, observer);
12279        mHandler.sendMessage(msg);
12280    }
12281
12282    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12283            PackageStats pStats) {
12284        if (packageName == null) {
12285            Slog.w(TAG, "Attempt to get size of null packageName.");
12286            return false;
12287        }
12288        PackageParser.Package p;
12289        boolean dataOnly = false;
12290        String libDirRoot = null;
12291        String asecPath = null;
12292        PackageSetting ps = null;
12293        synchronized (mPackages) {
12294            p = mPackages.get(packageName);
12295            ps = mSettings.mPackages.get(packageName);
12296            if(p == null) {
12297                dataOnly = true;
12298                if((ps == null) || (ps.pkg == null)) {
12299                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12300                    return false;
12301                }
12302                p = ps.pkg;
12303            }
12304            if (ps != null) {
12305                libDirRoot = ps.legacyNativeLibraryPathString;
12306            }
12307            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12308                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12309                if (secureContainerId != null) {
12310                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12311                }
12312            }
12313        }
12314        String publicSrcDir = null;
12315        if(!dataOnly) {
12316            final ApplicationInfo applicationInfo = p.applicationInfo;
12317            if (applicationInfo == null) {
12318                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12319                return false;
12320            }
12321            if (p.isForwardLocked()) {
12322                publicSrcDir = applicationInfo.getBaseResourcePath();
12323            }
12324        }
12325        // TODO: extend to measure size of split APKs
12326        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12327        // not just the first level.
12328        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12329        // just the primary.
12330        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12331        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
12332                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12333        if (res < 0) {
12334            return false;
12335        }
12336
12337        // Fix-up for forward-locked applications in ASEC containers.
12338        if (!isExternal(p)) {
12339            pStats.codeSize += pStats.externalCodeSize;
12340            pStats.externalCodeSize = 0L;
12341        }
12342
12343        return true;
12344    }
12345
12346
12347    @Override
12348    public void addPackageToPreferred(String packageName) {
12349        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12350    }
12351
12352    @Override
12353    public void removePackageFromPreferred(String packageName) {
12354        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12355    }
12356
12357    @Override
12358    public List<PackageInfo> getPreferredPackages(int flags) {
12359        return new ArrayList<PackageInfo>();
12360    }
12361
12362    private int getUidTargetSdkVersionLockedLPr(int uid) {
12363        Object obj = mSettings.getUserIdLPr(uid);
12364        if (obj instanceof SharedUserSetting) {
12365            final SharedUserSetting sus = (SharedUserSetting) obj;
12366            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12367            final Iterator<PackageSetting> it = sus.packages.iterator();
12368            while (it.hasNext()) {
12369                final PackageSetting ps = it.next();
12370                if (ps.pkg != null) {
12371                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12372                    if (v < vers) vers = v;
12373                }
12374            }
12375            return vers;
12376        } else if (obj instanceof PackageSetting) {
12377            final PackageSetting ps = (PackageSetting) obj;
12378            if (ps.pkg != null) {
12379                return ps.pkg.applicationInfo.targetSdkVersion;
12380            }
12381        }
12382        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12383    }
12384
12385    @Override
12386    public void addPreferredActivity(IntentFilter filter, int match,
12387            ComponentName[] set, ComponentName activity, int userId) {
12388        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12389                "Adding preferred");
12390    }
12391
12392    private void addPreferredActivityInternal(IntentFilter filter, int match,
12393            ComponentName[] set, ComponentName activity, boolean always, int userId,
12394            String opname) {
12395        // writer
12396        int callingUid = Binder.getCallingUid();
12397        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12398        if (filter.countActions() == 0) {
12399            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12400            return;
12401        }
12402        synchronized (mPackages) {
12403            if (mContext.checkCallingOrSelfPermission(
12404                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12405                    != PackageManager.PERMISSION_GRANTED) {
12406                if (getUidTargetSdkVersionLockedLPr(callingUid)
12407                        < Build.VERSION_CODES.FROYO) {
12408                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12409                            + callingUid);
12410                    return;
12411                }
12412                mContext.enforceCallingOrSelfPermission(
12413                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12414            }
12415
12416            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12417            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12418                    + userId + ":");
12419            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12420            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12421            scheduleWritePackageRestrictionsLocked(userId);
12422        }
12423    }
12424
12425    @Override
12426    public void replacePreferredActivity(IntentFilter filter, int match,
12427            ComponentName[] set, ComponentName activity, int userId) {
12428        if (filter.countActions() != 1) {
12429            throw new IllegalArgumentException(
12430                    "replacePreferredActivity expects filter to have only 1 action.");
12431        }
12432        if (filter.countDataAuthorities() != 0
12433                || filter.countDataPaths() != 0
12434                || filter.countDataSchemes() > 1
12435                || filter.countDataTypes() != 0) {
12436            throw new IllegalArgumentException(
12437                    "replacePreferredActivity expects filter to have no data authorities, " +
12438                    "paths, or types; and at most one scheme.");
12439        }
12440
12441        final int callingUid = Binder.getCallingUid();
12442        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12443        synchronized (mPackages) {
12444            if (mContext.checkCallingOrSelfPermission(
12445                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12446                    != PackageManager.PERMISSION_GRANTED) {
12447                if (getUidTargetSdkVersionLockedLPr(callingUid)
12448                        < Build.VERSION_CODES.FROYO) {
12449                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12450                            + Binder.getCallingUid());
12451                    return;
12452                }
12453                mContext.enforceCallingOrSelfPermission(
12454                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12455            }
12456
12457            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12458            if (pir != null) {
12459                // Get all of the existing entries that exactly match this filter.
12460                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
12461                if (existing != null && existing.size() == 1) {
12462                    PreferredActivity cur = existing.get(0);
12463                    if (DEBUG_PREFERRED) {
12464                        Slog.i(TAG, "Checking replace of preferred:");
12465                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12466                        if (!cur.mPref.mAlways) {
12467                            Slog.i(TAG, "  -- CUR; not mAlways!");
12468                        } else {
12469                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
12470                            Slog.i(TAG, "  -- CUR: mSet="
12471                                    + Arrays.toString(cur.mPref.mSetComponents));
12472                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
12473                            Slog.i(TAG, "  -- NEW: mMatch="
12474                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
12475                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
12476                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
12477                        }
12478                    }
12479                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
12480                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
12481                            && cur.mPref.sameSet(set)) {
12482                        // Setting the preferred activity to what it happens to be already
12483                        if (DEBUG_PREFERRED) {
12484                            Slog.i(TAG, "Replacing with same preferred activity "
12485                                    + cur.mPref.mShortComponent + " for user "
12486                                    + userId + ":");
12487                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12488                        }
12489                        return;
12490                    }
12491                }
12492
12493                if (existing != null) {
12494                    if (DEBUG_PREFERRED) {
12495                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
12496                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12497                    }
12498                    for (int i = 0; i < existing.size(); i++) {
12499                        PreferredActivity pa = existing.get(i);
12500                        if (DEBUG_PREFERRED) {
12501                            Slog.i(TAG, "Removing existing preferred activity "
12502                                    + pa.mPref.mComponent + ":");
12503                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
12504                        }
12505                        pir.removeFilter(pa);
12506                    }
12507                }
12508            }
12509            addPreferredActivityInternal(filter, match, set, activity, true, userId,
12510                    "Replacing preferred");
12511        }
12512    }
12513
12514    @Override
12515    public void clearPackagePreferredActivities(String packageName) {
12516        final int uid = Binder.getCallingUid();
12517        // writer
12518        synchronized (mPackages) {
12519            PackageParser.Package pkg = mPackages.get(packageName);
12520            if (pkg == null || pkg.applicationInfo.uid != uid) {
12521                if (mContext.checkCallingOrSelfPermission(
12522                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12523                        != PackageManager.PERMISSION_GRANTED) {
12524                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
12525                            < Build.VERSION_CODES.FROYO) {
12526                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
12527                                + Binder.getCallingUid());
12528                        return;
12529                    }
12530                    mContext.enforceCallingOrSelfPermission(
12531                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12532                }
12533            }
12534
12535            int user = UserHandle.getCallingUserId();
12536            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
12537                scheduleWritePackageRestrictionsLocked(user);
12538            }
12539        }
12540    }
12541
12542    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12543    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
12544        ArrayList<PreferredActivity> removed = null;
12545        boolean changed = false;
12546        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12547            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
12548            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12549            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
12550                continue;
12551            }
12552            Iterator<PreferredActivity> it = pir.filterIterator();
12553            while (it.hasNext()) {
12554                PreferredActivity pa = it.next();
12555                // Mark entry for removal only if it matches the package name
12556                // and the entry is of type "always".
12557                if (packageName == null ||
12558                        (pa.mPref.mComponent.getPackageName().equals(packageName)
12559                                && pa.mPref.mAlways)) {
12560                    if (removed == null) {
12561                        removed = new ArrayList<PreferredActivity>();
12562                    }
12563                    removed.add(pa);
12564                }
12565            }
12566            if (removed != null) {
12567                for (int j=0; j<removed.size(); j++) {
12568                    PreferredActivity pa = removed.get(j);
12569                    pir.removeFilter(pa);
12570                }
12571                changed = true;
12572            }
12573        }
12574        return changed;
12575    }
12576
12577    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12578    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
12579        if (userId == UserHandle.USER_ALL) {
12580            mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds());
12581            for (int oneUserId : sUserManager.getUserIds()) {
12582                scheduleWritePackageRestrictionsLocked(oneUserId);
12583            }
12584        } else {
12585            mSettings.removeIntentFilterVerificationLPw(packageName, userId);
12586            scheduleWritePackageRestrictionsLocked(userId);
12587        }
12588    }
12589
12590    @Override
12591    public void resetPreferredActivities(int userId) {
12592        /* TODO: Actually use userId. Why is it being passed in? */
12593        mContext.enforceCallingOrSelfPermission(
12594                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12595        // writer
12596        synchronized (mPackages) {
12597            int user = UserHandle.getCallingUserId();
12598            clearPackagePreferredActivitiesLPw(null, user);
12599            mSettings.readDefaultPreferredAppsLPw(this, user);
12600            scheduleWritePackageRestrictionsLocked(user);
12601        }
12602    }
12603
12604    @Override
12605    public int getPreferredActivities(List<IntentFilter> outFilters,
12606            List<ComponentName> outActivities, String packageName) {
12607
12608        int num = 0;
12609        final int userId = UserHandle.getCallingUserId();
12610        // reader
12611        synchronized (mPackages) {
12612            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12613            if (pir != null) {
12614                final Iterator<PreferredActivity> it = pir.filterIterator();
12615                while (it.hasNext()) {
12616                    final PreferredActivity pa = it.next();
12617                    if (packageName == null
12618                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
12619                                    && pa.mPref.mAlways)) {
12620                        if (outFilters != null) {
12621                            outFilters.add(new IntentFilter(pa));
12622                        }
12623                        if (outActivities != null) {
12624                            outActivities.add(pa.mPref.mComponent);
12625                        }
12626                    }
12627                }
12628            }
12629        }
12630
12631        return num;
12632    }
12633
12634    @Override
12635    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
12636            int userId) {
12637        int callingUid = Binder.getCallingUid();
12638        if (callingUid != Process.SYSTEM_UID) {
12639            throw new SecurityException(
12640                    "addPersistentPreferredActivity can only be run by the system");
12641        }
12642        if (filter.countActions() == 0) {
12643            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12644            return;
12645        }
12646        synchronized (mPackages) {
12647            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
12648                    " :");
12649            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12650            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
12651                    new PersistentPreferredActivity(filter, activity));
12652            scheduleWritePackageRestrictionsLocked(userId);
12653        }
12654    }
12655
12656    @Override
12657    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
12658        int callingUid = Binder.getCallingUid();
12659        if (callingUid != Process.SYSTEM_UID) {
12660            throw new SecurityException(
12661                    "clearPackagePersistentPreferredActivities can only be run by the system");
12662        }
12663        ArrayList<PersistentPreferredActivity> removed = null;
12664        boolean changed = false;
12665        synchronized (mPackages) {
12666            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
12667                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
12668                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
12669                        .valueAt(i);
12670                if (userId != thisUserId) {
12671                    continue;
12672                }
12673                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
12674                while (it.hasNext()) {
12675                    PersistentPreferredActivity ppa = it.next();
12676                    // Mark entry for removal only if it matches the package name.
12677                    if (ppa.mComponent.getPackageName().equals(packageName)) {
12678                        if (removed == null) {
12679                            removed = new ArrayList<PersistentPreferredActivity>();
12680                        }
12681                        removed.add(ppa);
12682                    }
12683                }
12684                if (removed != null) {
12685                    for (int j=0; j<removed.size(); j++) {
12686                        PersistentPreferredActivity ppa = removed.get(j);
12687                        ppir.removeFilter(ppa);
12688                    }
12689                    changed = true;
12690                }
12691            }
12692
12693            if (changed) {
12694                scheduleWritePackageRestrictionsLocked(userId);
12695            }
12696        }
12697    }
12698
12699    /**
12700     * Non-Binder method, support for the backup/restore mechanism: write the
12701     * full set of preferred activities in its canonical XML format.  Returns true
12702     * on success; false otherwise.
12703     */
12704    @Override
12705    public byte[] getPreferredActivityBackup(int userId) {
12706        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
12707            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
12708        }
12709
12710        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
12711        try {
12712            final XmlSerializer serializer = new FastXmlSerializer();
12713            serializer.setOutput(dataStream, "utf-8");
12714            serializer.startDocument(null, true);
12715            serializer.startTag(null, TAG_PREFERRED_BACKUP);
12716
12717            synchronized (mPackages) {
12718                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
12719            }
12720
12721            serializer.endTag(null, TAG_PREFERRED_BACKUP);
12722            serializer.endDocument();
12723            serializer.flush();
12724        } catch (Exception e) {
12725            if (DEBUG_BACKUP) {
12726                Slog.e(TAG, "Unable to write preferred activities for backup", e);
12727            }
12728            return null;
12729        }
12730
12731        return dataStream.toByteArray();
12732    }
12733
12734    @Override
12735    public void restorePreferredActivities(byte[] backup, int userId) {
12736        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
12737            throw new SecurityException("Only the system may call restorePreferredActivities()");
12738        }
12739
12740        try {
12741            final XmlPullParser parser = Xml.newPullParser();
12742            parser.setInput(new ByteArrayInputStream(backup), null);
12743
12744            int type;
12745            while ((type = parser.next()) != XmlPullParser.START_TAG
12746                    && type != XmlPullParser.END_DOCUMENT) {
12747            }
12748            if (type != XmlPullParser.START_TAG) {
12749                // oops didn't find a start tag?!
12750                if (DEBUG_BACKUP) {
12751                    Slog.e(TAG, "Didn't find start tag during restore");
12752                }
12753                return;
12754            }
12755
12756            // this is supposed to be TAG_PREFERRED_BACKUP
12757            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
12758                if (DEBUG_BACKUP) {
12759                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
12760                }
12761                return;
12762            }
12763
12764            // skip interfering stuff, then we're aligned with the backing implementation
12765            while ((type = parser.next()) == XmlPullParser.TEXT) { }
12766            synchronized (mPackages) {
12767                mSettings.readPreferredActivitiesLPw(parser, userId);
12768            }
12769        } catch (Exception e) {
12770            if (DEBUG_BACKUP) {
12771                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
12772            }
12773        }
12774    }
12775
12776    @Override
12777    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
12778            int sourceUserId, int targetUserId, int flags) {
12779        mContext.enforceCallingOrSelfPermission(
12780                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12781        int callingUid = Binder.getCallingUid();
12782        enforceOwnerRights(ownerPackage, callingUid);
12783        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12784        if (intentFilter.countActions() == 0) {
12785            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
12786            return;
12787        }
12788        synchronized (mPackages) {
12789            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
12790                    ownerPackage, targetUserId, flags);
12791            CrossProfileIntentResolver resolver =
12792                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12793            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
12794            // We have all those whose filter is equal. Now checking if the rest is equal as well.
12795            if (existing != null) {
12796                int size = existing.size();
12797                for (int i = 0; i < size; i++) {
12798                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
12799                        return;
12800                    }
12801                }
12802            }
12803            resolver.addFilter(newFilter);
12804            scheduleWritePackageRestrictionsLocked(sourceUserId);
12805        }
12806    }
12807
12808    @Override
12809    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
12810        mContext.enforceCallingOrSelfPermission(
12811                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12812        int callingUid = Binder.getCallingUid();
12813        enforceOwnerRights(ownerPackage, callingUid);
12814        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12815        synchronized (mPackages) {
12816            CrossProfileIntentResolver resolver =
12817                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12818            ArraySet<CrossProfileIntentFilter> set =
12819                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
12820            for (CrossProfileIntentFilter filter : set) {
12821                if (filter.getOwnerPackage().equals(ownerPackage)) {
12822                    resolver.removeFilter(filter);
12823                }
12824            }
12825            scheduleWritePackageRestrictionsLocked(sourceUserId);
12826        }
12827    }
12828
12829    // Enforcing that callingUid is owning pkg on userId
12830    private void enforceOwnerRights(String pkg, int callingUid) {
12831        // The system owns everything.
12832        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
12833            return;
12834        }
12835        int callingUserId = UserHandle.getUserId(callingUid);
12836        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
12837        if (pi == null) {
12838            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
12839                    + callingUserId);
12840        }
12841        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
12842            throw new SecurityException("Calling uid " + callingUid
12843                    + " does not own package " + pkg);
12844        }
12845    }
12846
12847    @Override
12848    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
12849        Intent intent = new Intent(Intent.ACTION_MAIN);
12850        intent.addCategory(Intent.CATEGORY_HOME);
12851
12852        final int callingUserId = UserHandle.getCallingUserId();
12853        List<ResolveInfo> list = queryIntentActivities(intent, null,
12854                PackageManager.GET_META_DATA, callingUserId);
12855        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
12856                true, false, false, callingUserId);
12857
12858        allHomeCandidates.clear();
12859        if (list != null) {
12860            for (ResolveInfo ri : list) {
12861                allHomeCandidates.add(ri);
12862            }
12863        }
12864        return (preferred == null || preferred.activityInfo == null)
12865                ? null
12866                : new ComponentName(preferred.activityInfo.packageName,
12867                        preferred.activityInfo.name);
12868    }
12869
12870    @Override
12871    public void setApplicationEnabledSetting(String appPackageName,
12872            int newState, int flags, int userId, String callingPackage) {
12873        if (!sUserManager.exists(userId)) return;
12874        if (callingPackage == null) {
12875            callingPackage = Integer.toString(Binder.getCallingUid());
12876        }
12877        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
12878    }
12879
12880    @Override
12881    public void setComponentEnabledSetting(ComponentName componentName,
12882            int newState, int flags, int userId) {
12883        if (!sUserManager.exists(userId)) return;
12884        setEnabledSetting(componentName.getPackageName(),
12885                componentName.getClassName(), newState, flags, userId, null);
12886    }
12887
12888    private void setEnabledSetting(final String packageName, String className, int newState,
12889            final int flags, int userId, String callingPackage) {
12890        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
12891              || newState == COMPONENT_ENABLED_STATE_ENABLED
12892              || newState == COMPONENT_ENABLED_STATE_DISABLED
12893              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
12894              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
12895            throw new IllegalArgumentException("Invalid new component state: "
12896                    + newState);
12897        }
12898        PackageSetting pkgSetting;
12899        final int uid = Binder.getCallingUid();
12900        final int permission = mContext.checkCallingOrSelfPermission(
12901                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12902        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
12903        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12904        boolean sendNow = false;
12905        boolean isApp = (className == null);
12906        String componentName = isApp ? packageName : className;
12907        int packageUid = -1;
12908        ArrayList<String> components;
12909
12910        // writer
12911        synchronized (mPackages) {
12912            pkgSetting = mSettings.mPackages.get(packageName);
12913            if (pkgSetting == null) {
12914                if (className == null) {
12915                    throw new IllegalArgumentException(
12916                            "Unknown package: " + packageName);
12917                }
12918                throw new IllegalArgumentException(
12919                        "Unknown component: " + packageName
12920                        + "/" + className);
12921            }
12922            // Allow root and verify that userId is not being specified by a different user
12923            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
12924                throw new SecurityException(
12925                        "Permission Denial: attempt to change component state from pid="
12926                        + Binder.getCallingPid()
12927                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
12928            }
12929            if (className == null) {
12930                // We're dealing with an application/package level state change
12931                if (pkgSetting.getEnabled(userId) == newState) {
12932                    // Nothing to do
12933                    return;
12934                }
12935                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
12936                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
12937                    // Don't care about who enables an app.
12938                    callingPackage = null;
12939                }
12940                pkgSetting.setEnabled(newState, userId, callingPackage);
12941                // pkgSetting.pkg.mSetEnabled = newState;
12942            } else {
12943                // We're dealing with a component level state change
12944                // First, verify that this is a valid class name.
12945                PackageParser.Package pkg = pkgSetting.pkg;
12946                if (pkg == null || !pkg.hasComponentClassName(className)) {
12947                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
12948                        throw new IllegalArgumentException("Component class " + className
12949                                + " does not exist in " + packageName);
12950                    } else {
12951                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
12952                                + className + " does not exist in " + packageName);
12953                    }
12954                }
12955                switch (newState) {
12956                case COMPONENT_ENABLED_STATE_ENABLED:
12957                    if (!pkgSetting.enableComponentLPw(className, userId)) {
12958                        return;
12959                    }
12960                    break;
12961                case COMPONENT_ENABLED_STATE_DISABLED:
12962                    if (!pkgSetting.disableComponentLPw(className, userId)) {
12963                        return;
12964                    }
12965                    break;
12966                case COMPONENT_ENABLED_STATE_DEFAULT:
12967                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
12968                        return;
12969                    }
12970                    break;
12971                default:
12972                    Slog.e(TAG, "Invalid new component state: " + newState);
12973                    return;
12974                }
12975            }
12976            scheduleWritePackageRestrictionsLocked(userId);
12977            components = mPendingBroadcasts.get(userId, packageName);
12978            final boolean newPackage = components == null;
12979            if (newPackage) {
12980                components = new ArrayList<String>();
12981            }
12982            if (!components.contains(componentName)) {
12983                components.add(componentName);
12984            }
12985            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12986                sendNow = true;
12987                // Purge entry from pending broadcast list if another one exists already
12988                // since we are sending one right away.
12989                mPendingBroadcasts.remove(userId, packageName);
12990            } else {
12991                if (newPackage) {
12992                    mPendingBroadcasts.put(userId, packageName, components);
12993                }
12994                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12995                    // Schedule a message
12996                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12997                }
12998            }
12999        }
13000
13001        long callingId = Binder.clearCallingIdentity();
13002        try {
13003            if (sendNow) {
13004                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13005                sendPackageChangedBroadcast(packageName,
13006                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13007            }
13008        } finally {
13009            Binder.restoreCallingIdentity(callingId);
13010        }
13011    }
13012
13013    private void sendPackageChangedBroadcast(String packageName,
13014            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13015        if (DEBUG_INSTALL)
13016            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13017                    + componentNames);
13018        Bundle extras = new Bundle(4);
13019        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13020        String nameList[] = new String[componentNames.size()];
13021        componentNames.toArray(nameList);
13022        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13023        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13024        extras.putInt(Intent.EXTRA_UID, packageUid);
13025        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13026                new int[] {UserHandle.getUserId(packageUid)});
13027    }
13028
13029    @Override
13030    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13031        if (!sUserManager.exists(userId)) return;
13032        final int uid = Binder.getCallingUid();
13033        final int permission = mContext.checkCallingOrSelfPermission(
13034                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13035        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13036        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13037        // writer
13038        synchronized (mPackages) {
13039            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
13040                    uid, userId)) {
13041                scheduleWritePackageRestrictionsLocked(userId);
13042            }
13043        }
13044    }
13045
13046    @Override
13047    public String getInstallerPackageName(String packageName) {
13048        // reader
13049        synchronized (mPackages) {
13050            return mSettings.getInstallerPackageNameLPr(packageName);
13051        }
13052    }
13053
13054    @Override
13055    public int getApplicationEnabledSetting(String packageName, int userId) {
13056        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13057        int uid = Binder.getCallingUid();
13058        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13059        // reader
13060        synchronized (mPackages) {
13061            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13062        }
13063    }
13064
13065    @Override
13066    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13067        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13068        int uid = Binder.getCallingUid();
13069        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13070        // reader
13071        synchronized (mPackages) {
13072            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13073        }
13074    }
13075
13076    @Override
13077    public void enterSafeMode() {
13078        enforceSystemOrRoot("Only the system can request entering safe mode");
13079
13080        if (!mSystemReady) {
13081            mSafeMode = true;
13082        }
13083    }
13084
13085    @Override
13086    public void systemReady() {
13087        mSystemReady = true;
13088
13089        // Read the compatibilty setting when the system is ready.
13090        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13091                mContext.getContentResolver(),
13092                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13093        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13094        if (DEBUG_SETTINGS) {
13095            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13096        }
13097
13098        synchronized (mPackages) {
13099            // Verify that all of the preferred activity components actually
13100            // exist.  It is possible for applications to be updated and at
13101            // that point remove a previously declared activity component that
13102            // had been set as a preferred activity.  We try to clean this up
13103            // the next time we encounter that preferred activity, but it is
13104            // possible for the user flow to never be able to return to that
13105            // situation so here we do a sanity check to make sure we haven't
13106            // left any junk around.
13107            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13108            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13109                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13110                removed.clear();
13111                for (PreferredActivity pa : pir.filterSet()) {
13112                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13113                        removed.add(pa);
13114                    }
13115                }
13116                if (removed.size() > 0) {
13117                    for (int r=0; r<removed.size(); r++) {
13118                        PreferredActivity pa = removed.get(r);
13119                        Slog.w(TAG, "Removing dangling preferred activity: "
13120                                + pa.mPref.mComponent);
13121                        pir.removeFilter(pa);
13122                    }
13123                    mSettings.writePackageRestrictionsLPr(
13124                            mSettings.mPreferredActivities.keyAt(i));
13125                }
13126            }
13127        }
13128        sUserManager.systemReady();
13129
13130        // Kick off any messages waiting for system ready
13131        if (mPostSystemReadyMessages != null) {
13132            for (Message msg : mPostSystemReadyMessages) {
13133                msg.sendToTarget();
13134            }
13135            mPostSystemReadyMessages = null;
13136        }
13137
13138        // Watch for external volumes that come and go over time
13139        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13140        storage.registerListener(mStorageListener);
13141
13142        mInstallerService.systemReady();
13143    }
13144
13145    @Override
13146    public boolean isSafeMode() {
13147        return mSafeMode;
13148    }
13149
13150    @Override
13151    public boolean hasSystemUidErrors() {
13152        return mHasSystemUidErrors;
13153    }
13154
13155    static String arrayToString(int[] array) {
13156        StringBuffer buf = new StringBuffer(128);
13157        buf.append('[');
13158        if (array != null) {
13159            for (int i=0; i<array.length; i++) {
13160                if (i > 0) buf.append(", ");
13161                buf.append(array[i]);
13162            }
13163        }
13164        buf.append(']');
13165        return buf.toString();
13166    }
13167
13168    static class DumpState {
13169        public static final int DUMP_LIBS = 1 << 0;
13170        public static final int DUMP_FEATURES = 1 << 1;
13171        public static final int DUMP_RESOLVERS = 1 << 2;
13172        public static final int DUMP_PERMISSIONS = 1 << 3;
13173        public static final int DUMP_PACKAGES = 1 << 4;
13174        public static final int DUMP_SHARED_USERS = 1 << 5;
13175        public static final int DUMP_MESSAGES = 1 << 6;
13176        public static final int DUMP_PROVIDERS = 1 << 7;
13177        public static final int DUMP_VERIFIERS = 1 << 8;
13178        public static final int DUMP_PREFERRED = 1 << 9;
13179        public static final int DUMP_PREFERRED_XML = 1 << 10;
13180        public static final int DUMP_KEYSETS = 1 << 11;
13181        public static final int DUMP_VERSION = 1 << 12;
13182        public static final int DUMP_INSTALLS = 1 << 13;
13183        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13184        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13185
13186        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13187
13188        private int mTypes;
13189
13190        private int mOptions;
13191
13192        private boolean mTitlePrinted;
13193
13194        private SharedUserSetting mSharedUser;
13195
13196        public boolean isDumping(int type) {
13197            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13198                return true;
13199            }
13200
13201            return (mTypes & type) != 0;
13202        }
13203
13204        public void setDump(int type) {
13205            mTypes |= type;
13206        }
13207
13208        public boolean isOptionEnabled(int option) {
13209            return (mOptions & option) != 0;
13210        }
13211
13212        public void setOptionEnabled(int option) {
13213            mOptions |= option;
13214        }
13215
13216        public boolean onTitlePrinted() {
13217            final boolean printed = mTitlePrinted;
13218            mTitlePrinted = true;
13219            return printed;
13220        }
13221
13222        public boolean getTitlePrinted() {
13223            return mTitlePrinted;
13224        }
13225
13226        public void setTitlePrinted(boolean enabled) {
13227            mTitlePrinted = enabled;
13228        }
13229
13230        public SharedUserSetting getSharedUser() {
13231            return mSharedUser;
13232        }
13233
13234        public void setSharedUser(SharedUserSetting user) {
13235            mSharedUser = user;
13236        }
13237    }
13238
13239    @Override
13240    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13241        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13242                != PackageManager.PERMISSION_GRANTED) {
13243            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13244                    + Binder.getCallingPid()
13245                    + ", uid=" + Binder.getCallingUid()
13246                    + " without permission "
13247                    + android.Manifest.permission.DUMP);
13248            return;
13249        }
13250
13251        DumpState dumpState = new DumpState();
13252        boolean fullPreferred = false;
13253        boolean checkin = false;
13254
13255        String packageName = null;
13256
13257        int opti = 0;
13258        while (opti < args.length) {
13259            String opt = args[opti];
13260            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13261                break;
13262            }
13263            opti++;
13264
13265            if ("-a".equals(opt)) {
13266                // Right now we only know how to print all.
13267            } else if ("-h".equals(opt)) {
13268                pw.println("Package manager dump options:");
13269                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13270                pw.println("    --checkin: dump for a checkin");
13271                pw.println("    -f: print details of intent filters");
13272                pw.println("    -h: print this help");
13273                pw.println("  cmd may be one of:");
13274                pw.println("    l[ibraries]: list known shared libraries");
13275                pw.println("    f[ibraries]: list device features");
13276                pw.println("    k[eysets]: print known keysets");
13277                pw.println("    r[esolvers]: dump intent resolvers");
13278                pw.println("    perm[issions]: dump permissions");
13279                pw.println("    pref[erred]: print preferred package settings");
13280                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13281                pw.println("    prov[iders]: dump content providers");
13282                pw.println("    p[ackages]: dump installed packages");
13283                pw.println("    s[hared-users]: dump shared user IDs");
13284                pw.println("    m[essages]: print collected runtime messages");
13285                pw.println("    v[erifiers]: print package verifier info");
13286                pw.println("    version: print database version info");
13287                pw.println("    write: write current settings now");
13288                pw.println("    <package.name>: info about given package");
13289                pw.println("    installs: details about install sessions");
13290                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13291                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13292                return;
13293            } else if ("--checkin".equals(opt)) {
13294                checkin = true;
13295            } else if ("-f".equals(opt)) {
13296                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13297            } else {
13298                pw.println("Unknown argument: " + opt + "; use -h for help");
13299            }
13300        }
13301
13302        // Is the caller requesting to dump a particular piece of data?
13303        if (opti < args.length) {
13304            String cmd = args[opti];
13305            opti++;
13306            // Is this a package name?
13307            if ("android".equals(cmd) || cmd.contains(".")) {
13308                packageName = cmd;
13309                // When dumping a single package, we always dump all of its
13310                // filter information since the amount of data will be reasonable.
13311                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13312            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13313                dumpState.setDump(DumpState.DUMP_LIBS);
13314            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13315                dumpState.setDump(DumpState.DUMP_FEATURES);
13316            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13317                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13318            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13319                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13320            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13321                dumpState.setDump(DumpState.DUMP_PREFERRED);
13322            } else if ("preferred-xml".equals(cmd)) {
13323                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13324                if (opti < args.length && "--full".equals(args[opti])) {
13325                    fullPreferred = true;
13326                    opti++;
13327                }
13328            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13329                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13330            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13331                dumpState.setDump(DumpState.DUMP_PACKAGES);
13332            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13333                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13334            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13335                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13336            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13337                dumpState.setDump(DumpState.DUMP_MESSAGES);
13338            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13339                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13340            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13341                    || "intent-filter-verifiers".equals(cmd)) {
13342                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13343            } else if ("version".equals(cmd)) {
13344                dumpState.setDump(DumpState.DUMP_VERSION);
13345            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13346                dumpState.setDump(DumpState.DUMP_KEYSETS);
13347            } else if ("installs".equals(cmd)) {
13348                dumpState.setDump(DumpState.DUMP_INSTALLS);
13349            } else if ("write".equals(cmd)) {
13350                synchronized (mPackages) {
13351                    mSettings.writeLPr();
13352                    pw.println("Settings written.");
13353                    return;
13354                }
13355            }
13356        }
13357
13358        if (checkin) {
13359            pw.println("vers,1");
13360        }
13361
13362        // reader
13363        synchronized (mPackages) {
13364            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13365                if (!checkin) {
13366                    if (dumpState.onTitlePrinted())
13367                        pw.println();
13368                    pw.println("Database versions:");
13369                    pw.print("  SDK Version:");
13370                    pw.print(" internal=");
13371                    pw.print(mSettings.mInternalSdkPlatform);
13372                    pw.print(" external=");
13373                    pw.println(mSettings.mExternalSdkPlatform);
13374                    pw.print("  DB Version:");
13375                    pw.print(" internal=");
13376                    pw.print(mSettings.mInternalDatabaseVersion);
13377                    pw.print(" external=");
13378                    pw.println(mSettings.mExternalDatabaseVersion);
13379                }
13380            }
13381
13382            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13383                if (!checkin) {
13384                    if (dumpState.onTitlePrinted())
13385                        pw.println();
13386                    pw.println("Verifiers:");
13387                    pw.print("  Required: ");
13388                    pw.print(mRequiredVerifierPackage);
13389                    pw.print(" (uid=");
13390                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13391                    pw.println(")");
13392                } else if (mRequiredVerifierPackage != null) {
13393                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13394                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13395                }
13396            }
13397
13398            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13399                    packageName == null) {
13400                if (mIntentFilterVerifierComponent != null) {
13401                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13402                    if (!checkin) {
13403                        if (dumpState.onTitlePrinted())
13404                            pw.println();
13405                        pw.println("Intent Filter Verifier:");
13406                        pw.print("  Using: ");
13407                        pw.print(verifierPackageName);
13408                        pw.print(" (uid=");
13409                        pw.print(getPackageUid(verifierPackageName, 0));
13410                        pw.println(")");
13411                    } else if (verifierPackageName != null) {
13412                        pw.print("ifv,"); pw.print(verifierPackageName);
13413                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13414                    }
13415                } else {
13416                    pw.println();
13417                    pw.println("No Intent Filter Verifier available!");
13418                }
13419            }
13420
13421            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13422                boolean printedHeader = false;
13423                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13424                while (it.hasNext()) {
13425                    String name = it.next();
13426                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13427                    if (!checkin) {
13428                        if (!printedHeader) {
13429                            if (dumpState.onTitlePrinted())
13430                                pw.println();
13431                            pw.println("Libraries:");
13432                            printedHeader = true;
13433                        }
13434                        pw.print("  ");
13435                    } else {
13436                        pw.print("lib,");
13437                    }
13438                    pw.print(name);
13439                    if (!checkin) {
13440                        pw.print(" -> ");
13441                    }
13442                    if (ent.path != null) {
13443                        if (!checkin) {
13444                            pw.print("(jar) ");
13445                            pw.print(ent.path);
13446                        } else {
13447                            pw.print(",jar,");
13448                            pw.print(ent.path);
13449                        }
13450                    } else {
13451                        if (!checkin) {
13452                            pw.print("(apk) ");
13453                            pw.print(ent.apk);
13454                        } else {
13455                            pw.print(",apk,");
13456                            pw.print(ent.apk);
13457                        }
13458                    }
13459                    pw.println();
13460                }
13461            }
13462
13463            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
13464                if (dumpState.onTitlePrinted())
13465                    pw.println();
13466                if (!checkin) {
13467                    pw.println("Features:");
13468                }
13469                Iterator<String> it = mAvailableFeatures.keySet().iterator();
13470                while (it.hasNext()) {
13471                    String name = it.next();
13472                    if (!checkin) {
13473                        pw.print("  ");
13474                    } else {
13475                        pw.print("feat,");
13476                    }
13477                    pw.println(name);
13478                }
13479            }
13480
13481            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
13482                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
13483                        : "Activity Resolver Table:", "  ", packageName,
13484                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13485                    dumpState.setTitlePrinted(true);
13486                }
13487                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
13488                        : "Receiver Resolver Table:", "  ", packageName,
13489                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13490                    dumpState.setTitlePrinted(true);
13491                }
13492                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
13493                        : "Service Resolver Table:", "  ", packageName,
13494                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13495                    dumpState.setTitlePrinted(true);
13496                }
13497                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
13498                        : "Provider Resolver Table:", "  ", packageName,
13499                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13500                    dumpState.setTitlePrinted(true);
13501                }
13502            }
13503
13504            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
13505                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13506                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13507                    int user = mSettings.mPreferredActivities.keyAt(i);
13508                    if (pir.dump(pw,
13509                            dumpState.getTitlePrinted()
13510                                ? "\nPreferred Activities User " + user + ":"
13511                                : "Preferred Activities User " + user + ":", "  ",
13512                            packageName, true, false)) {
13513                        dumpState.setTitlePrinted(true);
13514                    }
13515                }
13516            }
13517
13518            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
13519                pw.flush();
13520                FileOutputStream fout = new FileOutputStream(fd);
13521                BufferedOutputStream str = new BufferedOutputStream(fout);
13522                XmlSerializer serializer = new FastXmlSerializer();
13523                try {
13524                    serializer.setOutput(str, "utf-8");
13525                    serializer.startDocument(null, true);
13526                    serializer.setFeature(
13527                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
13528                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
13529                    serializer.endDocument();
13530                    serializer.flush();
13531                } catch (IllegalArgumentException e) {
13532                    pw.println("Failed writing: " + e);
13533                } catch (IllegalStateException e) {
13534                    pw.println("Failed writing: " + e);
13535                } catch (IOException e) {
13536                    pw.println("Failed writing: " + e);
13537                }
13538            }
13539
13540            if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) {
13541                pw.println();
13542                int count = mSettings.mPackages.size();
13543                if (count == 0) {
13544                    pw.println("No domain preferred apps!");
13545                    pw.println();
13546                } else {
13547                    final String prefix = "  ";
13548                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
13549                    if (allPackageSettings.size() == 0) {
13550                        pw.println("No domain preferred apps!");
13551                        pw.println();
13552                    } else {
13553                        pw.println("Domain preferred apps status:");
13554                        pw.println();
13555                        count = 0;
13556                        for (PackageSetting ps : allPackageSettings) {
13557                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13558                            if (ivi == null || ivi.getPackageName() == null) continue;
13559                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
13560                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
13561                            pw.println(prefix + "Status: " + ivi.getStatusString());
13562                            pw.println();
13563                            count++;
13564                        }
13565                        if (count == 0) {
13566                            pw.println(prefix + "No domain preferred app status!");
13567                            pw.println();
13568                        }
13569                        for (int userId : sUserManager.getUserIds()) {
13570                            pw.println("Domain preferred apps for User " + userId + ":");
13571                            pw.println();
13572                            count = 0;
13573                            for (PackageSetting ps : allPackageSettings) {
13574                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13575                                if (ivi == null || ivi.getPackageName() == null) {
13576                                    continue;
13577                                }
13578                                final int status = ps.getDomainVerificationStatusForUser(userId);
13579                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
13580                                    continue;
13581                                }
13582                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
13583                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
13584                                String statusStr = IntentFilterVerificationInfo.
13585                                        getStatusStringFromValue(status);
13586                                pw.println(prefix + "Status: " + statusStr);
13587                                pw.println();
13588                                count++;
13589                            }
13590                            if (count == 0) {
13591                                pw.println(prefix + "No domain preferred apps!");
13592                                pw.println();
13593                            }
13594                        }
13595                    }
13596                }
13597            }
13598
13599            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
13600                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
13601                if (packageName == null) {
13602                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
13603                        if (iperm == 0) {
13604                            if (dumpState.onTitlePrinted())
13605                                pw.println();
13606                            pw.println("AppOp Permissions:");
13607                        }
13608                        pw.print("  AppOp Permission ");
13609                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
13610                        pw.println(":");
13611                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
13612                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
13613                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
13614                        }
13615                    }
13616                }
13617            }
13618
13619            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
13620                boolean printedSomething = false;
13621                for (PackageParser.Provider p : mProviders.mProviders.values()) {
13622                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13623                        continue;
13624                    }
13625                    if (!printedSomething) {
13626                        if (dumpState.onTitlePrinted())
13627                            pw.println();
13628                        pw.println("Registered ContentProviders:");
13629                        printedSomething = true;
13630                    }
13631                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
13632                    pw.print("    "); pw.println(p.toString());
13633                }
13634                printedSomething = false;
13635                for (Map.Entry<String, PackageParser.Provider> entry :
13636                        mProvidersByAuthority.entrySet()) {
13637                    PackageParser.Provider p = entry.getValue();
13638                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13639                        continue;
13640                    }
13641                    if (!printedSomething) {
13642                        if (dumpState.onTitlePrinted())
13643                            pw.println();
13644                        pw.println("ContentProvider Authorities:");
13645                        printedSomething = true;
13646                    }
13647                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
13648                    pw.print("    "); pw.println(p.toString());
13649                    if (p.info != null && p.info.applicationInfo != null) {
13650                        final String appInfo = p.info.applicationInfo.toString();
13651                        pw.print("      applicationInfo="); pw.println(appInfo);
13652                    }
13653                }
13654            }
13655
13656            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
13657                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
13658            }
13659
13660            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
13661                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
13662            }
13663
13664            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
13665                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
13666            }
13667
13668            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
13669                // XXX should handle packageName != null by dumping only install data that
13670                // the given package is involved with.
13671                if (dumpState.onTitlePrinted()) pw.println();
13672                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
13673            }
13674
13675            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
13676                if (dumpState.onTitlePrinted()) pw.println();
13677                mSettings.dumpReadMessagesLPr(pw, dumpState);
13678
13679                pw.println();
13680                pw.println("Package warning messages:");
13681                BufferedReader in = null;
13682                String line = null;
13683                try {
13684                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
13685                    while ((line = in.readLine()) != null) {
13686                        if (line.contains("ignored: updated version")) continue;
13687                        pw.println(line);
13688                    }
13689                } catch (IOException ignored) {
13690                } finally {
13691                    IoUtils.closeQuietly(in);
13692                }
13693            }
13694
13695            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
13696                BufferedReader in = null;
13697                String line = null;
13698                try {
13699                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
13700                    while ((line = in.readLine()) != null) {
13701                        if (line.contains("ignored: updated version")) continue;
13702                        pw.print("msg,");
13703                        pw.println(line);
13704                    }
13705                } catch (IOException ignored) {
13706                } finally {
13707                    IoUtils.closeQuietly(in);
13708                }
13709            }
13710        }
13711    }
13712
13713    // ------- apps on sdcard specific code -------
13714    static final boolean DEBUG_SD_INSTALL = false;
13715
13716    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
13717
13718    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
13719
13720    private boolean mMediaMounted = false;
13721
13722    static String getEncryptKey() {
13723        try {
13724            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
13725                    SD_ENCRYPTION_KEYSTORE_NAME);
13726            if (sdEncKey == null) {
13727                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
13728                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
13729                if (sdEncKey == null) {
13730                    Slog.e(TAG, "Failed to create encryption keys");
13731                    return null;
13732                }
13733            }
13734            return sdEncKey;
13735        } catch (NoSuchAlgorithmException nsae) {
13736            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
13737            return null;
13738        } catch (IOException ioe) {
13739            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
13740            return null;
13741        }
13742    }
13743
13744    /*
13745     * Update media status on PackageManager.
13746     */
13747    @Override
13748    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
13749        int callingUid = Binder.getCallingUid();
13750        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
13751            throw new SecurityException("Media status can only be updated by the system");
13752        }
13753        // reader; this apparently protects mMediaMounted, but should probably
13754        // be a different lock in that case.
13755        synchronized (mPackages) {
13756            Log.i(TAG, "Updating external media status from "
13757                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
13758                    + (mediaStatus ? "mounted" : "unmounted"));
13759            if (DEBUG_SD_INSTALL)
13760                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
13761                        + ", mMediaMounted=" + mMediaMounted);
13762            if (mediaStatus == mMediaMounted) {
13763                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
13764                        : 0, -1);
13765                mHandler.sendMessage(msg);
13766                return;
13767            }
13768            mMediaMounted = mediaStatus;
13769        }
13770        // Queue up an async operation since the package installation may take a
13771        // little while.
13772        mHandler.post(new Runnable() {
13773            public void run() {
13774                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
13775            }
13776        });
13777    }
13778
13779    /**
13780     * Called by MountService when the initial ASECs to scan are available.
13781     * Should block until all the ASEC containers are finished being scanned.
13782     */
13783    public void scanAvailableAsecs() {
13784        updateExternalMediaStatusInner(true, false, false);
13785        if (mShouldRestoreconData) {
13786            SELinuxMMAC.setRestoreconDone();
13787            mShouldRestoreconData = false;
13788        }
13789    }
13790
13791    /*
13792     * Collect information of applications on external media, map them against
13793     * existing containers and update information based on current mount status.
13794     * Please note that we always have to report status if reportStatus has been
13795     * set to true especially when unloading packages.
13796     */
13797    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
13798            boolean externalStorage) {
13799        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
13800        int[] uidArr = EmptyArray.INT;
13801
13802        final String[] list = PackageHelper.getSecureContainerList();
13803        if (ArrayUtils.isEmpty(list)) {
13804            Log.i(TAG, "No secure containers found");
13805        } else {
13806            // Process list of secure containers and categorize them
13807            // as active or stale based on their package internal state.
13808
13809            // reader
13810            synchronized (mPackages) {
13811                for (String cid : list) {
13812                    // Leave stages untouched for now; installer service owns them
13813                    if (PackageInstallerService.isStageName(cid)) continue;
13814
13815                    if (DEBUG_SD_INSTALL)
13816                        Log.i(TAG, "Processing container " + cid);
13817                    String pkgName = getAsecPackageName(cid);
13818                    if (pkgName == null) {
13819                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
13820                        continue;
13821                    }
13822                    if (DEBUG_SD_INSTALL)
13823                        Log.i(TAG, "Looking for pkg : " + pkgName);
13824
13825                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
13826                    if (ps == null) {
13827                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
13828                        continue;
13829                    }
13830
13831                    /*
13832                     * Skip packages that are not external if we're unmounting
13833                     * external storage.
13834                     */
13835                    if (externalStorage && !isMounted && !isExternal(ps)) {
13836                        continue;
13837                    }
13838
13839                    final AsecInstallArgs args = new AsecInstallArgs(cid,
13840                            getAppDexInstructionSets(ps), ps.isForwardLocked());
13841                    // The package status is changed only if the code path
13842                    // matches between settings and the container id.
13843                    if (ps.codePathString != null
13844                            && ps.codePathString.startsWith(args.getCodePath())) {
13845                        if (DEBUG_SD_INSTALL) {
13846                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
13847                                    + " at code path: " + ps.codePathString);
13848                        }
13849
13850                        // We do have a valid package installed on sdcard
13851                        processCids.put(args, ps.codePathString);
13852                        final int uid = ps.appId;
13853                        if (uid != -1) {
13854                            uidArr = ArrayUtils.appendInt(uidArr, uid);
13855                        }
13856                    } else {
13857                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
13858                                + ps.codePathString);
13859                    }
13860                }
13861            }
13862
13863            Arrays.sort(uidArr);
13864        }
13865
13866        // Process packages with valid entries.
13867        if (isMounted) {
13868            if (DEBUG_SD_INSTALL)
13869                Log.i(TAG, "Loading packages");
13870            loadMediaPackages(processCids, uidArr);
13871            startCleaningPackages();
13872            mInstallerService.onSecureContainersAvailable();
13873        } else {
13874            if (DEBUG_SD_INSTALL)
13875                Log.i(TAG, "Unloading packages");
13876            unloadMediaPackages(processCids, uidArr, reportStatus);
13877        }
13878    }
13879
13880    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13881            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
13882        final int size = infos.size();
13883        final String[] packageNames = new String[size];
13884        final int[] packageUids = new int[size];
13885        for (int i = 0; i < size; i++) {
13886            final ApplicationInfo info = infos.get(i);
13887            packageNames[i] = info.packageName;
13888            packageUids[i] = info.uid;
13889        }
13890        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
13891                finishedReceiver);
13892    }
13893
13894    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13895            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
13896        sendResourcesChangedBroadcast(mediaStatus, replacing,
13897                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
13898    }
13899
13900    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13901            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
13902        int size = pkgList.length;
13903        if (size > 0) {
13904            // Send broadcasts here
13905            Bundle extras = new Bundle();
13906            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13907            if (uidArr != null) {
13908                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
13909            }
13910            if (replacing) {
13911                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
13912            }
13913            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
13914                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
13915            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
13916        }
13917    }
13918
13919   /*
13920     * Look at potentially valid container ids from processCids If package
13921     * information doesn't match the one on record or package scanning fails,
13922     * the cid is added to list of removeCids. We currently don't delete stale
13923     * containers.
13924     */
13925    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
13926        ArrayList<String> pkgList = new ArrayList<String>();
13927        Set<AsecInstallArgs> keys = processCids.keySet();
13928
13929        for (AsecInstallArgs args : keys) {
13930            String codePath = processCids.get(args);
13931            if (DEBUG_SD_INSTALL)
13932                Log.i(TAG, "Loading container : " + args.cid);
13933            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13934            try {
13935                // Make sure there are no container errors first.
13936                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
13937                    Slog.e(TAG, "Failed to mount cid : " + args.cid
13938                            + " when installing from sdcard");
13939                    continue;
13940                }
13941                // Check code path here.
13942                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
13943                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
13944                            + " does not match one in settings " + codePath);
13945                    continue;
13946                }
13947                // Parse package
13948                int parseFlags = mDefParseFlags;
13949                if (args.isExternalAsec()) {
13950                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
13951                }
13952                if (args.isFwdLocked()) {
13953                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
13954                }
13955
13956                synchronized (mInstallLock) {
13957                    PackageParser.Package pkg = null;
13958                    try {
13959                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
13960                    } catch (PackageManagerException e) {
13961                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
13962                    }
13963                    // Scan the package
13964                    if (pkg != null) {
13965                        /*
13966                         * TODO why is the lock being held? doPostInstall is
13967                         * called in other places without the lock. This needs
13968                         * to be straightened out.
13969                         */
13970                        // writer
13971                        synchronized (mPackages) {
13972                            retCode = PackageManager.INSTALL_SUCCEEDED;
13973                            pkgList.add(pkg.packageName);
13974                            // Post process args
13975                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
13976                                    pkg.applicationInfo.uid);
13977                        }
13978                    } else {
13979                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
13980                    }
13981                }
13982
13983            } finally {
13984                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
13985                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
13986                }
13987            }
13988        }
13989        // writer
13990        synchronized (mPackages) {
13991            // If the platform SDK has changed since the last time we booted,
13992            // we need to re-grant app permission to catch any new ones that
13993            // appear. This is really a hack, and means that apps can in some
13994            // cases get permissions that the user didn't initially explicitly
13995            // allow... it would be nice to have some better way to handle
13996            // this situation.
13997            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
13998            if (regrantPermissions)
13999                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14000                        + mSdkVersion + "; regranting permissions for external storage");
14001            mSettings.mExternalSdkPlatform = mSdkVersion;
14002
14003            // Make sure group IDs have been assigned, and any permission
14004            // changes in other apps are accounted for
14005            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14006                    | (regrantPermissions
14007                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14008                            : 0));
14009
14010            mSettings.updateExternalDatabaseVersion();
14011
14012            // can downgrade to reader
14013            // Persist settings
14014            mSettings.writeLPr();
14015        }
14016        // Send a broadcast to let everyone know we are done processing
14017        if (pkgList.size() > 0) {
14018            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14019        }
14020    }
14021
14022   /*
14023     * Utility method to unload a list of specified containers
14024     */
14025    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14026        // Just unmount all valid containers.
14027        for (AsecInstallArgs arg : cidArgs) {
14028            synchronized (mInstallLock) {
14029                arg.doPostDeleteLI(false);
14030           }
14031       }
14032   }
14033
14034    /*
14035     * Unload packages mounted on external media. This involves deleting package
14036     * data from internal structures, sending broadcasts about diabled packages,
14037     * gc'ing to free up references, unmounting all secure containers
14038     * corresponding to packages on external media, and posting a
14039     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14040     * that we always have to post this message if status has been requested no
14041     * matter what.
14042     */
14043    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14044            final boolean reportStatus) {
14045        if (DEBUG_SD_INSTALL)
14046            Log.i(TAG, "unloading media packages");
14047        ArrayList<String> pkgList = new ArrayList<String>();
14048        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14049        final Set<AsecInstallArgs> keys = processCids.keySet();
14050        for (AsecInstallArgs args : keys) {
14051            String pkgName = args.getPackageName();
14052            if (DEBUG_SD_INSTALL)
14053                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14054            // Delete package internally
14055            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14056            synchronized (mInstallLock) {
14057                boolean res = deletePackageLI(pkgName, null, false, null, null,
14058                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14059                if (res) {
14060                    pkgList.add(pkgName);
14061                } else {
14062                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14063                    failedList.add(args);
14064                }
14065            }
14066        }
14067
14068        // reader
14069        synchronized (mPackages) {
14070            // We didn't update the settings after removing each package;
14071            // write them now for all packages.
14072            mSettings.writeLPr();
14073        }
14074
14075        // We have to absolutely send UPDATED_MEDIA_STATUS only
14076        // after confirming that all the receivers processed the ordered
14077        // broadcast when packages get disabled, force a gc to clean things up.
14078        // and unload all the containers.
14079        if (pkgList.size() > 0) {
14080            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14081                    new IIntentReceiver.Stub() {
14082                public void performReceive(Intent intent, int resultCode, String data,
14083                        Bundle extras, boolean ordered, boolean sticky,
14084                        int sendingUser) throws RemoteException {
14085                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14086                            reportStatus ? 1 : 0, 1, keys);
14087                    mHandler.sendMessage(msg);
14088                }
14089            });
14090        } else {
14091            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14092                    keys);
14093            mHandler.sendMessage(msg);
14094        }
14095    }
14096
14097    private void loadPrivatePackages(VolumeInfo vol) {
14098        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14099        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14100        synchronized (mPackages) {
14101            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14102            for (PackageSetting ps : packages) {
14103                synchronized (mInstallLock) {
14104                    final PackageParser.Package pkg;
14105                    try {
14106                        pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14107                        loaded.add(pkg.applicationInfo);
14108                    } catch (PackageManagerException e) {
14109                        Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14110                    }
14111                }
14112            }
14113
14114            // TODO: regrant any permissions that changed based since original install
14115
14116            mSettings.writeLPr();
14117        }
14118
14119        Slog.d(TAG, "Loaded packages " + loaded);
14120        sendResourcesChangedBroadcast(true, false, loaded, null);
14121    }
14122
14123    private void unloadPrivatePackages(VolumeInfo vol) {
14124        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14125        synchronized (mPackages) {
14126            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14127            for (PackageSetting ps : packages) {
14128                if (ps.pkg == null) continue;
14129                synchronized (mInstallLock) {
14130                    final ApplicationInfo info = ps.pkg.applicationInfo;
14131                    final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14132                    if (deletePackageLI(ps.name, null, false, null, null,
14133                            PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14134                        unloaded.add(info);
14135                    } else {
14136                        Slog.w(TAG, "Failed to unload " + ps.codePath);
14137                    }
14138                }
14139            }
14140
14141            mSettings.writeLPr();
14142        }
14143
14144        Slog.d(TAG, "Unloaded packages " + unloaded);
14145        sendResourcesChangedBroadcast(false, false, unloaded, null);
14146    }
14147
14148    @Override
14149    public int movePackage(final String packageName, final String volumeUuid) {
14150        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14151
14152        final int moveId = mNextMoveId.getAndIncrement();
14153        try {
14154            movePackageInternal(packageName, volumeUuid, moveId);
14155        } catch (PackageManagerException e) {
14156            Slog.d(TAG, "Failed to move " + packageName, e);
14157            mMoveCallbacks.notifyStatusChanged(moveId, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14158        }
14159        return moveId;
14160    }
14161
14162    private void movePackageInternal(final String packageName, final String volumeUuid,
14163            final int moveId) throws PackageManagerException {
14164        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14165        final PackageManager pm = mContext.getPackageManager();
14166
14167        final boolean currentAsec;
14168        final String currentVolumeUuid;
14169        final File codeFile;
14170        final String installerPackageName;
14171        final String packageAbiOverride;
14172        final int appId;
14173        final String seinfo;
14174
14175        // reader
14176        synchronized (mPackages) {
14177            final PackageParser.Package pkg = mPackages.get(packageName);
14178            final PackageSetting ps = mSettings.mPackages.get(packageName);
14179            if (pkg == null || ps == null) {
14180                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14181            }
14182
14183            if (pkg.applicationInfo.isSystemApp()) {
14184                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14185                        "Cannot move system application");
14186            } else if (pkg.mOperationPending) {
14187                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14188                        "Attempt to move package which has pending operations");
14189            }
14190
14191            // TODO: yell if already in desired location
14192
14193            mMoveCallbacks.notifyStarted(moveId,
14194                    String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)));
14195
14196            pkg.mOperationPending = true;
14197
14198            currentAsec = pkg.applicationInfo.isForwardLocked()
14199                    || pkg.applicationInfo.isExternalAsec();
14200            currentVolumeUuid = ps.volumeUuid;
14201            codeFile = new File(pkg.codePath);
14202            installerPackageName = ps.installerPackageName;
14203            packageAbiOverride = ps.cpuAbiOverrideString;
14204            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14205            seinfo = pkg.applicationInfo.seinfo;
14206        }
14207
14208        int installFlags;
14209        final boolean moveData;
14210
14211        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
14212            installFlags = INSTALL_INTERNAL;
14213            moveData = !currentAsec;
14214        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
14215            installFlags = INSTALL_EXTERNAL;
14216            moveData = false;
14217        } else {
14218            final StorageManager storage = mContext.getSystemService(StorageManager.class);
14219            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
14220            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
14221                    || !volume.isMountedWritable()) {
14222                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14223                        "Move location not mounted private volume");
14224            }
14225
14226            Preconditions.checkState(!currentAsec);
14227
14228            installFlags = INSTALL_INTERNAL;
14229            moveData = true;
14230        }
14231
14232        Slog.d(TAG, "Moving " + packageName + " from " + currentVolumeUuid + " to " + volumeUuid);
14233        mMoveCallbacks.notifyStatusChanged(moveId, 10, -1);
14234
14235        if (moveData) {
14236            synchronized (mInstallLock) {
14237                // TODO: split this into separate copy and delete operations
14238                if (mInstaller.moveUserDataDirs(currentVolumeUuid, volumeUuid, packageName, appId,
14239                        seinfo) != 0) {
14240                    synchronized (mPackages) {
14241                        final PackageParser.Package pkg = mPackages.get(packageName);
14242                        if (pkg != null) {
14243                            pkg.mOperationPending = false;
14244                        }
14245                    }
14246
14247                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14248                            "Failed to move private data");
14249                }
14250            }
14251        }
14252
14253        mMoveCallbacks.notifyStatusChanged(moveId, 50);
14254
14255        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14256            @Override
14257            public void onUserActionRequired(Intent intent) throws RemoteException {
14258                throw new IllegalStateException();
14259            }
14260
14261            @Override
14262            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14263                    Bundle extras) throws RemoteException {
14264                Slog.d(TAG, "Install result for move: "
14265                        + PackageManager.installStatusToString(returnCode, msg));
14266
14267                // We usually have a new package now after the install, but if
14268                // we failed we need to clear the pending flag on the original
14269                // package object.
14270                synchronized (mPackages) {
14271                    final PackageParser.Package pkg = mPackages.get(packageName);
14272                    if (pkg != null) {
14273                        pkg.mOperationPending = false;
14274                    }
14275                }
14276
14277                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14278                switch (status) {
14279                    case PackageInstaller.STATUS_SUCCESS:
14280                        mMoveCallbacks.notifyStatusChanged(moveId,
14281                                PackageManager.MOVE_SUCCEEDED);
14282                        break;
14283                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14284                        mMoveCallbacks.notifyStatusChanged(moveId,
14285                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14286                        break;
14287                    default:
14288                        mMoveCallbacks.notifyStatusChanged(moveId,
14289                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14290                        break;
14291                }
14292            }
14293        };
14294
14295        // Treat a move like reinstalling an existing app, which ensures that we
14296        // process everythign uniformly, like unpacking native libraries.
14297        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14298
14299        final Message msg = mHandler.obtainMessage(INIT_COPY);
14300        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14301        msg.obj = new InstallParams(origin, installObserver, installFlags,
14302                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14303        mHandler.sendMessage(msg);
14304    }
14305
14306    @Override
14307    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
14308        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14309
14310        final int realMoveId = mNextMoveId.getAndIncrement();
14311        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
14312            @Override
14313            public void onStarted(int moveId, String title) {
14314                // Ignored
14315            }
14316
14317            @Override
14318            public void onStatusChanged(int moveId, int status, long estMillis) {
14319                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
14320            }
14321        };
14322
14323        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14324        storage.setPrimaryStorageUuid(volumeUuid, callback);
14325        return realMoveId;
14326    }
14327
14328    @Override
14329    public int getMoveStatus(int moveId) {
14330        mContext.enforceCallingOrSelfPermission(
14331                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14332        return mMoveCallbacks.mLastStatus.get(moveId);
14333    }
14334
14335    @Override
14336    public void registerMoveCallback(IPackageMoveObserver callback) {
14337        mContext.enforceCallingOrSelfPermission(
14338                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14339        mMoveCallbacks.register(callback);
14340    }
14341
14342    @Override
14343    public void unregisterMoveCallback(IPackageMoveObserver callback) {
14344        mContext.enforceCallingOrSelfPermission(
14345                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14346        mMoveCallbacks.unregister(callback);
14347    }
14348
14349    @Override
14350    public boolean setInstallLocation(int loc) {
14351        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14352                null);
14353        if (getInstallLocation() == loc) {
14354            return true;
14355        }
14356        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14357                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14358            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14359                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14360            return true;
14361        }
14362        return false;
14363   }
14364
14365    @Override
14366    public int getInstallLocation() {
14367        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14368                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14369                PackageHelper.APP_INSTALL_AUTO);
14370    }
14371
14372    /** Called by UserManagerService */
14373    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14374        mDirtyUsers.remove(userHandle);
14375        mSettings.removeUserLPw(userHandle);
14376        mPendingBroadcasts.remove(userHandle);
14377        if (mInstaller != null) {
14378            // Technically, we shouldn't be doing this with the package lock
14379            // held.  However, this is very rare, and there is already so much
14380            // other disk I/O going on, that we'll let it slide for now.
14381            final StorageManager storage = StorageManager.from(mContext);
14382            final List<VolumeInfo> vols = storage.getVolumes();
14383            for (VolumeInfo vol : vols) {
14384                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
14385                    final String volumeUuid = vol.getFsUuid();
14386                    Slog.d(TAG, "Removing user data on volume " + volumeUuid);
14387                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
14388                }
14389            }
14390        }
14391        mUserNeedsBadging.delete(userHandle);
14392        removeUnusedPackagesLILPw(userManager, userHandle);
14393    }
14394
14395    /**
14396     * We're removing userHandle and would like to remove any downloaded packages
14397     * that are no longer in use by any other user.
14398     * @param userHandle the user being removed
14399     */
14400    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
14401        final boolean DEBUG_CLEAN_APKS = false;
14402        int [] users = userManager.getUserIdsLPr();
14403        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
14404        while (psit.hasNext()) {
14405            PackageSetting ps = psit.next();
14406            if (ps.pkg == null) {
14407                continue;
14408            }
14409            final String packageName = ps.pkg.packageName;
14410            // Skip over if system app
14411            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14412                continue;
14413            }
14414            if (DEBUG_CLEAN_APKS) {
14415                Slog.i(TAG, "Checking package " + packageName);
14416            }
14417            boolean keep = false;
14418            for (int i = 0; i < users.length; i++) {
14419                if (users[i] != userHandle && ps.getInstalled(users[i])) {
14420                    keep = true;
14421                    if (DEBUG_CLEAN_APKS) {
14422                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
14423                                + users[i]);
14424                    }
14425                    break;
14426                }
14427            }
14428            if (!keep) {
14429                if (DEBUG_CLEAN_APKS) {
14430                    Slog.i(TAG, "  Removing package " + packageName);
14431                }
14432                mHandler.post(new Runnable() {
14433                    public void run() {
14434                        deletePackageX(packageName, userHandle, 0);
14435                    } //end run
14436                });
14437            }
14438        }
14439    }
14440
14441    /** Called by UserManagerService */
14442    void createNewUserLILPw(int userHandle, File path) {
14443        if (mInstaller != null) {
14444            mInstaller.createUserConfig(userHandle);
14445            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
14446        }
14447    }
14448
14449    void newUserCreatedLILPw(int userHandle) {
14450        // Adding a user requires updating runtime permissions for system apps.
14451        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
14452    }
14453
14454    @Override
14455    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
14456        mContext.enforceCallingOrSelfPermission(
14457                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14458                "Only package verification agents can read the verifier device identity");
14459
14460        synchronized (mPackages) {
14461            return mSettings.getVerifierDeviceIdentityLPw();
14462        }
14463    }
14464
14465    @Override
14466    public void setPermissionEnforced(String permission, boolean enforced) {
14467        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
14468        if (READ_EXTERNAL_STORAGE.equals(permission)) {
14469            synchronized (mPackages) {
14470                if (mSettings.mReadExternalStorageEnforced == null
14471                        || mSettings.mReadExternalStorageEnforced != enforced) {
14472                    mSettings.mReadExternalStorageEnforced = enforced;
14473                    mSettings.writeLPr();
14474                }
14475            }
14476            // kill any non-foreground processes so we restart them and
14477            // grant/revoke the GID.
14478            final IActivityManager am = ActivityManagerNative.getDefault();
14479            if (am != null) {
14480                final long token = Binder.clearCallingIdentity();
14481                try {
14482                    am.killProcessesBelowForeground("setPermissionEnforcement");
14483                } catch (RemoteException e) {
14484                } finally {
14485                    Binder.restoreCallingIdentity(token);
14486                }
14487            }
14488        } else {
14489            throw new IllegalArgumentException("No selective enforcement for " + permission);
14490        }
14491    }
14492
14493    @Override
14494    @Deprecated
14495    public boolean isPermissionEnforced(String permission) {
14496        return true;
14497    }
14498
14499    @Override
14500    public boolean isStorageLow() {
14501        final long token = Binder.clearCallingIdentity();
14502        try {
14503            final DeviceStorageMonitorInternal
14504                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14505            if (dsm != null) {
14506                return dsm.isMemoryLow();
14507            } else {
14508                return false;
14509            }
14510        } finally {
14511            Binder.restoreCallingIdentity(token);
14512        }
14513    }
14514
14515    @Override
14516    public IPackageInstaller getPackageInstaller() {
14517        return mInstallerService;
14518    }
14519
14520    private boolean userNeedsBadging(int userId) {
14521        int index = mUserNeedsBadging.indexOfKey(userId);
14522        if (index < 0) {
14523            final UserInfo userInfo;
14524            final long token = Binder.clearCallingIdentity();
14525            try {
14526                userInfo = sUserManager.getUserInfo(userId);
14527            } finally {
14528                Binder.restoreCallingIdentity(token);
14529            }
14530            final boolean b;
14531            if (userInfo != null && userInfo.isManagedProfile()) {
14532                b = true;
14533            } else {
14534                b = false;
14535            }
14536            mUserNeedsBadging.put(userId, b);
14537            return b;
14538        }
14539        return mUserNeedsBadging.valueAt(index);
14540    }
14541
14542    @Override
14543    public KeySet getKeySetByAlias(String packageName, String alias) {
14544        if (packageName == null || alias == null) {
14545            return null;
14546        }
14547        synchronized(mPackages) {
14548            final PackageParser.Package pkg = mPackages.get(packageName);
14549            if (pkg == null) {
14550                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14551                throw new IllegalArgumentException("Unknown package: " + packageName);
14552            }
14553            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14554            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
14555        }
14556    }
14557
14558    @Override
14559    public KeySet getSigningKeySet(String packageName) {
14560        if (packageName == null) {
14561            return null;
14562        }
14563        synchronized(mPackages) {
14564            final PackageParser.Package pkg = mPackages.get(packageName);
14565            if (pkg == null) {
14566                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14567                throw new IllegalArgumentException("Unknown package: " + packageName);
14568            }
14569            if (pkg.applicationInfo.uid != Binder.getCallingUid()
14570                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
14571                throw new SecurityException("May not access signing KeySet of other apps.");
14572            }
14573            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14574            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
14575        }
14576    }
14577
14578    @Override
14579    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
14580        if (packageName == null || ks == null) {
14581            return false;
14582        }
14583        synchronized(mPackages) {
14584            final PackageParser.Package pkg = mPackages.get(packageName);
14585            if (pkg == null) {
14586                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14587                throw new IllegalArgumentException("Unknown package: " + packageName);
14588            }
14589            IBinder ksh = ks.getToken();
14590            if (ksh instanceof KeySetHandle) {
14591                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14592                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
14593            }
14594            return false;
14595        }
14596    }
14597
14598    @Override
14599    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
14600        if (packageName == null || ks == null) {
14601            return false;
14602        }
14603        synchronized(mPackages) {
14604            final PackageParser.Package pkg = mPackages.get(packageName);
14605            if (pkg == null) {
14606                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14607                throw new IllegalArgumentException("Unknown package: " + packageName);
14608            }
14609            IBinder ksh = ks.getToken();
14610            if (ksh instanceof KeySetHandle) {
14611                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14612                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
14613            }
14614            return false;
14615        }
14616    }
14617
14618    public void getUsageStatsIfNoPackageUsageInfo() {
14619        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
14620            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
14621            if (usm == null) {
14622                throw new IllegalStateException("UsageStatsManager must be initialized");
14623            }
14624            long now = System.currentTimeMillis();
14625            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
14626            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
14627                String packageName = entry.getKey();
14628                PackageParser.Package pkg = mPackages.get(packageName);
14629                if (pkg == null) {
14630                    continue;
14631                }
14632                UsageStats usage = entry.getValue();
14633                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
14634                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
14635            }
14636        }
14637    }
14638
14639    /**
14640     * Check and throw if the given before/after packages would be considered a
14641     * downgrade.
14642     */
14643    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
14644            throws PackageManagerException {
14645        if (after.versionCode < before.mVersionCode) {
14646            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14647                    "Update version code " + after.versionCode + " is older than current "
14648                    + before.mVersionCode);
14649        } else if (after.versionCode == before.mVersionCode) {
14650            if (after.baseRevisionCode < before.baseRevisionCode) {
14651                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14652                        "Update base revision code " + after.baseRevisionCode
14653                        + " is older than current " + before.baseRevisionCode);
14654            }
14655
14656            if (!ArrayUtils.isEmpty(after.splitNames)) {
14657                for (int i = 0; i < after.splitNames.length; i++) {
14658                    final String splitName = after.splitNames[i];
14659                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
14660                    if (j != -1) {
14661                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
14662                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14663                                    "Update split " + splitName + " revision code "
14664                                    + after.splitRevisionCodes[i] + " is older than current "
14665                                    + before.splitRevisionCodes[j]);
14666                        }
14667                    }
14668                }
14669            }
14670        }
14671    }
14672
14673    private static class MoveCallbacks extends Handler {
14674        private static final int MSG_STARTED = 1;
14675        private static final int MSG_STATUS_CHANGED = 2;
14676
14677        private final RemoteCallbackList<IPackageMoveObserver>
14678                mCallbacks = new RemoteCallbackList<>();
14679
14680        private final SparseIntArray mLastStatus = new SparseIntArray();
14681
14682        public MoveCallbacks(Looper looper) {
14683            super(looper);
14684        }
14685
14686        public void register(IPackageMoveObserver callback) {
14687            mCallbacks.register(callback);
14688        }
14689
14690        public void unregister(IPackageMoveObserver callback) {
14691            mCallbacks.unregister(callback);
14692        }
14693
14694        @Override
14695        public void handleMessage(Message msg) {
14696            final SomeArgs args = (SomeArgs) msg.obj;
14697            final int n = mCallbacks.beginBroadcast();
14698            for (int i = 0; i < n; i++) {
14699                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
14700                try {
14701                    invokeCallback(callback, msg.what, args);
14702                } catch (RemoteException ignored) {
14703                }
14704            }
14705            mCallbacks.finishBroadcast();
14706            args.recycle();
14707        }
14708
14709        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
14710                throws RemoteException {
14711            switch (what) {
14712                case MSG_STARTED: {
14713                    callback.onStarted(args.argi1, (String) args.arg2);
14714                    break;
14715                }
14716                case MSG_STATUS_CHANGED: {
14717                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
14718                    break;
14719                }
14720            }
14721        }
14722
14723        private void notifyStarted(int moveId, String title) {
14724            Slog.v(TAG, "Move " + moveId + " started with title " + title);
14725
14726            final SomeArgs args = SomeArgs.obtain();
14727            args.argi1 = moveId;
14728            args.arg2 = title;
14729            obtainMessage(MSG_STARTED, args).sendToTarget();
14730        }
14731
14732        private void notifyStatusChanged(int moveId, int status) {
14733            notifyStatusChanged(moveId, status, -1);
14734        }
14735
14736        private void notifyStatusChanged(int moveId, int status, long estMillis) {
14737            Slog.v(TAG, "Move " + moveId + " status " + status);
14738
14739            final SomeArgs args = SomeArgs.obtain();
14740            args.argi1 = moveId;
14741            args.argi2 = status;
14742            args.arg3 = estMillis;
14743            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
14744
14745            synchronized (mLastStatus) {
14746                mLastStatus.put(moveId, status);
14747            }
14748        }
14749    }
14750}
14751