PackageManagerService.java revision b2b9ab8354da1485178cd8d8e9d89ac915b3f269
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
46import static android.content.pm.PackageManager.INSTALL_INTERNAL;
47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
52import static android.content.pm.PackageManager.MOVE_EXTERNAL_MEDIA;
53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
54import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
55import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
56import static android.content.pm.PackageManager.MOVE_INTERNAL;
57import static android.content.pm.PackageParser.isApkFile;
58import static android.os.Process.PACKAGE_INFO_GID;
59import static android.os.Process.SYSTEM_UID;
60import static android.system.OsConstants.O_CREAT;
61import static android.system.OsConstants.O_RDWR;
62import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
64import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
65import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
66import static com.android.internal.util.ArrayUtils.appendInt;
67import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
68import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
70import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
71import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
72
73import android.Manifest;
74import org.xmlpull.v1.XmlPullParser;
75import android.app.ActivityManager;
76import android.app.ActivityManagerNative;
77import android.app.AppGlobals;
78import android.app.IActivityManager;
79import android.app.admin.IDevicePolicyManager;
80import android.app.backup.IBackupManager;
81import android.app.usage.UsageStats;
82import android.app.usage.UsageStatsManager;
83import android.content.BroadcastReceiver;
84import android.content.ComponentName;
85import android.content.Context;
86import android.content.IIntentReceiver;
87import android.content.Intent;
88import android.content.IntentFilter;
89import android.content.IntentSender;
90import android.content.IntentSender.SendIntentException;
91import android.content.ServiceConnection;
92import android.content.pm.ActivityInfo;
93import android.content.pm.ApplicationInfo;
94import android.content.pm.FeatureInfo;
95import android.content.pm.IPackageDataObserver;
96import android.content.pm.IPackageDeleteObserver;
97import android.content.pm.IPackageDeleteObserver2;
98import android.content.pm.IPackageInstallObserver2;
99import android.content.pm.IPackageInstaller;
100import android.content.pm.IPackageManager;
101import android.content.pm.IPackageMoveObserver;
102import android.content.pm.IPackageStatsObserver;
103import android.content.pm.InstrumentationInfo;
104import android.content.pm.IntentFilterVerificationInfo;
105import android.content.pm.KeySet;
106import android.content.pm.ManifestDigest;
107import android.content.pm.PackageCleanItem;
108import android.content.pm.PackageInfo;
109import android.content.pm.PackageInfoLite;
110import android.content.pm.PackageInstaller;
111import android.content.pm.PackageManager;
112import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
113import android.content.pm.PackageParser;
114import android.content.pm.PackageParser.ActivityIntentInfo;
115import android.content.pm.PackageParser.PackageLite;
116import android.content.pm.PackageParser.PackageParserException;
117import android.content.pm.PackageStats;
118import android.content.pm.PackageUserState;
119import android.content.pm.ParceledListSlice;
120import android.content.pm.PermissionGroupInfo;
121import android.content.pm.PermissionInfo;
122import android.content.pm.ProviderInfo;
123import android.content.pm.ResolveInfo;
124import android.content.pm.ServiceInfo;
125import android.content.pm.Signature;
126import android.content.pm.UserInfo;
127import android.content.pm.VerificationParams;
128import android.content.pm.VerifierDeviceIdentity;
129import android.content.pm.VerifierInfo;
130import android.content.res.Resources;
131import android.hardware.display.DisplayManager;
132import android.net.Uri;
133import android.os.Binder;
134import android.os.Build;
135import android.os.Bundle;
136import android.os.Debug;
137import android.os.Environment;
138import android.os.Environment.UserEnvironment;
139import android.os.FileUtils;
140import android.os.Handler;
141import android.os.IBinder;
142import android.os.Looper;
143import android.os.Message;
144import android.os.Parcel;
145import android.os.ParcelFileDescriptor;
146import android.os.Process;
147import android.os.RemoteException;
148import android.os.SELinux;
149import android.os.ServiceManager;
150import android.os.SystemClock;
151import android.os.SystemProperties;
152import android.os.UserHandle;
153import android.os.UserManager;
154import android.os.storage.IMountService;
155import android.os.storage.StorageEventListener;
156import android.os.storage.StorageManager;
157import android.os.storage.VolumeInfo;
158import android.security.KeyStore;
159import android.security.SystemKeyStore;
160import android.system.ErrnoException;
161import android.system.Os;
162import android.system.StructStat;
163import android.text.TextUtils;
164import android.text.format.DateUtils;
165import android.util.ArrayMap;
166import android.util.ArraySet;
167import android.util.AtomicFile;
168import android.util.DisplayMetrics;
169import android.util.EventLog;
170import android.util.ExceptionUtils;
171import android.util.Log;
172import android.util.LogPrinter;
173import android.util.PrintStreamPrinter;
174import android.util.Slog;
175import android.util.SparseArray;
176import android.util.SparseBooleanArray;
177import android.util.Xml;
178import android.view.Display;
179
180import dalvik.system.DexFile;
181import dalvik.system.VMRuntime;
182
183import libcore.io.IoUtils;
184import libcore.util.EmptyArray;
185
186import com.android.internal.R;
187import com.android.internal.app.IMediaContainerService;
188import com.android.internal.app.ResolverActivity;
189import com.android.internal.content.NativeLibraryHelper;
190import com.android.internal.content.PackageHelper;
191import com.android.internal.os.IParcelFileDescriptorFactory;
192import com.android.internal.util.ArrayUtils;
193import com.android.internal.util.FastPrintWriter;
194import com.android.internal.util.FastXmlSerializer;
195import com.android.internal.util.IndentingPrintWriter;
196import com.android.server.EventLogTags;
197import com.android.server.IntentResolver;
198import com.android.server.LocalServices;
199import com.android.server.ServiceThread;
200import com.android.server.SystemConfig;
201import com.android.server.Watchdog;
202import com.android.server.pm.Settings.DatabaseVersion;
203import com.android.server.storage.DeviceStorageMonitorInternal;
204
205import org.xmlpull.v1.XmlSerializer;
206
207import java.io.BufferedInputStream;
208import java.io.BufferedOutputStream;
209import java.io.BufferedReader;
210import java.io.ByteArrayInputStream;
211import java.io.ByteArrayOutputStream;
212import java.io.File;
213import java.io.FileDescriptor;
214import java.io.FileNotFoundException;
215import java.io.FileOutputStream;
216import java.io.FileReader;
217import java.io.FilenameFilter;
218import java.io.IOException;
219import java.io.InputStream;
220import java.io.PrintWriter;
221import java.nio.charset.StandardCharsets;
222import java.security.NoSuchAlgorithmException;
223import java.security.PublicKey;
224import java.security.cert.CertificateEncodingException;
225import java.security.cert.CertificateException;
226import java.text.SimpleDateFormat;
227import java.util.ArrayList;
228import java.util.Arrays;
229import java.util.Collection;
230import java.util.Collections;
231import java.util.Comparator;
232import java.util.Date;
233import java.util.Iterator;
234import java.util.List;
235import java.util.Map;
236import java.util.Objects;
237import java.util.Set;
238import java.util.concurrent.atomic.AtomicBoolean;
239import java.util.concurrent.atomic.AtomicLong;
240
241/**
242 * Keep track of all those .apks everywhere.
243 *
244 * This is very central to the platform's security; please run the unit
245 * tests whenever making modifications here:
246 *
247mmm frameworks/base/tests/AndroidTests
248adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
249adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
250 *
251 * {@hide}
252 */
253public class PackageManagerService extends IPackageManager.Stub {
254    static final String TAG = "PackageManager";
255    static final boolean DEBUG_SETTINGS = false;
256    static final boolean DEBUG_PREFERRED = false;
257    static final boolean DEBUG_UPGRADE = false;
258    private static final boolean DEBUG_BACKUP = true;
259    private static final boolean DEBUG_INSTALL = false;
260    private static final boolean DEBUG_REMOVE = false;
261    private static final boolean DEBUG_BROADCASTS = false;
262    private static final boolean DEBUG_SHOW_INFO = false;
263    private static final boolean DEBUG_PACKAGE_INFO = false;
264    private static final boolean DEBUG_INTENT_MATCHING = false;
265    private static final boolean DEBUG_PACKAGE_SCANNING = false;
266    private static final boolean DEBUG_VERIFY = false;
267    private static final boolean DEBUG_DEXOPT = false;
268    private static final boolean DEBUG_ABI_SELECTION = false;
269
270    static final boolean RUNTIME_PERMISSIONS_ENABLED =
271            SystemProperties.getInt("ro.runtime.permissions.enabled", 0) == 1;
272
273    private static final int RADIO_UID = Process.PHONE_UID;
274    private static final int LOG_UID = Process.LOG_UID;
275    private static final int NFC_UID = Process.NFC_UID;
276    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
277    private static final int SHELL_UID = Process.SHELL_UID;
278
279    // Cap the size of permission trees that 3rd party apps can define
280    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
281
282    // Suffix used during package installation when copying/moving
283    // package apks to install directory.
284    private static final String INSTALL_PACKAGE_SUFFIX = "-";
285
286    static final int SCAN_NO_DEX = 1<<1;
287    static final int SCAN_FORCE_DEX = 1<<2;
288    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
289    static final int SCAN_NEW_INSTALL = 1<<4;
290    static final int SCAN_NO_PATHS = 1<<5;
291    static final int SCAN_UPDATE_TIME = 1<<6;
292    static final int SCAN_DEFER_DEX = 1<<7;
293    static final int SCAN_BOOTING = 1<<8;
294    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
295    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
296    static final int SCAN_REPLACING = 1<<11;
297    static final int SCAN_REQUIRE_KNOWN = 1<<12;
298
299    static final int REMOVE_CHATTY = 1<<16;
300
301    /**
302     * Timeout (in milliseconds) after which the watchdog should declare that
303     * our handler thread is wedged.  The usual default for such things is one
304     * minute but we sometimes do very lengthy I/O operations on this thread,
305     * such as installing multi-gigabyte applications, so ours needs to be longer.
306     */
307    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
308
309    /**
310     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
311     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
312     * settings entry if available, otherwise we use the hardcoded default.  If it's been
313     * more than this long since the last fstrim, we force one during the boot sequence.
314     *
315     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
316     * one gets run at the next available charging+idle time.  This final mandatory
317     * no-fstrim check kicks in only of the other scheduling criteria is never met.
318     */
319    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
320
321    /**
322     * Whether verification is enabled by default.
323     */
324    private static final boolean DEFAULT_VERIFY_ENABLE = true;
325
326    /**
327     * The default maximum time to wait for the verification agent to return in
328     * milliseconds.
329     */
330    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
331
332    /**
333     * The default response for package verification timeout.
334     *
335     * This can be either PackageManager.VERIFICATION_ALLOW or
336     * PackageManager.VERIFICATION_REJECT.
337     */
338    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
339
340    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
341
342    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
343            DEFAULT_CONTAINER_PACKAGE,
344            "com.android.defcontainer.DefaultContainerService");
345
346    private static final String KILL_APP_REASON_GIDS_CHANGED =
347            "permission grant or revoke changed gids";
348
349    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
350            "permissions revoked";
351
352    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
353
354    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
355
356    /** Permission grant: not grant the permission. */
357    private static final int GRANT_DENIED = 1;
358
359    /** Permission grant: grant the permission as an install permission. */
360    private static final int GRANT_INSTALL = 2;
361
362    /** Permission grant: grant the permission as a runtime one. */
363    private static final int GRANT_RUNTIME = 3;
364
365    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
366    private static final int GRANT_UPGRADE = 4;
367
368    final ServiceThread mHandlerThread;
369
370    final PackageHandler mHandler;
371
372    /**
373     * Messages for {@link #mHandler} that need to wait for system ready before
374     * being dispatched.
375     */
376    private ArrayList<Message> mPostSystemReadyMessages;
377
378    final int mSdkVersion = Build.VERSION.SDK_INT;
379
380    final Context mContext;
381    final boolean mFactoryTest;
382    final boolean mOnlyCore;
383    final boolean mLazyDexOpt;
384    final long mDexOptLRUThresholdInMills;
385    final DisplayMetrics mMetrics;
386    final int mDefParseFlags;
387    final String[] mSeparateProcesses;
388    final boolean mIsUpgrade;
389
390    // This is where all application persistent data goes.
391    final File mAppDataDir;
392
393    // This is where all application persistent data goes for secondary users.
394    final File mUserAppDataDir;
395
396    /** The location for ASEC container files on internal storage. */
397    final String mAsecInternalPath;
398
399    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
400    // LOCK HELD.  Can be called with mInstallLock held.
401    final Installer mInstaller;
402
403    /** Directory where installed third-party apps stored */
404    final File mAppInstallDir;
405
406    /**
407     * Directory to which applications installed internally have their
408     * 32 bit native libraries copied.
409     */
410    private File mAppLib32InstallDir;
411
412    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
413    // apps.
414    final File mDrmAppPrivateInstallDir;
415
416    // ----------------------------------------------------------------
417
418    // Lock for state used when installing and doing other long running
419    // operations.  Methods that must be called with this lock held have
420    // the suffix "LI".
421    final Object mInstallLock = new Object();
422
423    // ----------------------------------------------------------------
424
425    // Keys are String (package name), values are Package.  This also serves
426    // as the lock for the global state.  Methods that must be called with
427    // this lock held have the prefix "LP".
428    final ArrayMap<String, PackageParser.Package> mPackages =
429            new ArrayMap<String, PackageParser.Package>();
430
431    // Tracks available target package names -> overlay package paths.
432    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
433        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
434
435    final Settings mSettings;
436    boolean mRestoredSettings;
437
438    // System configuration read by SystemConfig.
439    final int[] mGlobalGids;
440    final SparseArray<ArraySet<String>> mSystemPermissions;
441    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
442
443    // If mac_permissions.xml was found for seinfo labeling.
444    boolean mFoundPolicyFile;
445
446    // If a recursive restorecon of /data/data/<pkg> is needed.
447    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
448
449    public static final class SharedLibraryEntry {
450        public final String path;
451        public final String apk;
452
453        SharedLibraryEntry(String _path, String _apk) {
454            path = _path;
455            apk = _apk;
456        }
457    }
458
459    // Currently known shared libraries.
460    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
461            new ArrayMap<String, SharedLibraryEntry>();
462
463    // All available activities, for your resolving pleasure.
464    final ActivityIntentResolver mActivities =
465            new ActivityIntentResolver();
466
467    // All available receivers, for your resolving pleasure.
468    final ActivityIntentResolver mReceivers =
469            new ActivityIntentResolver();
470
471    // All available services, for your resolving pleasure.
472    final ServiceIntentResolver mServices = new ServiceIntentResolver();
473
474    // All available providers, for your resolving pleasure.
475    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
476
477    // Mapping from provider base names (first directory in content URI codePath)
478    // to the provider information.
479    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
480            new ArrayMap<String, PackageParser.Provider>();
481
482    // Mapping from instrumentation class names to info about them.
483    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
484            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
485
486    // Mapping from permission names to info about them.
487    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
488            new ArrayMap<String, PackageParser.PermissionGroup>();
489
490    // Packages whose data we have transfered into another package, thus
491    // should no longer exist.
492    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
493
494    // Broadcast actions that are only available to the system.
495    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
496
497    /** List of packages waiting for verification. */
498    final SparseArray<PackageVerificationState> mPendingVerification
499            = new SparseArray<PackageVerificationState>();
500
501    /** Set of packages associated with each app op permission. */
502    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
503
504    final PackageInstallerService mInstallerService;
505
506    private final PackageDexOptimizer mPackageDexOptimizer;
507    // Cache of users who need badging.
508    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
509
510    /** Token for keys in mPendingVerification. */
511    private int mPendingVerificationToken = 0;
512
513    volatile boolean mSystemReady;
514    volatile boolean mSafeMode;
515    volatile boolean mHasSystemUidErrors;
516
517    ApplicationInfo mAndroidApplication;
518    final ActivityInfo mResolveActivity = new ActivityInfo();
519    final ResolveInfo mResolveInfo = new ResolveInfo();
520    ComponentName mResolveComponentName;
521    PackageParser.Package mPlatformPackage;
522    ComponentName mCustomResolverComponentName;
523
524    boolean mResolverReplaced = false;
525
526    private final ComponentName mIntentFilterVerifierComponent;
527    private int mIntentFilterVerificationToken = 0;
528
529    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
530            = new SparseArray<IntentFilterVerificationState>();
531
532    private interface IntentFilterVerifier<T extends IntentFilter> {
533        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
534                                               T filter, String packageName);
535        void startVerifications(int userId);
536        void receiveVerificationResponse(int verificationId);
537    }
538
539    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
540        private Context mContext;
541        private ComponentName mIntentFilterVerifierComponent;
542        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
543
544        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
545            mContext = context;
546            mIntentFilterVerifierComponent = verifierComponent;
547        }
548
549        private String getDefaultScheme() {
550            // TODO: replace SCHEME_HTTP with SCHEME_HTTPS
551            return IntentFilter.SCHEME_HTTP;
552        }
553
554        @Override
555        public void startVerifications(int userId) {
556            // Launch verifications requests
557            int count = mCurrentIntentFilterVerifications.size();
558            for (int n=0; n<count; n++) {
559                int verificationId = mCurrentIntentFilterVerifications.get(n);
560                final IntentFilterVerificationState ivs =
561                        mIntentFilterVerificationStates.get(verificationId);
562
563                String packageName = ivs.getPackageName();
564                boolean modified = false;
565
566                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
567                final int filterCount = filters.size();
568                for (int m=0; m<filterCount; m++) {
569                    PackageParser.ActivityIntentInfo filter = filters.get(m);
570                    synchronized (mPackages) {
571                        modified = mSettings.createIntentFilterVerificationIfNeededLPw(
572                                packageName, filter.getHosts());
573                    }
574                }
575                synchronized (mPackages) {
576                    if (modified) {
577                        scheduleWriteSettingsLocked();
578                    }
579                }
580                sendVerificationRequest(userId, verificationId, ivs);
581            }
582            mCurrentIntentFilterVerifications.clear();
583        }
584
585        private void sendVerificationRequest(int userId, int verificationId,
586                                             IntentFilterVerificationState ivs) {
587
588            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
589            verificationIntent.putExtra(
590                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
591                    verificationId);
592            verificationIntent.putExtra(
593                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
594                    getDefaultScheme());
595            verificationIntent.putExtra(
596                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
597                    ivs.getHostsString());
598            verificationIntent.putExtra(
599                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
600                    ivs.getPackageName());
601            verificationIntent.setComponent(mIntentFilterVerifierComponent);
602            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
603
604            UserHandle user = new UserHandle(userId);
605            mContext.sendBroadcastAsUser(verificationIntent, user);
606            Slog.d(TAG, "Sending IntenFilter verification broadcast");
607        }
608
609        public void receiveVerificationResponse(int verificationId) {
610            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
611
612            final boolean verified = ivs.isVerified();
613
614            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
615            final int count = filters.size();
616            for (int n=0; n<count; n++) {
617                PackageParser.ActivityIntentInfo filter = filters.get(n);
618                filter.setVerified(verified);
619
620                Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:"
621                        + verified + " and hosts:" + ivs.getHostsString());
622            }
623
624            mIntentFilterVerificationStates.remove(verificationId);
625
626            final String packageName = ivs.getPackageName();
627            IntentFilterVerificationInfo ivi = null;
628
629            synchronized (mPackages) {
630                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
631            }
632            if (ivi == null) {
633                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
634                        + verificationId + " packageName:" + packageName);
635                return;
636            }
637            Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId: "
638                    + verificationId);
639
640            synchronized (mPackages) {
641                if (verified) {
642                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
643                } else {
644                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
645                }
646                scheduleWriteSettingsLocked();
647
648                final int userId = ivs.getUserId();
649                if (userId != UserHandle.USER_ALL) {
650                    final int userStatus =
651                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
652
653                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
654                    boolean needUpdate = false;
655
656                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
657                    // already been set by the User thru the Disambiguation dialog
658                    switch (userStatus) {
659                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
660                            if (verified) {
661                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
662                            } else {
663                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
664                            }
665                            needUpdate = true;
666                            break;
667
668                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
669                            if (verified) {
670                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
671                                needUpdate = true;
672                            }
673                            break;
674
675                        default:
676                            // Nothing to do
677                    }
678
679                    if (needUpdate) {
680                        mSettings.updateIntentFilterVerificationStatusLPw(
681                                packageName, updatedStatus, userId);
682                        scheduleWritePackageRestrictionsLocked(userId);
683                    }
684                }
685            }
686        }
687
688        @Override
689        public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
690                    ActivityIntentInfo filter, String packageName) {
691            if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
692                    filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
693                Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme");
694                return false;
695            }
696            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
697            if (ivs == null) {
698                ivs = createDomainVerificationState(verifierId, userId, verificationId,
699                        packageName);
700            }
701            ArrayList<String> hosts = filter.getHostsList();
702            if (!hasValidHosts(hosts)) {
703                return false;
704            }
705            ivs.addFilter(filter);
706            return true;
707        }
708
709        private IntentFilterVerificationState createDomainVerificationState(int verifierId,
710                int userId, int verificationId, String packageName) {
711            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
712                    verifierId, userId, packageName);
713            ivs.setPendingState();
714            synchronized (mPackages) {
715                mIntentFilterVerificationStates.append(verificationId, ivs);
716                mCurrentIntentFilterVerifications.add(verificationId);
717            }
718            return ivs;
719        }
720
721        private boolean hasValidHosts(ArrayList<String> hosts) {
722            if (hosts.size() == 0) {
723                Slog.d(TAG, "IntentFilter does not contain any data hosts");
724                return false;
725            }
726            String hostEndBase = null;
727            for (String host : hosts) {
728                String[] hostParts = host.split("\\.");
729                // Should be at minimum a host like "example.com"
730                if (hostParts.length < 2) {
731                    Slog.d(TAG, "IntentFilter does not contain a valid data host name: " + host);
732                    return false;
733                }
734                // Verify that we have the same ending domain
735                int length = hostParts.length;
736                String hostEnd = hostParts[length - 1] + hostParts[length - 2];
737                if (hostEndBase == null) {
738                    hostEndBase = hostEnd;
739                }
740                if (!hostEnd.equalsIgnoreCase(hostEndBase)) {
741                    Slog.d(TAG, "IntentFilter does not contain the same data domains");
742                    return false;
743                }
744            }
745            return true;
746        }
747    }
748
749    private IntentFilterVerifier mIntentFilterVerifier;
750
751    // Set of pending broadcasts for aggregating enable/disable of components.
752    static class PendingPackageBroadcasts {
753        // for each user id, a map of <package name -> components within that package>
754        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
755
756        public PendingPackageBroadcasts() {
757            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
758        }
759
760        public ArrayList<String> get(int userId, String packageName) {
761            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
762            return packages.get(packageName);
763        }
764
765        public void put(int userId, String packageName, ArrayList<String> components) {
766            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
767            packages.put(packageName, components);
768        }
769
770        public void remove(int userId, String packageName) {
771            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
772            if (packages != null) {
773                packages.remove(packageName);
774            }
775        }
776
777        public void remove(int userId) {
778            mUidMap.remove(userId);
779        }
780
781        public int userIdCount() {
782            return mUidMap.size();
783        }
784
785        public int userIdAt(int n) {
786            return mUidMap.keyAt(n);
787        }
788
789        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
790            return mUidMap.get(userId);
791        }
792
793        public int size() {
794            // total number of pending broadcast entries across all userIds
795            int num = 0;
796            for (int i = 0; i< mUidMap.size(); i++) {
797                num += mUidMap.valueAt(i).size();
798            }
799            return num;
800        }
801
802        public void clear() {
803            mUidMap.clear();
804        }
805
806        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
807            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
808            if (map == null) {
809                map = new ArrayMap<String, ArrayList<String>>();
810                mUidMap.put(userId, map);
811            }
812            return map;
813        }
814    }
815    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
816
817    // Service Connection to remote media container service to copy
818    // package uri's from external media onto secure containers
819    // or internal storage.
820    private IMediaContainerService mContainerService = null;
821
822    static final int SEND_PENDING_BROADCAST = 1;
823    static final int MCS_BOUND = 3;
824    static final int END_COPY = 4;
825    static final int INIT_COPY = 5;
826    static final int MCS_UNBIND = 6;
827    static final int START_CLEANING_PACKAGE = 7;
828    static final int FIND_INSTALL_LOC = 8;
829    static final int POST_INSTALL = 9;
830    static final int MCS_RECONNECT = 10;
831    static final int MCS_GIVE_UP = 11;
832    static final int UPDATED_MEDIA_STATUS = 12;
833    static final int WRITE_SETTINGS = 13;
834    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
835    static final int PACKAGE_VERIFIED = 15;
836    static final int CHECK_PENDING_VERIFICATION = 16;
837    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
838    static final int INTENT_FILTER_VERIFIED = 18;
839
840    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
841
842    // Delay time in millisecs
843    static final int BROADCAST_DELAY = 10 * 1000;
844
845    static UserManagerService sUserManager;
846
847    // Stores a list of users whose package restrictions file needs to be updated
848    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
849
850    final private DefaultContainerConnection mDefContainerConn =
851            new DefaultContainerConnection();
852    class DefaultContainerConnection implements ServiceConnection {
853        public void onServiceConnected(ComponentName name, IBinder service) {
854            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
855            IMediaContainerService imcs =
856                IMediaContainerService.Stub.asInterface(service);
857            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
858        }
859
860        public void onServiceDisconnected(ComponentName name) {
861            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
862        }
863    };
864
865    // Recordkeeping of restore-after-install operations that are currently in flight
866    // between the Package Manager and the Backup Manager
867    class PostInstallData {
868        public InstallArgs args;
869        public PackageInstalledInfo res;
870
871        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
872            args = _a;
873            res = _r;
874        }
875    };
876    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
877    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
878
879    // backup/restore of preferred activity state
880    private static final String TAG_PREFERRED_BACKUP = "pa";
881
882    private final String mRequiredVerifierPackage;
883
884    private final PackageUsage mPackageUsage = new PackageUsage();
885
886    private class PackageUsage {
887        private static final int WRITE_INTERVAL
888            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
889
890        private final Object mFileLock = new Object();
891        private final AtomicLong mLastWritten = new AtomicLong(0);
892        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
893
894        private boolean mIsHistoricalPackageUsageAvailable = true;
895
896        boolean isHistoricalPackageUsageAvailable() {
897            return mIsHistoricalPackageUsageAvailable;
898        }
899
900        void write(boolean force) {
901            if (force) {
902                writeInternal();
903                return;
904            }
905            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
906                && !DEBUG_DEXOPT) {
907                return;
908            }
909            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
910                new Thread("PackageUsage_DiskWriter") {
911                    @Override
912                    public void run() {
913                        try {
914                            writeInternal();
915                        } finally {
916                            mBackgroundWriteRunning.set(false);
917                        }
918                    }
919                }.start();
920            }
921        }
922
923        private void writeInternal() {
924            synchronized (mPackages) {
925                synchronized (mFileLock) {
926                    AtomicFile file = getFile();
927                    FileOutputStream f = null;
928                    try {
929                        f = file.startWrite();
930                        BufferedOutputStream out = new BufferedOutputStream(f);
931                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
932                        StringBuilder sb = new StringBuilder();
933                        for (PackageParser.Package pkg : mPackages.values()) {
934                            if (pkg.mLastPackageUsageTimeInMills == 0) {
935                                continue;
936                            }
937                            sb.setLength(0);
938                            sb.append(pkg.packageName);
939                            sb.append(' ');
940                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
941                            sb.append('\n');
942                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
943                        }
944                        out.flush();
945                        file.finishWrite(f);
946                    } catch (IOException e) {
947                        if (f != null) {
948                            file.failWrite(f);
949                        }
950                        Log.e(TAG, "Failed to write package usage times", e);
951                    }
952                }
953            }
954            mLastWritten.set(SystemClock.elapsedRealtime());
955        }
956
957        void readLP() {
958            synchronized (mFileLock) {
959                AtomicFile file = getFile();
960                BufferedInputStream in = null;
961                try {
962                    in = new BufferedInputStream(file.openRead());
963                    StringBuffer sb = new StringBuffer();
964                    while (true) {
965                        String packageName = readToken(in, sb, ' ');
966                        if (packageName == null) {
967                            break;
968                        }
969                        String timeInMillisString = readToken(in, sb, '\n');
970                        if (timeInMillisString == null) {
971                            throw new IOException("Failed to find last usage time for package "
972                                                  + packageName);
973                        }
974                        PackageParser.Package pkg = mPackages.get(packageName);
975                        if (pkg == null) {
976                            continue;
977                        }
978                        long timeInMillis;
979                        try {
980                            timeInMillis = Long.parseLong(timeInMillisString.toString());
981                        } catch (NumberFormatException e) {
982                            throw new IOException("Failed to parse " + timeInMillisString
983                                                  + " as a long.", e);
984                        }
985                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
986                    }
987                } catch (FileNotFoundException expected) {
988                    mIsHistoricalPackageUsageAvailable = false;
989                } catch (IOException e) {
990                    Log.w(TAG, "Failed to read package usage times", e);
991                } finally {
992                    IoUtils.closeQuietly(in);
993                }
994            }
995            mLastWritten.set(SystemClock.elapsedRealtime());
996        }
997
998        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
999                throws IOException {
1000            sb.setLength(0);
1001            while (true) {
1002                int ch = in.read();
1003                if (ch == -1) {
1004                    if (sb.length() == 0) {
1005                        return null;
1006                    }
1007                    throw new IOException("Unexpected EOF");
1008                }
1009                if (ch == endOfToken) {
1010                    return sb.toString();
1011                }
1012                sb.append((char)ch);
1013            }
1014        }
1015
1016        private AtomicFile getFile() {
1017            File dataDir = Environment.getDataDirectory();
1018            File systemDir = new File(dataDir, "system");
1019            File fname = new File(systemDir, "package-usage.list");
1020            return new AtomicFile(fname);
1021        }
1022    }
1023
1024    class PackageHandler extends Handler {
1025        private boolean mBound = false;
1026        final ArrayList<HandlerParams> mPendingInstalls =
1027            new ArrayList<HandlerParams>();
1028
1029        private boolean connectToService() {
1030            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1031                    " DefaultContainerService");
1032            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1033            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1034            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1035                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1036                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1037                mBound = true;
1038                return true;
1039            }
1040            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1041            return false;
1042        }
1043
1044        private void disconnectService() {
1045            mContainerService = null;
1046            mBound = false;
1047            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1048            mContext.unbindService(mDefContainerConn);
1049            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1050        }
1051
1052        PackageHandler(Looper looper) {
1053            super(looper);
1054        }
1055
1056        public void handleMessage(Message msg) {
1057            try {
1058                doHandleMessage(msg);
1059            } finally {
1060                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1061            }
1062        }
1063
1064        void doHandleMessage(Message msg) {
1065            switch (msg.what) {
1066                case INIT_COPY: {
1067                    HandlerParams params = (HandlerParams) msg.obj;
1068                    int idx = mPendingInstalls.size();
1069                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1070                    // If a bind was already initiated we dont really
1071                    // need to do anything. The pending install
1072                    // will be processed later on.
1073                    if (!mBound) {
1074                        // If this is the only one pending we might
1075                        // have to bind to the service again.
1076                        if (!connectToService()) {
1077                            Slog.e(TAG, "Failed to bind to media container service");
1078                            params.serviceError();
1079                            return;
1080                        } else {
1081                            // Once we bind to the service, the first
1082                            // pending request will be processed.
1083                            mPendingInstalls.add(idx, params);
1084                        }
1085                    } else {
1086                        mPendingInstalls.add(idx, params);
1087                        // Already bound to the service. Just make
1088                        // sure we trigger off processing the first request.
1089                        if (idx == 0) {
1090                            mHandler.sendEmptyMessage(MCS_BOUND);
1091                        }
1092                    }
1093                    break;
1094                }
1095                case MCS_BOUND: {
1096                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1097                    if (msg.obj != null) {
1098                        mContainerService = (IMediaContainerService) msg.obj;
1099                    }
1100                    if (mContainerService == null) {
1101                        // Something seriously wrong. Bail out
1102                        Slog.e(TAG, "Cannot bind to media container service");
1103                        for (HandlerParams params : mPendingInstalls) {
1104                            // Indicate service bind error
1105                            params.serviceError();
1106                        }
1107                        mPendingInstalls.clear();
1108                    } else if (mPendingInstalls.size() > 0) {
1109                        HandlerParams params = mPendingInstalls.get(0);
1110                        if (params != null) {
1111                            if (params.startCopy()) {
1112                                // We are done...  look for more work or to
1113                                // go idle.
1114                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1115                                        "Checking for more work or unbind...");
1116                                // Delete pending install
1117                                if (mPendingInstalls.size() > 0) {
1118                                    mPendingInstalls.remove(0);
1119                                }
1120                                if (mPendingInstalls.size() == 0) {
1121                                    if (mBound) {
1122                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1123                                                "Posting delayed MCS_UNBIND");
1124                                        removeMessages(MCS_UNBIND);
1125                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1126                                        // Unbind after a little delay, to avoid
1127                                        // continual thrashing.
1128                                        sendMessageDelayed(ubmsg, 10000);
1129                                    }
1130                                } else {
1131                                    // There are more pending requests in queue.
1132                                    // Just post MCS_BOUND message to trigger processing
1133                                    // of next pending install.
1134                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1135                                            "Posting MCS_BOUND for next work");
1136                                    mHandler.sendEmptyMessage(MCS_BOUND);
1137                                }
1138                            }
1139                        }
1140                    } else {
1141                        // Should never happen ideally.
1142                        Slog.w(TAG, "Empty queue");
1143                    }
1144                    break;
1145                }
1146                case MCS_RECONNECT: {
1147                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1148                    if (mPendingInstalls.size() > 0) {
1149                        if (mBound) {
1150                            disconnectService();
1151                        }
1152                        if (!connectToService()) {
1153                            Slog.e(TAG, "Failed to bind to media container service");
1154                            for (HandlerParams params : mPendingInstalls) {
1155                                // Indicate service bind error
1156                                params.serviceError();
1157                            }
1158                            mPendingInstalls.clear();
1159                        }
1160                    }
1161                    break;
1162                }
1163                case MCS_UNBIND: {
1164                    // If there is no actual work left, then time to unbind.
1165                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1166
1167                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1168                        if (mBound) {
1169                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1170
1171                            disconnectService();
1172                        }
1173                    } else if (mPendingInstalls.size() > 0) {
1174                        // There are more pending requests in queue.
1175                        // Just post MCS_BOUND message to trigger processing
1176                        // of next pending install.
1177                        mHandler.sendEmptyMessage(MCS_BOUND);
1178                    }
1179
1180                    break;
1181                }
1182                case MCS_GIVE_UP: {
1183                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1184                    mPendingInstalls.remove(0);
1185                    break;
1186                }
1187                case SEND_PENDING_BROADCAST: {
1188                    String packages[];
1189                    ArrayList<String> components[];
1190                    int size = 0;
1191                    int uids[];
1192                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1193                    synchronized (mPackages) {
1194                        if (mPendingBroadcasts == null) {
1195                            return;
1196                        }
1197                        size = mPendingBroadcasts.size();
1198                        if (size <= 0) {
1199                            // Nothing to be done. Just return
1200                            return;
1201                        }
1202                        packages = new String[size];
1203                        components = new ArrayList[size];
1204                        uids = new int[size];
1205                        int i = 0;  // filling out the above arrays
1206
1207                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1208                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1209                            Iterator<Map.Entry<String, ArrayList<String>>> it
1210                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1211                                            .entrySet().iterator();
1212                            while (it.hasNext() && i < size) {
1213                                Map.Entry<String, ArrayList<String>> ent = it.next();
1214                                packages[i] = ent.getKey();
1215                                components[i] = ent.getValue();
1216                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1217                                uids[i] = (ps != null)
1218                                        ? UserHandle.getUid(packageUserId, ps.appId)
1219                                        : -1;
1220                                i++;
1221                            }
1222                        }
1223                        size = i;
1224                        mPendingBroadcasts.clear();
1225                    }
1226                    // Send broadcasts
1227                    for (int i = 0; i < size; i++) {
1228                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1229                    }
1230                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1231                    break;
1232                }
1233                case START_CLEANING_PACKAGE: {
1234                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1235                    final String packageName = (String)msg.obj;
1236                    final int userId = msg.arg1;
1237                    final boolean andCode = msg.arg2 != 0;
1238                    synchronized (mPackages) {
1239                        if (userId == UserHandle.USER_ALL) {
1240                            int[] users = sUserManager.getUserIds();
1241                            for (int user : users) {
1242                                mSettings.addPackageToCleanLPw(
1243                                        new PackageCleanItem(user, packageName, andCode));
1244                            }
1245                        } else {
1246                            mSettings.addPackageToCleanLPw(
1247                                    new PackageCleanItem(userId, packageName, andCode));
1248                        }
1249                    }
1250                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1251                    startCleaningPackages();
1252                } break;
1253                case POST_INSTALL: {
1254                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1255                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1256                    mRunningInstalls.delete(msg.arg1);
1257                    boolean deleteOld = false;
1258
1259                    if (data != null) {
1260                        InstallArgs args = data.args;
1261                        PackageInstalledInfo res = data.res;
1262
1263                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1264                            res.removedInfo.sendBroadcast(false, true, false);
1265                            Bundle extras = new Bundle(1);
1266                            extras.putInt(Intent.EXTRA_UID, res.uid);
1267
1268                            // Now that we successfully installed the package, grant runtime
1269                            // permissions if requested before broadcasting the install.
1270                            if ((args.installFlags
1271                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1272                                grantRequestedRuntimePermissions(res.pkg,
1273                                        args.user.getIdentifier());
1274                            }
1275
1276                            // Determine the set of users who are adding this
1277                            // package for the first time vs. those who are seeing
1278                            // an update.
1279                            int[] firstUsers;
1280                            int[] updateUsers = new int[0];
1281                            if (res.origUsers == null || res.origUsers.length == 0) {
1282                                firstUsers = res.newUsers;
1283                            } else {
1284                                firstUsers = new int[0];
1285                                for (int i=0; i<res.newUsers.length; i++) {
1286                                    int user = res.newUsers[i];
1287                                    boolean isNew = true;
1288                                    for (int j=0; j<res.origUsers.length; j++) {
1289                                        if (res.origUsers[j] == user) {
1290                                            isNew = false;
1291                                            break;
1292                                        }
1293                                    }
1294                                    if (isNew) {
1295                                        int[] newFirst = new int[firstUsers.length+1];
1296                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1297                                                firstUsers.length);
1298                                        newFirst[firstUsers.length] = user;
1299                                        firstUsers = newFirst;
1300                                    } else {
1301                                        int[] newUpdate = new int[updateUsers.length+1];
1302                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1303                                                updateUsers.length);
1304                                        newUpdate[updateUsers.length] = user;
1305                                        updateUsers = newUpdate;
1306                                    }
1307                                }
1308                            }
1309                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1310                                    res.pkg.applicationInfo.packageName,
1311                                    extras, null, null, firstUsers);
1312                            final boolean update = res.removedInfo.removedPackage != null;
1313                            if (update) {
1314                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1315                            }
1316                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1317                                    res.pkg.applicationInfo.packageName,
1318                                    extras, null, null, updateUsers);
1319                            if (update) {
1320                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1321                                        res.pkg.applicationInfo.packageName,
1322                                        extras, null, null, updateUsers);
1323                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1324                                        null, null,
1325                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1326
1327                                // treat asec-hosted packages like removable media on upgrade
1328                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1329                                    if (DEBUG_INSTALL) {
1330                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1331                                                + " is ASEC-hosted -> AVAILABLE");
1332                                    }
1333                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1334                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1335                                    pkgList.add(res.pkg.applicationInfo.packageName);
1336                                    sendResourcesChangedBroadcast(true, true,
1337                                            pkgList,uidArray, null);
1338                                }
1339                            }
1340                            if (res.removedInfo.args != null) {
1341                                // Remove the replaced package's older resources safely now
1342                                deleteOld = true;
1343                            }
1344
1345                            // Log current value of "unknown sources" setting
1346                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1347                                getUnknownSourcesSettings());
1348                        }
1349                        // Force a gc to clear up things
1350                        Runtime.getRuntime().gc();
1351                        // We delete after a gc for applications  on sdcard.
1352                        if (deleteOld) {
1353                            synchronized (mInstallLock) {
1354                                res.removedInfo.args.doPostDeleteLI(true);
1355                            }
1356                        }
1357                        if (args.observer != null) {
1358                            try {
1359                                Bundle extras = extrasForInstallResult(res);
1360                                args.observer.onPackageInstalled(res.name, res.returnCode,
1361                                        res.returnMsg, extras);
1362                            } catch (RemoteException e) {
1363                                Slog.i(TAG, "Observer no longer exists.");
1364                            }
1365                        }
1366                    } else {
1367                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1368                    }
1369                } break;
1370                case UPDATED_MEDIA_STATUS: {
1371                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1372                    boolean reportStatus = msg.arg1 == 1;
1373                    boolean doGc = msg.arg2 == 1;
1374                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1375                    if (doGc) {
1376                        // Force a gc to clear up stale containers.
1377                        Runtime.getRuntime().gc();
1378                    }
1379                    if (msg.obj != null) {
1380                        @SuppressWarnings("unchecked")
1381                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1382                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1383                        // Unload containers
1384                        unloadAllContainers(args);
1385                    }
1386                    if (reportStatus) {
1387                        try {
1388                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1389                            PackageHelper.getMountService().finishMediaUpdate();
1390                        } catch (RemoteException e) {
1391                            Log.e(TAG, "MountService not running?");
1392                        }
1393                    }
1394                } break;
1395                case WRITE_SETTINGS: {
1396                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1397                    synchronized (mPackages) {
1398                        removeMessages(WRITE_SETTINGS);
1399                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1400                        mSettings.writeLPr();
1401                        mDirtyUsers.clear();
1402                    }
1403                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1404                } break;
1405                case WRITE_PACKAGE_RESTRICTIONS: {
1406                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1407                    synchronized (mPackages) {
1408                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1409                        for (int userId : mDirtyUsers) {
1410                            mSettings.writePackageRestrictionsLPr(userId);
1411                        }
1412                        mDirtyUsers.clear();
1413                    }
1414                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1415                } break;
1416                case CHECK_PENDING_VERIFICATION: {
1417                    final int verificationId = msg.arg1;
1418                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1419
1420                    if ((state != null) && !state.timeoutExtended()) {
1421                        final InstallArgs args = state.getInstallArgs();
1422                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1423
1424                        Slog.i(TAG, "Verification timed out for " + originUri);
1425                        mPendingVerification.remove(verificationId);
1426
1427                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1428
1429                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1430                            Slog.i(TAG, "Continuing with installation of " + originUri);
1431                            state.setVerifierResponse(Binder.getCallingUid(),
1432                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1433                            broadcastPackageVerified(verificationId, originUri,
1434                                    PackageManager.VERIFICATION_ALLOW,
1435                                    state.getInstallArgs().getUser());
1436                            try {
1437                                ret = args.copyApk(mContainerService, true);
1438                            } catch (RemoteException e) {
1439                                Slog.e(TAG, "Could not contact the ContainerService");
1440                            }
1441                        } else {
1442                            broadcastPackageVerified(verificationId, originUri,
1443                                    PackageManager.VERIFICATION_REJECT,
1444                                    state.getInstallArgs().getUser());
1445                        }
1446
1447                        processPendingInstall(args, ret);
1448                        mHandler.sendEmptyMessage(MCS_UNBIND);
1449                    }
1450                    break;
1451                }
1452                case PACKAGE_VERIFIED: {
1453                    final int verificationId = msg.arg1;
1454
1455                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1456                    if (state == null) {
1457                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1458                        break;
1459                    }
1460
1461                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1462
1463                    state.setVerifierResponse(response.callerUid, response.code);
1464
1465                    if (state.isVerificationComplete()) {
1466                        mPendingVerification.remove(verificationId);
1467
1468                        final InstallArgs args = state.getInstallArgs();
1469                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1470
1471                        int ret;
1472                        if (state.isInstallAllowed()) {
1473                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1474                            broadcastPackageVerified(verificationId, originUri,
1475                                    response.code, state.getInstallArgs().getUser());
1476                            try {
1477                                ret = args.copyApk(mContainerService, true);
1478                            } catch (RemoteException e) {
1479                                Slog.e(TAG, "Could not contact the ContainerService");
1480                            }
1481                        } else {
1482                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1483                        }
1484
1485                        processPendingInstall(args, ret);
1486
1487                        mHandler.sendEmptyMessage(MCS_UNBIND);
1488                    }
1489
1490                    break;
1491                }
1492                case START_INTENT_FILTER_VERIFICATIONS: {
1493                    int userId = msg.arg1;
1494                    int verifierUid = msg.arg2;
1495                    PackageParser.Package pkg = (PackageParser.Package)msg.obj;
1496
1497                    verifyIntentFiltersIfNeeded(userId, verifierUid, pkg);
1498                    break;
1499                }
1500                case INTENT_FILTER_VERIFIED: {
1501                    final int verificationId = msg.arg1;
1502
1503                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1504                            verificationId);
1505                    if (state == null) {
1506                        Slog.w(TAG, "Invalid IntentFilter verification token "
1507                                + verificationId + " received");
1508                        break;
1509                    }
1510
1511                    final int userId = state.getUserId();
1512
1513                    Slog.d(TAG, "Processing IntentFilter verification with token:"
1514                            + verificationId + " and userId:" + userId);
1515
1516                    final IntentFilterVerificationResponse response =
1517                            (IntentFilterVerificationResponse) msg.obj;
1518
1519                    state.setVerifierResponse(response.callerUid, response.code);
1520
1521                    Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1522                            + " and userId:" + userId
1523                            + " is settings verifier response with response code:"
1524                            + response.code);
1525
1526                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1527                        Slog.d(TAG, "Domains failing verification: "
1528                                + response.getFailedDomainsString());
1529                    }
1530
1531                    if (state.isVerificationComplete()) {
1532                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1533                    } else {
1534                        Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1535                                + " was not said to be complete");
1536                    }
1537
1538                    break;
1539                }
1540            }
1541        }
1542    }
1543
1544    private StorageEventListener mStorageListener = new StorageEventListener() {
1545        @Override
1546        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1547            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1548                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1549                    loadPrivatePackages(vol);
1550                } else if (vol.state == VolumeInfo.STATE_UNMOUNTING) {
1551                    unloadPrivatePackages(vol);
1552                }
1553            }
1554
1555            if (vol.isPrimary() && vol.type == VolumeInfo.TYPE_PUBLIC) {
1556                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1557                    updateExternalMediaStatus(true, false);
1558                } else if (vol.state == VolumeInfo.STATE_UNMOUNTING) {
1559                    updateExternalMediaStatus(false, false);
1560                }
1561            }
1562        }
1563    };
1564
1565    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1566        if (userId >= UserHandle.USER_OWNER) {
1567            grantRequestedRuntimePermissionsForUser(pkg, userId);
1568        } else if (userId == UserHandle.USER_ALL) {
1569            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1570                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1571            }
1572        }
1573    }
1574
1575    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1576        SettingBase sb = (SettingBase) pkg.mExtras;
1577        if (sb == null) {
1578            return;
1579        }
1580
1581        PermissionsState permissionsState = sb.getPermissionsState();
1582
1583        for (String permission : pkg.requestedPermissions) {
1584            BasePermission bp = mSettings.mPermissions.get(permission);
1585            if (bp != null && bp.isRuntime()) {
1586                permissionsState.grantRuntimePermission(bp, userId);
1587            }
1588        }
1589    }
1590
1591    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1592        Bundle extras = null;
1593        switch (res.returnCode) {
1594            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1595                extras = new Bundle();
1596                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1597                        res.origPermission);
1598                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1599                        res.origPackage);
1600                break;
1601            }
1602        }
1603        return extras;
1604    }
1605
1606    void scheduleWriteSettingsLocked() {
1607        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1608            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1609        }
1610    }
1611
1612    void scheduleWritePackageRestrictionsLocked(int userId) {
1613        if (!sUserManager.exists(userId)) return;
1614        mDirtyUsers.add(userId);
1615        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1616            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1617        }
1618    }
1619
1620    public static PackageManagerService main(Context context, Installer installer,
1621            boolean factoryTest, boolean onlyCore) {
1622        PackageManagerService m = new PackageManagerService(context, installer,
1623                factoryTest, onlyCore);
1624        ServiceManager.addService("package", m);
1625        return m;
1626    }
1627
1628    static String[] splitString(String str, char sep) {
1629        int count = 1;
1630        int i = 0;
1631        while ((i=str.indexOf(sep, i)) >= 0) {
1632            count++;
1633            i++;
1634        }
1635
1636        String[] res = new String[count];
1637        i=0;
1638        count = 0;
1639        int lastI=0;
1640        while ((i=str.indexOf(sep, i)) >= 0) {
1641            res[count] = str.substring(lastI, i);
1642            count++;
1643            i++;
1644            lastI = i;
1645        }
1646        res[count] = str.substring(lastI, str.length());
1647        return res;
1648    }
1649
1650    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1651        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1652                Context.DISPLAY_SERVICE);
1653        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1654    }
1655
1656    public PackageManagerService(Context context, Installer installer,
1657            boolean factoryTest, boolean onlyCore) {
1658        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1659                SystemClock.uptimeMillis());
1660
1661        if (mSdkVersion <= 0) {
1662            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1663        }
1664
1665        mContext = context;
1666        mFactoryTest = factoryTest;
1667        mOnlyCore = onlyCore;
1668        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1669        mMetrics = new DisplayMetrics();
1670        mSettings = new Settings(mPackages);
1671        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1672                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1673        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1674                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1675        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1676                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1677        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1678                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1679        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1680                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1681        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1682                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1683
1684        // TODO: add a property to control this?
1685        long dexOptLRUThresholdInMinutes;
1686        if (mLazyDexOpt) {
1687            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1688        } else {
1689            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1690        }
1691        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1692
1693        String separateProcesses = SystemProperties.get("debug.separate_processes");
1694        if (separateProcesses != null && separateProcesses.length() > 0) {
1695            if ("*".equals(separateProcesses)) {
1696                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1697                mSeparateProcesses = null;
1698                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1699            } else {
1700                mDefParseFlags = 0;
1701                mSeparateProcesses = separateProcesses.split(",");
1702                Slog.w(TAG, "Running with debug.separate_processes: "
1703                        + separateProcesses);
1704            }
1705        } else {
1706            mDefParseFlags = 0;
1707            mSeparateProcesses = null;
1708        }
1709
1710        mInstaller = installer;
1711        mPackageDexOptimizer = new PackageDexOptimizer(this);
1712
1713        getDefaultDisplayMetrics(context, mMetrics);
1714
1715        SystemConfig systemConfig = SystemConfig.getInstance();
1716        mGlobalGids = systemConfig.getGlobalGids();
1717        mSystemPermissions = systemConfig.getSystemPermissions();
1718        mAvailableFeatures = systemConfig.getAvailableFeatures();
1719
1720        synchronized (mInstallLock) {
1721        // writer
1722        synchronized (mPackages) {
1723            mHandlerThread = new ServiceThread(TAG,
1724                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1725            mHandlerThread.start();
1726            mHandler = new PackageHandler(mHandlerThread.getLooper());
1727            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1728
1729            File dataDir = Environment.getDataDirectory();
1730            mAppDataDir = new File(dataDir, "data");
1731            mAppInstallDir = new File(dataDir, "app");
1732            mAppLib32InstallDir = new File(dataDir, "app-lib");
1733            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1734            mUserAppDataDir = new File(dataDir, "user");
1735            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1736
1737            sUserManager = new UserManagerService(context, this,
1738                    mInstallLock, mPackages);
1739
1740            // Propagate permission configuration in to package manager.
1741            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1742                    = systemConfig.getPermissions();
1743            for (int i=0; i<permConfig.size(); i++) {
1744                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1745                BasePermission bp = mSettings.mPermissions.get(perm.name);
1746                if (bp == null) {
1747                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1748                    mSettings.mPermissions.put(perm.name, bp);
1749                }
1750                if (perm.gids != null) {
1751                    bp.setGids(perm.gids, perm.perUser);
1752                }
1753            }
1754
1755            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1756            for (int i=0; i<libConfig.size(); i++) {
1757                mSharedLibraries.put(libConfig.keyAt(i),
1758                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1759            }
1760
1761            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1762
1763            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1764                    mSdkVersion, mOnlyCore);
1765
1766            String customResolverActivity = Resources.getSystem().getString(
1767                    R.string.config_customResolverActivity);
1768            if (TextUtils.isEmpty(customResolverActivity)) {
1769                customResolverActivity = null;
1770            } else {
1771                mCustomResolverComponentName = ComponentName.unflattenFromString(
1772                        customResolverActivity);
1773            }
1774
1775            long startTime = SystemClock.uptimeMillis();
1776
1777            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1778                    startTime);
1779
1780            // Set flag to monitor and not change apk file paths when
1781            // scanning install directories.
1782            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1783
1784            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1785
1786            /**
1787             * Add everything in the in the boot class path to the
1788             * list of process files because dexopt will have been run
1789             * if necessary during zygote startup.
1790             */
1791            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1792            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1793
1794            if (bootClassPath != null) {
1795                String[] bootClassPathElements = splitString(bootClassPath, ':');
1796                for (String element : bootClassPathElements) {
1797                    alreadyDexOpted.add(element);
1798                }
1799            } else {
1800                Slog.w(TAG, "No BOOTCLASSPATH found!");
1801            }
1802
1803            if (systemServerClassPath != null) {
1804                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1805                for (String element : systemServerClassPathElements) {
1806                    alreadyDexOpted.add(element);
1807                }
1808            } else {
1809                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1810            }
1811
1812            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1813            final String[] dexCodeInstructionSets =
1814                    getDexCodeInstructionSets(
1815                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1816
1817            /**
1818             * Ensure all external libraries have had dexopt run on them.
1819             */
1820            if (mSharedLibraries.size() > 0) {
1821                // NOTE: For now, we're compiling these system "shared libraries"
1822                // (and framework jars) into all available architectures. It's possible
1823                // to compile them only when we come across an app that uses them (there's
1824                // already logic for that in scanPackageLI) but that adds some complexity.
1825                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1826                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1827                        final String lib = libEntry.path;
1828                        if (lib == null) {
1829                            continue;
1830                        }
1831
1832                        try {
1833                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1834                                                                                 dexCodeInstructionSet,
1835                                                                                 false);
1836                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1837                                alreadyDexOpted.add(lib);
1838
1839                                // The list of "shared libraries" we have at this point is
1840                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1841                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1842                                } else {
1843                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1844                                }
1845                            }
1846                        } catch (FileNotFoundException e) {
1847                            Slog.w(TAG, "Library not found: " + lib);
1848                        } catch (IOException e) {
1849                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1850                                    + e.getMessage());
1851                        }
1852                    }
1853                }
1854            }
1855
1856            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1857
1858            // Gross hack for now: we know this file doesn't contain any
1859            // code, so don't dexopt it to avoid the resulting log spew.
1860            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1861
1862            // Gross hack for now: we know this file is only part of
1863            // the boot class path for art, so don't dexopt it to
1864            // avoid the resulting log spew.
1865            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1866
1867            /**
1868             * And there are a number of commands implemented in Java, which
1869             * we currently need to do the dexopt on so that they can be
1870             * run from a non-root shell.
1871             */
1872            String[] frameworkFiles = frameworkDir.list();
1873            if (frameworkFiles != null) {
1874                // TODO: We could compile these only for the most preferred ABI. We should
1875                // first double check that the dex files for these commands are not referenced
1876                // by other system apps.
1877                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1878                    for (int i=0; i<frameworkFiles.length; i++) {
1879                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1880                        String path = libPath.getPath();
1881                        // Skip the file if we already did it.
1882                        if (alreadyDexOpted.contains(path)) {
1883                            continue;
1884                        }
1885                        // Skip the file if it is not a type we want to dexopt.
1886                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1887                            continue;
1888                        }
1889                        try {
1890                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1891                                                                                 dexCodeInstructionSet,
1892                                                                                 false);
1893                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1894                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1895                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1896                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1897                            }
1898                        } catch (FileNotFoundException e) {
1899                            Slog.w(TAG, "Jar not found: " + path);
1900                        } catch (IOException e) {
1901                            Slog.w(TAG, "Exception reading jar: " + path, e);
1902                        }
1903                    }
1904                }
1905            }
1906
1907            // Collect vendor overlay packages.
1908            // (Do this before scanning any apps.)
1909            // For security and version matching reason, only consider
1910            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1911            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1912            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1913                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1914
1915            // Find base frameworks (resource packages without code).
1916            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1917                    | PackageParser.PARSE_IS_SYSTEM_DIR
1918                    | PackageParser.PARSE_IS_PRIVILEGED,
1919                    scanFlags | SCAN_NO_DEX, 0);
1920
1921            // Collected privileged system packages.
1922            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1923            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1924                    | PackageParser.PARSE_IS_SYSTEM_DIR
1925                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1926
1927            // Collect ordinary system packages.
1928            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1929            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1930                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1931
1932            // Collect all vendor packages.
1933            File vendorAppDir = new File("/vendor/app");
1934            try {
1935                vendorAppDir = vendorAppDir.getCanonicalFile();
1936            } catch (IOException e) {
1937                // failed to look up canonical path, continue with original one
1938            }
1939            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1940                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1941
1942            // Collect all OEM packages.
1943            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1944            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1945                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1946
1947            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1948            mInstaller.moveFiles();
1949
1950            // Prune any system packages that no longer exist.
1951            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1952            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1953            if (!mOnlyCore) {
1954                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1955                while (psit.hasNext()) {
1956                    PackageSetting ps = psit.next();
1957
1958                    /*
1959                     * If this is not a system app, it can't be a
1960                     * disable system app.
1961                     */
1962                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1963                        continue;
1964                    }
1965
1966                    /*
1967                     * If the package is scanned, it's not erased.
1968                     */
1969                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1970                    if (scannedPkg != null) {
1971                        /*
1972                         * If the system app is both scanned and in the
1973                         * disabled packages list, then it must have been
1974                         * added via OTA. Remove it from the currently
1975                         * scanned package so the previously user-installed
1976                         * application can be scanned.
1977                         */
1978                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1979                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1980                                    + ps.name + "; removing system app.  Last known codePath="
1981                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1982                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1983                                    + scannedPkg.mVersionCode);
1984                            removePackageLI(ps, true);
1985                            expectingBetter.put(ps.name, ps.codePath);
1986                        }
1987
1988                        continue;
1989                    }
1990
1991                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1992                        psit.remove();
1993                        logCriticalInfo(Log.WARN, "System package " + ps.name
1994                                + " no longer exists; wiping its data");
1995                        removeDataDirsLI(ps.name);
1996                    } else {
1997                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1998                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1999                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2000                        }
2001                    }
2002                }
2003            }
2004
2005            //look for any incomplete package installations
2006            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2007            //clean up list
2008            for(int i = 0; i < deletePkgsList.size(); i++) {
2009                //clean up here
2010                cleanupInstallFailedPackage(deletePkgsList.get(i));
2011            }
2012            //delete tmp files
2013            deleteTempPackageFiles();
2014
2015            // Remove any shared userIDs that have no associated packages
2016            mSettings.pruneSharedUsersLPw();
2017
2018            if (!mOnlyCore) {
2019                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2020                        SystemClock.uptimeMillis());
2021                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2022
2023                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2024                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2025
2026                /**
2027                 * Remove disable package settings for any updated system
2028                 * apps that were removed via an OTA. If they're not a
2029                 * previously-updated app, remove them completely.
2030                 * Otherwise, just revoke their system-level permissions.
2031                 */
2032                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2033                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2034                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2035
2036                    String msg;
2037                    if (deletedPkg == null) {
2038                        msg = "Updated system package " + deletedAppName
2039                                + " no longer exists; wiping its data";
2040                        removeDataDirsLI(deletedAppName);
2041                    } else {
2042                        msg = "Updated system app + " + deletedAppName
2043                                + " no longer present; removing system privileges for "
2044                                + deletedAppName;
2045
2046                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2047
2048                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2049                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2050                    }
2051                    logCriticalInfo(Log.WARN, msg);
2052                }
2053
2054                /**
2055                 * Make sure all system apps that we expected to appear on
2056                 * the userdata partition actually showed up. If they never
2057                 * appeared, crawl back and revive the system version.
2058                 */
2059                for (int i = 0; i < expectingBetter.size(); i++) {
2060                    final String packageName = expectingBetter.keyAt(i);
2061                    if (!mPackages.containsKey(packageName)) {
2062                        final File scanFile = expectingBetter.valueAt(i);
2063
2064                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2065                                + " but never showed up; reverting to system");
2066
2067                        final int reparseFlags;
2068                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2069                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2070                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2071                                    | PackageParser.PARSE_IS_PRIVILEGED;
2072                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2073                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2074                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2075                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2076                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2077                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2078                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2079                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2080                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2081                        } else {
2082                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2083                            continue;
2084                        }
2085
2086                        mSettings.enableSystemPackageLPw(packageName);
2087
2088                        try {
2089                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2090                        } catch (PackageManagerException e) {
2091                            Slog.e(TAG, "Failed to parse original system package: "
2092                                    + e.getMessage());
2093                        }
2094                    }
2095                }
2096            }
2097
2098            // Now that we know all of the shared libraries, update all clients to have
2099            // the correct library paths.
2100            updateAllSharedLibrariesLPw();
2101
2102            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2103                // NOTE: We ignore potential failures here during a system scan (like
2104                // the rest of the commands above) because there's precious little we
2105                // can do about it. A settings error is reported, though.
2106                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2107                        false /* force dexopt */, false /* defer dexopt */);
2108            }
2109
2110            // Now that we know all the packages we are keeping,
2111            // read and update their last usage times.
2112            mPackageUsage.readLP();
2113
2114            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2115                    SystemClock.uptimeMillis());
2116            Slog.i(TAG, "Time to scan packages: "
2117                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2118                    + " seconds");
2119
2120            // If the platform SDK has changed since the last time we booted,
2121            // we need to re-grant app permission to catch any new ones that
2122            // appear.  This is really a hack, and means that apps can in some
2123            // cases get permissions that the user didn't initially explicitly
2124            // allow...  it would be nice to have some better way to handle
2125            // this situation.
2126            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2127                    != mSdkVersion;
2128            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2129                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2130                    + "; regranting permissions for internal storage");
2131            mSettings.mInternalSdkPlatform = mSdkVersion;
2132
2133            // For now runtime permissions are toggled via a system property.
2134            if (!RUNTIME_PERMISSIONS_ENABLED) {
2135                // Remove the runtime permissions state if the feature
2136                // was disabled by flipping the system property.
2137                mSettings.deleteRuntimePermissionsFiles();
2138            }
2139
2140            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2141                    | (regrantPermissions
2142                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2143                            : 0));
2144
2145            // If this is the first boot, and it is a normal boot, then
2146            // we need to initialize the default preferred apps.
2147            if (!mRestoredSettings && !onlyCore) {
2148                mSettings.readDefaultPreferredAppsLPw(this, 0);
2149            }
2150
2151            // If this is first boot after an OTA, and a normal boot, then
2152            // we need to clear code cache directories.
2153            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2154            if (mIsUpgrade && !onlyCore) {
2155                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2156                for (String pkgName : mSettings.mPackages.keySet()) {
2157                    deleteCodeCacheDirsLI(pkgName);
2158                }
2159                mSettings.mFingerprint = Build.FINGERPRINT;
2160            }
2161
2162            // All the changes are done during package scanning.
2163            mSettings.updateInternalDatabaseVersion();
2164
2165            // can downgrade to reader
2166            mSettings.writeLPr();
2167
2168            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2169                    SystemClock.uptimeMillis());
2170
2171            mRequiredVerifierPackage = getRequiredVerifierLPr();
2172
2173            mInstallerService = new PackageInstallerService(context, this);
2174
2175            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2176            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2177                    mIntentFilterVerifierComponent);
2178
2179        } // synchronized (mPackages)
2180        } // synchronized (mInstallLock)
2181
2182        // Now after opening every single application zip, make sure they
2183        // are all flushed.  Not really needed, but keeps things nice and
2184        // tidy.
2185        Runtime.getRuntime().gc();
2186    }
2187
2188    @Override
2189    public boolean isFirstBoot() {
2190        return !mRestoredSettings;
2191    }
2192
2193    @Override
2194    public boolean isOnlyCoreApps() {
2195        return mOnlyCore;
2196    }
2197
2198    @Override
2199    public boolean isUpgrade() {
2200        return mIsUpgrade;
2201    }
2202
2203    private String getRequiredVerifierLPr() {
2204        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2205        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2206                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2207
2208        String requiredVerifier = null;
2209
2210        final int N = receivers.size();
2211        for (int i = 0; i < N; i++) {
2212            final ResolveInfo info = receivers.get(i);
2213
2214            if (info.activityInfo == null) {
2215                continue;
2216            }
2217
2218            final String packageName = info.activityInfo.packageName;
2219
2220            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2221                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2222                continue;
2223            }
2224
2225            if (requiredVerifier != null) {
2226                throw new RuntimeException("There can be only one required verifier");
2227            }
2228
2229            requiredVerifier = packageName;
2230        }
2231
2232        return requiredVerifier;
2233    }
2234
2235    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2236        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2237        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2238                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2239
2240        ComponentName verifierComponentName = null;
2241
2242        int priority = -1000;
2243        final int N = receivers.size();
2244        for (int i = 0; i < N; i++) {
2245            final ResolveInfo info = receivers.get(i);
2246
2247            if (info.activityInfo == null) {
2248                continue;
2249            }
2250
2251            final String packageName = info.activityInfo.packageName;
2252
2253            final PackageSetting ps = mSettings.mPackages.get(packageName);
2254            if (ps == null) {
2255                continue;
2256            }
2257
2258            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2259                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2260                continue;
2261            }
2262
2263            // Select the IntentFilterVerifier with the highest priority
2264            if (priority < info.priority) {
2265                priority = info.priority;
2266                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2267                Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName +
2268                        " with priority: " + info.priority);
2269            }
2270        }
2271
2272        return verifierComponentName;
2273    }
2274
2275    @Override
2276    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2277            throws RemoteException {
2278        try {
2279            return super.onTransact(code, data, reply, flags);
2280        } catch (RuntimeException e) {
2281            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2282                Slog.wtf(TAG, "Package Manager Crash", e);
2283            }
2284            throw e;
2285        }
2286    }
2287
2288    void cleanupInstallFailedPackage(PackageSetting ps) {
2289        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2290
2291        removeDataDirsLI(ps.name);
2292        if (ps.codePath != null) {
2293            if (ps.codePath.isDirectory()) {
2294                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2295            } else {
2296                ps.codePath.delete();
2297            }
2298        }
2299        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2300            if (ps.resourcePath.isDirectory()) {
2301                FileUtils.deleteContents(ps.resourcePath);
2302            }
2303            ps.resourcePath.delete();
2304        }
2305        mSettings.removePackageLPw(ps.name);
2306    }
2307
2308    static int[] appendInts(int[] cur, int[] add) {
2309        if (add == null) return cur;
2310        if (cur == null) return add;
2311        final int N = add.length;
2312        for (int i=0; i<N; i++) {
2313            cur = appendInt(cur, add[i]);
2314        }
2315        return cur;
2316    }
2317
2318    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2319        if (!sUserManager.exists(userId)) return null;
2320        final PackageSetting ps = (PackageSetting) p.mExtras;
2321        if (ps == null) {
2322            return null;
2323        }
2324
2325        final PermissionsState permissionsState = ps.getPermissionsState();
2326
2327        final int[] gids = permissionsState.computeGids(userId);
2328        final Set<String> permissions = permissionsState.getPermissions(userId);
2329        final PackageUserState state = ps.readUserState(userId);
2330
2331        return PackageParser.generatePackageInfo(p, gids, flags,
2332                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2333    }
2334
2335    @Override
2336    public boolean isPackageAvailable(String packageName, int userId) {
2337        if (!sUserManager.exists(userId)) return false;
2338        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2339        synchronized (mPackages) {
2340            PackageParser.Package p = mPackages.get(packageName);
2341            if (p != null) {
2342                final PackageSetting ps = (PackageSetting) p.mExtras;
2343                if (ps != null) {
2344                    final PackageUserState state = ps.readUserState(userId);
2345                    if (state != null) {
2346                        return PackageParser.isAvailable(state);
2347                    }
2348                }
2349            }
2350        }
2351        return false;
2352    }
2353
2354    @Override
2355    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2356        if (!sUserManager.exists(userId)) return null;
2357        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2358        // reader
2359        synchronized (mPackages) {
2360            PackageParser.Package p = mPackages.get(packageName);
2361            if (DEBUG_PACKAGE_INFO)
2362                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2363            if (p != null) {
2364                return generatePackageInfo(p, flags, userId);
2365            }
2366            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2367                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2368            }
2369        }
2370        return null;
2371    }
2372
2373    @Override
2374    public String[] currentToCanonicalPackageNames(String[] names) {
2375        String[] out = new String[names.length];
2376        // reader
2377        synchronized (mPackages) {
2378            for (int i=names.length-1; i>=0; i--) {
2379                PackageSetting ps = mSettings.mPackages.get(names[i]);
2380                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2381            }
2382        }
2383        return out;
2384    }
2385
2386    @Override
2387    public String[] canonicalToCurrentPackageNames(String[] names) {
2388        String[] out = new String[names.length];
2389        // reader
2390        synchronized (mPackages) {
2391            for (int i=names.length-1; i>=0; i--) {
2392                String cur = mSettings.mRenamedPackages.get(names[i]);
2393                out[i] = cur != null ? cur : names[i];
2394            }
2395        }
2396        return out;
2397    }
2398
2399    @Override
2400    public int getPackageUid(String packageName, int userId) {
2401        if (!sUserManager.exists(userId)) return -1;
2402        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2403
2404        // reader
2405        synchronized (mPackages) {
2406            PackageParser.Package p = mPackages.get(packageName);
2407            if(p != null) {
2408                return UserHandle.getUid(userId, p.applicationInfo.uid);
2409            }
2410            PackageSetting ps = mSettings.mPackages.get(packageName);
2411            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2412                return -1;
2413            }
2414            p = ps.pkg;
2415            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2416        }
2417    }
2418
2419    @Override
2420    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2421        if (!sUserManager.exists(userId)) {
2422            return null;
2423        }
2424
2425        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2426                "getPackageGids");
2427
2428        // reader
2429        synchronized (mPackages) {
2430            PackageParser.Package p = mPackages.get(packageName);
2431            if (DEBUG_PACKAGE_INFO) {
2432                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2433            }
2434            if (p != null) {
2435                PackageSetting ps = (PackageSetting) p.mExtras;
2436                return ps.getPermissionsState().computeGids(userId);
2437            }
2438        }
2439
2440        return null;
2441    }
2442
2443    static PermissionInfo generatePermissionInfo(
2444            BasePermission bp, int flags) {
2445        if (bp.perm != null) {
2446            return PackageParser.generatePermissionInfo(bp.perm, flags);
2447        }
2448        PermissionInfo pi = new PermissionInfo();
2449        pi.name = bp.name;
2450        pi.packageName = bp.sourcePackage;
2451        pi.nonLocalizedLabel = bp.name;
2452        pi.protectionLevel = bp.protectionLevel;
2453        return pi;
2454    }
2455
2456    @Override
2457    public PermissionInfo getPermissionInfo(String name, int flags) {
2458        // reader
2459        synchronized (mPackages) {
2460            final BasePermission p = mSettings.mPermissions.get(name);
2461            if (p != null) {
2462                return generatePermissionInfo(p, flags);
2463            }
2464            return null;
2465        }
2466    }
2467
2468    @Override
2469    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2470        // reader
2471        synchronized (mPackages) {
2472            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2473            for (BasePermission p : mSettings.mPermissions.values()) {
2474                if (group == null) {
2475                    if (p.perm == null || p.perm.info.group == null) {
2476                        out.add(generatePermissionInfo(p, flags));
2477                    }
2478                } else {
2479                    if (p.perm != null && group.equals(p.perm.info.group)) {
2480                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2481                    }
2482                }
2483            }
2484
2485            if (out.size() > 0) {
2486                return out;
2487            }
2488            return mPermissionGroups.containsKey(group) ? out : null;
2489        }
2490    }
2491
2492    @Override
2493    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2494        // reader
2495        synchronized (mPackages) {
2496            return PackageParser.generatePermissionGroupInfo(
2497                    mPermissionGroups.get(name), flags);
2498        }
2499    }
2500
2501    @Override
2502    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2503        // reader
2504        synchronized (mPackages) {
2505            final int N = mPermissionGroups.size();
2506            ArrayList<PermissionGroupInfo> out
2507                    = new ArrayList<PermissionGroupInfo>(N);
2508            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2509                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2510            }
2511            return out;
2512        }
2513    }
2514
2515    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2516            int userId) {
2517        if (!sUserManager.exists(userId)) return null;
2518        PackageSetting ps = mSettings.mPackages.get(packageName);
2519        if (ps != null) {
2520            if (ps.pkg == null) {
2521                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2522                        flags, userId);
2523                if (pInfo != null) {
2524                    return pInfo.applicationInfo;
2525                }
2526                return null;
2527            }
2528            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2529                    ps.readUserState(userId), userId);
2530        }
2531        return null;
2532    }
2533
2534    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2535            int userId) {
2536        if (!sUserManager.exists(userId)) return null;
2537        PackageSetting ps = mSettings.mPackages.get(packageName);
2538        if (ps != null) {
2539            PackageParser.Package pkg = ps.pkg;
2540            if (pkg == null) {
2541                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2542                    return null;
2543                }
2544                // Only data remains, so we aren't worried about code paths
2545                pkg = new PackageParser.Package(packageName);
2546                pkg.applicationInfo.packageName = packageName;
2547                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2548                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2549                pkg.applicationInfo.dataDir =
2550                        getDataPathForPackage(packageName, 0).getPath();
2551                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2552                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2553            }
2554            return generatePackageInfo(pkg, flags, userId);
2555        }
2556        return null;
2557    }
2558
2559    @Override
2560    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2561        if (!sUserManager.exists(userId)) return null;
2562        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2563        // writer
2564        synchronized (mPackages) {
2565            PackageParser.Package p = mPackages.get(packageName);
2566            if (DEBUG_PACKAGE_INFO) Log.v(
2567                    TAG, "getApplicationInfo " + packageName
2568                    + ": " + p);
2569            if (p != null) {
2570                PackageSetting ps = mSettings.mPackages.get(packageName);
2571                if (ps == null) return null;
2572                // Note: isEnabledLP() does not apply here - always return info
2573                return PackageParser.generateApplicationInfo(
2574                        p, flags, ps.readUserState(userId), userId);
2575            }
2576            if ("android".equals(packageName)||"system".equals(packageName)) {
2577                return mAndroidApplication;
2578            }
2579            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2580                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2581            }
2582        }
2583        return null;
2584    }
2585
2586
2587    @Override
2588    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2589        mContext.enforceCallingOrSelfPermission(
2590                android.Manifest.permission.CLEAR_APP_CACHE, null);
2591        // Queue up an async operation since clearing cache may take a little while.
2592        mHandler.post(new Runnable() {
2593            public void run() {
2594                mHandler.removeCallbacks(this);
2595                int retCode = -1;
2596                synchronized (mInstallLock) {
2597                    retCode = mInstaller.freeCache(freeStorageSize);
2598                    if (retCode < 0) {
2599                        Slog.w(TAG, "Couldn't clear application caches");
2600                    }
2601                }
2602                if (observer != null) {
2603                    try {
2604                        observer.onRemoveCompleted(null, (retCode >= 0));
2605                    } catch (RemoteException e) {
2606                        Slog.w(TAG, "RemoveException when invoking call back");
2607                    }
2608                }
2609            }
2610        });
2611    }
2612
2613    @Override
2614    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2615        mContext.enforceCallingOrSelfPermission(
2616                android.Manifest.permission.CLEAR_APP_CACHE, null);
2617        // Queue up an async operation since clearing cache may take a little while.
2618        mHandler.post(new Runnable() {
2619            public void run() {
2620                mHandler.removeCallbacks(this);
2621                int retCode = -1;
2622                synchronized (mInstallLock) {
2623                    retCode = mInstaller.freeCache(freeStorageSize);
2624                    if (retCode < 0) {
2625                        Slog.w(TAG, "Couldn't clear application caches");
2626                    }
2627                }
2628                if(pi != null) {
2629                    try {
2630                        // Callback via pending intent
2631                        int code = (retCode >= 0) ? 1 : 0;
2632                        pi.sendIntent(null, code, null,
2633                                null, null);
2634                    } catch (SendIntentException e1) {
2635                        Slog.i(TAG, "Failed to send pending intent");
2636                    }
2637                }
2638            }
2639        });
2640    }
2641
2642    void freeStorage(long freeStorageSize) throws IOException {
2643        synchronized (mInstallLock) {
2644            if (mInstaller.freeCache(freeStorageSize) < 0) {
2645                throw new IOException("Failed to free enough space");
2646            }
2647        }
2648    }
2649
2650    @Override
2651    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2652        if (!sUserManager.exists(userId)) return null;
2653        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2654        synchronized (mPackages) {
2655            PackageParser.Activity a = mActivities.mActivities.get(component);
2656
2657            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2658            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2659                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2660                if (ps == null) return null;
2661                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2662                        userId);
2663            }
2664            if (mResolveComponentName.equals(component)) {
2665                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2666                        new PackageUserState(), userId);
2667            }
2668        }
2669        return null;
2670    }
2671
2672    @Override
2673    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2674            String resolvedType) {
2675        synchronized (mPackages) {
2676            PackageParser.Activity a = mActivities.mActivities.get(component);
2677            if (a == null) {
2678                return false;
2679            }
2680            for (int i=0; i<a.intents.size(); i++) {
2681                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2682                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2683                    return true;
2684                }
2685            }
2686            return false;
2687        }
2688    }
2689
2690    @Override
2691    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2692        if (!sUserManager.exists(userId)) return null;
2693        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2694        synchronized (mPackages) {
2695            PackageParser.Activity a = mReceivers.mActivities.get(component);
2696            if (DEBUG_PACKAGE_INFO) Log.v(
2697                TAG, "getReceiverInfo " + component + ": " + a);
2698            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2699                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2700                if (ps == null) return null;
2701                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2702                        userId);
2703            }
2704        }
2705        return null;
2706    }
2707
2708    @Override
2709    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2710        if (!sUserManager.exists(userId)) return null;
2711        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2712        synchronized (mPackages) {
2713            PackageParser.Service s = mServices.mServices.get(component);
2714            if (DEBUG_PACKAGE_INFO) Log.v(
2715                TAG, "getServiceInfo " + component + ": " + s);
2716            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2717                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2718                if (ps == null) return null;
2719                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2720                        userId);
2721            }
2722        }
2723        return null;
2724    }
2725
2726    @Override
2727    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2728        if (!sUserManager.exists(userId)) return null;
2729        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2730        synchronized (mPackages) {
2731            PackageParser.Provider p = mProviders.mProviders.get(component);
2732            if (DEBUG_PACKAGE_INFO) Log.v(
2733                TAG, "getProviderInfo " + component + ": " + p);
2734            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2735                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2736                if (ps == null) return null;
2737                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2738                        userId);
2739            }
2740        }
2741        return null;
2742    }
2743
2744    @Override
2745    public String[] getSystemSharedLibraryNames() {
2746        Set<String> libSet;
2747        synchronized (mPackages) {
2748            libSet = mSharedLibraries.keySet();
2749            int size = libSet.size();
2750            if (size > 0) {
2751                String[] libs = new String[size];
2752                libSet.toArray(libs);
2753                return libs;
2754            }
2755        }
2756        return null;
2757    }
2758
2759    /**
2760     * @hide
2761     */
2762    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2763        synchronized (mPackages) {
2764            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2765            if (lib != null && lib.apk != null) {
2766                return mPackages.get(lib.apk);
2767            }
2768        }
2769        return null;
2770    }
2771
2772    @Override
2773    public FeatureInfo[] getSystemAvailableFeatures() {
2774        Collection<FeatureInfo> featSet;
2775        synchronized (mPackages) {
2776            featSet = mAvailableFeatures.values();
2777            int size = featSet.size();
2778            if (size > 0) {
2779                FeatureInfo[] features = new FeatureInfo[size+1];
2780                featSet.toArray(features);
2781                FeatureInfo fi = new FeatureInfo();
2782                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2783                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2784                features[size] = fi;
2785                return features;
2786            }
2787        }
2788        return null;
2789    }
2790
2791    @Override
2792    public boolean hasSystemFeature(String name) {
2793        synchronized (mPackages) {
2794            return mAvailableFeatures.containsKey(name);
2795        }
2796    }
2797
2798    private void checkValidCaller(int uid, int userId) {
2799        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2800            return;
2801
2802        throw new SecurityException("Caller uid=" + uid
2803                + " is not privileged to communicate with user=" + userId);
2804    }
2805
2806    @Override
2807    public int checkPermission(String permName, String pkgName, int userId) {
2808        if (!sUserManager.exists(userId)) {
2809            return PackageManager.PERMISSION_DENIED;
2810        }
2811
2812        synchronized (mPackages) {
2813            final PackageParser.Package p = mPackages.get(pkgName);
2814            if (p != null && p.mExtras != null) {
2815                final PackageSetting ps = (PackageSetting) p.mExtras;
2816                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2817                    return PackageManager.PERMISSION_GRANTED;
2818                }
2819            }
2820        }
2821
2822        return PackageManager.PERMISSION_DENIED;
2823    }
2824
2825    @Override
2826    public int checkUidPermission(String permName, int uid) {
2827        final int userId = UserHandle.getUserId(uid);
2828
2829        if (!sUserManager.exists(userId)) {
2830            return PackageManager.PERMISSION_DENIED;
2831        }
2832
2833        synchronized (mPackages) {
2834            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2835            if (obj != null) {
2836                final SettingBase ps = (SettingBase) obj;
2837                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2838                    return PackageManager.PERMISSION_GRANTED;
2839                }
2840            } else {
2841                ArraySet<String> perms = mSystemPermissions.get(uid);
2842                if (perms != null && perms.contains(permName)) {
2843                    return PackageManager.PERMISSION_GRANTED;
2844                }
2845            }
2846        }
2847
2848        return PackageManager.PERMISSION_DENIED;
2849    }
2850
2851    /**
2852     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2853     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2854     * @param checkShell TODO(yamasani):
2855     * @param message the message to log on security exception
2856     */
2857    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2858            boolean checkShell, String message) {
2859        if (userId < 0) {
2860            throw new IllegalArgumentException("Invalid userId " + userId);
2861        }
2862        if (checkShell) {
2863            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2864        }
2865        if (userId == UserHandle.getUserId(callingUid)) return;
2866        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2867            if (requireFullPermission) {
2868                mContext.enforceCallingOrSelfPermission(
2869                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2870            } else {
2871                try {
2872                    mContext.enforceCallingOrSelfPermission(
2873                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2874                } catch (SecurityException se) {
2875                    mContext.enforceCallingOrSelfPermission(
2876                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2877                }
2878            }
2879        }
2880    }
2881
2882    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2883        if (callingUid == Process.SHELL_UID) {
2884            if (userHandle >= 0
2885                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2886                throw new SecurityException("Shell does not have permission to access user "
2887                        + userHandle);
2888            } else if (userHandle < 0) {
2889                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2890                        + Debug.getCallers(3));
2891            }
2892        }
2893    }
2894
2895    private BasePermission findPermissionTreeLP(String permName) {
2896        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2897            if (permName.startsWith(bp.name) &&
2898                    permName.length() > bp.name.length() &&
2899                    permName.charAt(bp.name.length()) == '.') {
2900                return bp;
2901            }
2902        }
2903        return null;
2904    }
2905
2906    private BasePermission checkPermissionTreeLP(String permName) {
2907        if (permName != null) {
2908            BasePermission bp = findPermissionTreeLP(permName);
2909            if (bp != null) {
2910                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2911                    return bp;
2912                }
2913                throw new SecurityException("Calling uid "
2914                        + Binder.getCallingUid()
2915                        + " is not allowed to add to permission tree "
2916                        + bp.name + " owned by uid " + bp.uid);
2917            }
2918        }
2919        throw new SecurityException("No permission tree found for " + permName);
2920    }
2921
2922    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2923        if (s1 == null) {
2924            return s2 == null;
2925        }
2926        if (s2 == null) {
2927            return false;
2928        }
2929        if (s1.getClass() != s2.getClass()) {
2930            return false;
2931        }
2932        return s1.equals(s2);
2933    }
2934
2935    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2936        if (pi1.icon != pi2.icon) return false;
2937        if (pi1.logo != pi2.logo) return false;
2938        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2939        if (!compareStrings(pi1.name, pi2.name)) return false;
2940        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2941        // We'll take care of setting this one.
2942        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2943        // These are not currently stored in settings.
2944        //if (!compareStrings(pi1.group, pi2.group)) return false;
2945        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2946        //if (pi1.labelRes != pi2.labelRes) return false;
2947        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2948        return true;
2949    }
2950
2951    int permissionInfoFootprint(PermissionInfo info) {
2952        int size = info.name.length();
2953        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2954        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2955        return size;
2956    }
2957
2958    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2959        int size = 0;
2960        for (BasePermission perm : mSettings.mPermissions.values()) {
2961            if (perm.uid == tree.uid) {
2962                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2963            }
2964        }
2965        return size;
2966    }
2967
2968    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2969        // We calculate the max size of permissions defined by this uid and throw
2970        // if that plus the size of 'info' would exceed our stated maximum.
2971        if (tree.uid != Process.SYSTEM_UID) {
2972            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2973            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2974                throw new SecurityException("Permission tree size cap exceeded");
2975            }
2976        }
2977    }
2978
2979    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2980        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2981            throw new SecurityException("Label must be specified in permission");
2982        }
2983        BasePermission tree = checkPermissionTreeLP(info.name);
2984        BasePermission bp = mSettings.mPermissions.get(info.name);
2985        boolean added = bp == null;
2986        boolean changed = true;
2987        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2988        if (added) {
2989            enforcePermissionCapLocked(info, tree);
2990            bp = new BasePermission(info.name, tree.sourcePackage,
2991                    BasePermission.TYPE_DYNAMIC);
2992        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2993            throw new SecurityException(
2994                    "Not allowed to modify non-dynamic permission "
2995                    + info.name);
2996        } else {
2997            if (bp.protectionLevel == fixedLevel
2998                    && bp.perm.owner.equals(tree.perm.owner)
2999                    && bp.uid == tree.uid
3000                    && comparePermissionInfos(bp.perm.info, info)) {
3001                changed = false;
3002            }
3003        }
3004        bp.protectionLevel = fixedLevel;
3005        info = new PermissionInfo(info);
3006        info.protectionLevel = fixedLevel;
3007        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3008        bp.perm.info.packageName = tree.perm.info.packageName;
3009        bp.uid = tree.uid;
3010        if (added) {
3011            mSettings.mPermissions.put(info.name, bp);
3012        }
3013        if (changed) {
3014            if (!async) {
3015                mSettings.writeLPr();
3016            } else {
3017                scheduleWriteSettingsLocked();
3018            }
3019        }
3020        return added;
3021    }
3022
3023    @Override
3024    public boolean addPermission(PermissionInfo info) {
3025        synchronized (mPackages) {
3026            return addPermissionLocked(info, false);
3027        }
3028    }
3029
3030    @Override
3031    public boolean addPermissionAsync(PermissionInfo info) {
3032        synchronized (mPackages) {
3033            return addPermissionLocked(info, true);
3034        }
3035    }
3036
3037    @Override
3038    public void removePermission(String name) {
3039        synchronized (mPackages) {
3040            checkPermissionTreeLP(name);
3041            BasePermission bp = mSettings.mPermissions.get(name);
3042            if (bp != null) {
3043                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3044                    throw new SecurityException(
3045                            "Not allowed to modify non-dynamic permission "
3046                            + name);
3047                }
3048                mSettings.mPermissions.remove(name);
3049                mSettings.writeLPr();
3050            }
3051        }
3052    }
3053
3054    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3055            BasePermission bp) {
3056        int index = pkg.requestedPermissions.indexOf(bp.name);
3057        if (index == -1) {
3058            throw new SecurityException("Package " + pkg.packageName
3059                    + " has not requested permission " + bp.name);
3060        }
3061        if (!bp.isRuntime()) {
3062            throw new SecurityException("Permission " + bp.name
3063                    + " is not a changeable permission type");
3064        }
3065    }
3066
3067    @Override
3068    public boolean grantPermission(String packageName, String name, int userId) {
3069        if (!RUNTIME_PERMISSIONS_ENABLED) {
3070            return false;
3071        }
3072
3073        if (!sUserManager.exists(userId)) {
3074            return false;
3075        }
3076
3077        mContext.enforceCallingOrSelfPermission(
3078                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3079                "grantPermission");
3080
3081        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3082                "grantPermission");
3083
3084        boolean gidsChanged = false;
3085        final SettingBase sb;
3086
3087        synchronized (mPackages) {
3088            final PackageParser.Package pkg = mPackages.get(packageName);
3089            if (pkg == null) {
3090                throw new IllegalArgumentException("Unknown package: " + packageName);
3091            }
3092
3093            final BasePermission bp = mSettings.mPermissions.get(name);
3094            if (bp == null) {
3095                throw new IllegalArgumentException("Unknown permission: " + name);
3096            }
3097
3098            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3099
3100            sb = (SettingBase) pkg.mExtras;
3101            if (sb == null) {
3102                throw new IllegalArgumentException("Unknown package: " + packageName);
3103            }
3104
3105            final PermissionsState permissionsState = sb.getPermissionsState();
3106
3107            final int result = permissionsState.grantRuntimePermission(bp, userId);
3108            switch (result) {
3109                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3110                    return false;
3111                }
3112
3113                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3114                    gidsChanged = true;
3115                } break;
3116            }
3117
3118            // Not critical if that is lost - app has to request again.
3119            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3120        }
3121
3122        if (gidsChanged) {
3123            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3124        }
3125
3126        return true;
3127    }
3128
3129    @Override
3130    public boolean revokePermission(String packageName, String name, int userId) {
3131        if (!RUNTIME_PERMISSIONS_ENABLED) {
3132            return false;
3133        }
3134
3135        if (!sUserManager.exists(userId)) {
3136            return false;
3137        }
3138
3139        mContext.enforceCallingOrSelfPermission(
3140                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3141                "revokePermission");
3142
3143        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3144                "revokePermission");
3145
3146        final SettingBase sb;
3147
3148        synchronized (mPackages) {
3149            final PackageParser.Package pkg = mPackages.get(packageName);
3150            if (pkg == null) {
3151                throw new IllegalArgumentException("Unknown package: " + packageName);
3152            }
3153
3154            final BasePermission bp = mSettings.mPermissions.get(name);
3155            if (bp == null) {
3156                throw new IllegalArgumentException("Unknown permission: " + name);
3157            }
3158
3159            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3160
3161            sb = (SettingBase) pkg.mExtras;
3162            if (sb == null) {
3163                throw new IllegalArgumentException("Unknown package: " + packageName);
3164            }
3165
3166            final PermissionsState permissionsState = sb.getPermissionsState();
3167
3168            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3169                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3170                return false;
3171            }
3172
3173            // Critical, after this call all should never have the permission.
3174            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3175        }
3176
3177        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3178
3179        return true;
3180    }
3181
3182    @Override
3183    public boolean isProtectedBroadcast(String actionName) {
3184        synchronized (mPackages) {
3185            return mProtectedBroadcasts.contains(actionName);
3186        }
3187    }
3188
3189    @Override
3190    public int checkSignatures(String pkg1, String pkg2) {
3191        synchronized (mPackages) {
3192            final PackageParser.Package p1 = mPackages.get(pkg1);
3193            final PackageParser.Package p2 = mPackages.get(pkg2);
3194            if (p1 == null || p1.mExtras == null
3195                    || p2 == null || p2.mExtras == null) {
3196                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3197            }
3198            return compareSignatures(p1.mSignatures, p2.mSignatures);
3199        }
3200    }
3201
3202    @Override
3203    public int checkUidSignatures(int uid1, int uid2) {
3204        // Map to base uids.
3205        uid1 = UserHandle.getAppId(uid1);
3206        uid2 = UserHandle.getAppId(uid2);
3207        // reader
3208        synchronized (mPackages) {
3209            Signature[] s1;
3210            Signature[] s2;
3211            Object obj = mSettings.getUserIdLPr(uid1);
3212            if (obj != null) {
3213                if (obj instanceof SharedUserSetting) {
3214                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3215                } else if (obj instanceof PackageSetting) {
3216                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3217                } else {
3218                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3219                }
3220            } else {
3221                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3222            }
3223            obj = mSettings.getUserIdLPr(uid2);
3224            if (obj != null) {
3225                if (obj instanceof SharedUserSetting) {
3226                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3227                } else if (obj instanceof PackageSetting) {
3228                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3229                } else {
3230                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3231                }
3232            } else {
3233                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3234            }
3235            return compareSignatures(s1, s2);
3236        }
3237    }
3238
3239    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3240        final long identity = Binder.clearCallingIdentity();
3241        try {
3242            if (sb instanceof SharedUserSetting) {
3243                SharedUserSetting sus = (SharedUserSetting) sb;
3244                final int packageCount = sus.packages.size();
3245                for (int i = 0; i < packageCount; i++) {
3246                    PackageSetting susPs = sus.packages.valueAt(i);
3247                    if (userId == UserHandle.USER_ALL) {
3248                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3249                    } else {
3250                        final int uid = UserHandle.getUid(userId, susPs.appId);
3251                        killUid(uid, reason);
3252                    }
3253                }
3254            } else if (sb instanceof PackageSetting) {
3255                PackageSetting ps = (PackageSetting) sb;
3256                if (userId == UserHandle.USER_ALL) {
3257                    killApplication(ps.pkg.packageName, ps.appId, reason);
3258                } else {
3259                    final int uid = UserHandle.getUid(userId, ps.appId);
3260                    killUid(uid, reason);
3261                }
3262            }
3263        } finally {
3264            Binder.restoreCallingIdentity(identity);
3265        }
3266    }
3267
3268    private static void killUid(int uid, String reason) {
3269        IActivityManager am = ActivityManagerNative.getDefault();
3270        if (am != null) {
3271            try {
3272                am.killUid(uid, reason);
3273            } catch (RemoteException e) {
3274                /* ignore - same process */
3275            }
3276        }
3277    }
3278
3279    /**
3280     * Compares two sets of signatures. Returns:
3281     * <br />
3282     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3283     * <br />
3284     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3285     * <br />
3286     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3287     * <br />
3288     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3289     * <br />
3290     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3291     */
3292    static int compareSignatures(Signature[] s1, Signature[] s2) {
3293        if (s1 == null) {
3294            return s2 == null
3295                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3296                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3297        }
3298
3299        if (s2 == null) {
3300            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3301        }
3302
3303        if (s1.length != s2.length) {
3304            return PackageManager.SIGNATURE_NO_MATCH;
3305        }
3306
3307        // Since both signature sets are of size 1, we can compare without HashSets.
3308        if (s1.length == 1) {
3309            return s1[0].equals(s2[0]) ?
3310                    PackageManager.SIGNATURE_MATCH :
3311                    PackageManager.SIGNATURE_NO_MATCH;
3312        }
3313
3314        ArraySet<Signature> set1 = new ArraySet<Signature>();
3315        for (Signature sig : s1) {
3316            set1.add(sig);
3317        }
3318        ArraySet<Signature> set2 = new ArraySet<Signature>();
3319        for (Signature sig : s2) {
3320            set2.add(sig);
3321        }
3322        // Make sure s2 contains all signatures in s1.
3323        if (set1.equals(set2)) {
3324            return PackageManager.SIGNATURE_MATCH;
3325        }
3326        return PackageManager.SIGNATURE_NO_MATCH;
3327    }
3328
3329    /**
3330     * If the database version for this type of package (internal storage or
3331     * external storage) is less than the version where package signatures
3332     * were updated, return true.
3333     */
3334    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3335        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3336                DatabaseVersion.SIGNATURE_END_ENTITY))
3337                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3338                        DatabaseVersion.SIGNATURE_END_ENTITY));
3339    }
3340
3341    /**
3342     * Used for backward compatibility to make sure any packages with
3343     * certificate chains get upgraded to the new style. {@code existingSigs}
3344     * will be in the old format (since they were stored on disk from before the
3345     * system upgrade) and {@code scannedSigs} will be in the newer format.
3346     */
3347    private int compareSignaturesCompat(PackageSignatures existingSigs,
3348            PackageParser.Package scannedPkg) {
3349        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3350            return PackageManager.SIGNATURE_NO_MATCH;
3351        }
3352
3353        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3354        for (Signature sig : existingSigs.mSignatures) {
3355            existingSet.add(sig);
3356        }
3357        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3358        for (Signature sig : scannedPkg.mSignatures) {
3359            try {
3360                Signature[] chainSignatures = sig.getChainSignatures();
3361                for (Signature chainSig : chainSignatures) {
3362                    scannedCompatSet.add(chainSig);
3363                }
3364            } catch (CertificateEncodingException e) {
3365                scannedCompatSet.add(sig);
3366            }
3367        }
3368        /*
3369         * Make sure the expanded scanned set contains all signatures in the
3370         * existing one.
3371         */
3372        if (scannedCompatSet.equals(existingSet)) {
3373            // Migrate the old signatures to the new scheme.
3374            existingSigs.assignSignatures(scannedPkg.mSignatures);
3375            // The new KeySets will be re-added later in the scanning process.
3376            synchronized (mPackages) {
3377                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3378            }
3379            return PackageManager.SIGNATURE_MATCH;
3380        }
3381        return PackageManager.SIGNATURE_NO_MATCH;
3382    }
3383
3384    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3385        if (isExternal(scannedPkg)) {
3386            return mSettings.isExternalDatabaseVersionOlderThan(
3387                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3388        } else {
3389            return mSettings.isInternalDatabaseVersionOlderThan(
3390                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3391        }
3392    }
3393
3394    private int compareSignaturesRecover(PackageSignatures existingSigs,
3395            PackageParser.Package scannedPkg) {
3396        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3397            return PackageManager.SIGNATURE_NO_MATCH;
3398        }
3399
3400        String msg = null;
3401        try {
3402            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3403                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3404                        + scannedPkg.packageName);
3405                return PackageManager.SIGNATURE_MATCH;
3406            }
3407        } catch (CertificateException e) {
3408            msg = e.getMessage();
3409        }
3410
3411        logCriticalInfo(Log.INFO,
3412                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3413        return PackageManager.SIGNATURE_NO_MATCH;
3414    }
3415
3416    @Override
3417    public String[] getPackagesForUid(int uid) {
3418        uid = UserHandle.getAppId(uid);
3419        // reader
3420        synchronized (mPackages) {
3421            Object obj = mSettings.getUserIdLPr(uid);
3422            if (obj instanceof SharedUserSetting) {
3423                final SharedUserSetting sus = (SharedUserSetting) obj;
3424                final int N = sus.packages.size();
3425                final String[] res = new String[N];
3426                final Iterator<PackageSetting> it = sus.packages.iterator();
3427                int i = 0;
3428                while (it.hasNext()) {
3429                    res[i++] = it.next().name;
3430                }
3431                return res;
3432            } else if (obj instanceof PackageSetting) {
3433                final PackageSetting ps = (PackageSetting) obj;
3434                return new String[] { ps.name };
3435            }
3436        }
3437        return null;
3438    }
3439
3440    @Override
3441    public String getNameForUid(int uid) {
3442        // reader
3443        synchronized (mPackages) {
3444            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3445            if (obj instanceof SharedUserSetting) {
3446                final SharedUserSetting sus = (SharedUserSetting) obj;
3447                return sus.name + ":" + sus.userId;
3448            } else if (obj instanceof PackageSetting) {
3449                final PackageSetting ps = (PackageSetting) obj;
3450                return ps.name;
3451            }
3452        }
3453        return null;
3454    }
3455
3456    @Override
3457    public int getUidForSharedUser(String sharedUserName) {
3458        if(sharedUserName == null) {
3459            return -1;
3460        }
3461        // reader
3462        synchronized (mPackages) {
3463            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3464            if (suid == null) {
3465                return -1;
3466            }
3467            return suid.userId;
3468        }
3469    }
3470
3471    @Override
3472    public int getFlagsForUid(int uid) {
3473        synchronized (mPackages) {
3474            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3475            if (obj instanceof SharedUserSetting) {
3476                final SharedUserSetting sus = (SharedUserSetting) obj;
3477                return sus.pkgFlags;
3478            } else if (obj instanceof PackageSetting) {
3479                final PackageSetting ps = (PackageSetting) obj;
3480                return ps.pkgFlags;
3481            }
3482        }
3483        return 0;
3484    }
3485
3486    @Override
3487    public int getPrivateFlagsForUid(int uid) {
3488        synchronized (mPackages) {
3489            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3490            if (obj instanceof SharedUserSetting) {
3491                final SharedUserSetting sus = (SharedUserSetting) obj;
3492                return sus.pkgPrivateFlags;
3493            } else if (obj instanceof PackageSetting) {
3494                final PackageSetting ps = (PackageSetting) obj;
3495                return ps.pkgPrivateFlags;
3496            }
3497        }
3498        return 0;
3499    }
3500
3501    @Override
3502    public boolean isUidPrivileged(int uid) {
3503        uid = UserHandle.getAppId(uid);
3504        // reader
3505        synchronized (mPackages) {
3506            Object obj = mSettings.getUserIdLPr(uid);
3507            if (obj instanceof SharedUserSetting) {
3508                final SharedUserSetting sus = (SharedUserSetting) obj;
3509                final Iterator<PackageSetting> it = sus.packages.iterator();
3510                while (it.hasNext()) {
3511                    if (it.next().isPrivileged()) {
3512                        return true;
3513                    }
3514                }
3515            } else if (obj instanceof PackageSetting) {
3516                final PackageSetting ps = (PackageSetting) obj;
3517                return ps.isPrivileged();
3518            }
3519        }
3520        return false;
3521    }
3522
3523    @Override
3524    public String[] getAppOpPermissionPackages(String permissionName) {
3525        synchronized (mPackages) {
3526            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3527            if (pkgs == null) {
3528                return null;
3529            }
3530            return pkgs.toArray(new String[pkgs.size()]);
3531        }
3532    }
3533
3534    @Override
3535    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3536            int flags, int userId) {
3537        if (!sUserManager.exists(userId)) return null;
3538        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3539        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3540        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3541    }
3542
3543    @Override
3544    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3545            IntentFilter filter, int match, ComponentName activity) {
3546        final int userId = UserHandle.getCallingUserId();
3547        if (DEBUG_PREFERRED) {
3548            Log.v(TAG, "setLastChosenActivity intent=" + intent
3549                + " resolvedType=" + resolvedType
3550                + " flags=" + flags
3551                + " filter=" + filter
3552                + " match=" + match
3553                + " activity=" + activity);
3554            filter.dump(new PrintStreamPrinter(System.out), "    ");
3555        }
3556        intent.setComponent(null);
3557        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3558        // Find any earlier preferred or last chosen entries and nuke them
3559        findPreferredActivity(intent, resolvedType,
3560                flags, query, 0, false, true, false, userId);
3561        // Add the new activity as the last chosen for this filter
3562        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3563                "Setting last chosen");
3564    }
3565
3566    @Override
3567    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3568        final int userId = UserHandle.getCallingUserId();
3569        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3570        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3571        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3572                false, false, false, userId);
3573    }
3574
3575    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3576            int flags, List<ResolveInfo> query, int userId) {
3577        if (query != null) {
3578            final int N = query.size();
3579            if (N == 1) {
3580                return query.get(0);
3581            } else if (N > 1) {
3582                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3583                // If there is more than one activity with the same priority,
3584                // then let the user decide between them.
3585                ResolveInfo r0 = query.get(0);
3586                ResolveInfo r1 = query.get(1);
3587                if (DEBUG_INTENT_MATCHING || debug) {
3588                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3589                            + r1.activityInfo.name + "=" + r1.priority);
3590                }
3591                // If the first activity has a higher priority, or a different
3592                // default, then it is always desireable to pick it.
3593                if (r0.priority != r1.priority
3594                        || r0.preferredOrder != r1.preferredOrder
3595                        || r0.isDefault != r1.isDefault) {
3596                    return query.get(0);
3597                }
3598                // If we have saved a preference for a preferred activity for
3599                // this Intent, use that.
3600                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3601                        flags, query, r0.priority, true, false, debug, userId);
3602                if (ri != null) {
3603                    return ri;
3604                }
3605                if (userId != 0) {
3606                    ri = new ResolveInfo(mResolveInfo);
3607                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3608                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3609                            ri.activityInfo.applicationInfo);
3610                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3611                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3612                    return ri;
3613                }
3614                return mResolveInfo;
3615            }
3616        }
3617        return null;
3618    }
3619
3620    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3621            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3622        final int N = query.size();
3623        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3624                .get(userId);
3625        // Get the list of persistent preferred activities that handle the intent
3626        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3627        List<PersistentPreferredActivity> pprefs = ppir != null
3628                ? ppir.queryIntent(intent, resolvedType,
3629                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3630                : null;
3631        if (pprefs != null && pprefs.size() > 0) {
3632            final int M = pprefs.size();
3633            for (int i=0; i<M; i++) {
3634                final PersistentPreferredActivity ppa = pprefs.get(i);
3635                if (DEBUG_PREFERRED || debug) {
3636                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3637                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3638                            + "\n  component=" + ppa.mComponent);
3639                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3640                }
3641                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3642                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3643                if (DEBUG_PREFERRED || debug) {
3644                    Slog.v(TAG, "Found persistent preferred activity:");
3645                    if (ai != null) {
3646                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3647                    } else {
3648                        Slog.v(TAG, "  null");
3649                    }
3650                }
3651                if (ai == null) {
3652                    // This previously registered persistent preferred activity
3653                    // component is no longer known. Ignore it and do NOT remove it.
3654                    continue;
3655                }
3656                for (int j=0; j<N; j++) {
3657                    final ResolveInfo ri = query.get(j);
3658                    if (!ri.activityInfo.applicationInfo.packageName
3659                            .equals(ai.applicationInfo.packageName)) {
3660                        continue;
3661                    }
3662                    if (!ri.activityInfo.name.equals(ai.name)) {
3663                        continue;
3664                    }
3665                    //  Found a persistent preference that can handle the intent.
3666                    if (DEBUG_PREFERRED || debug) {
3667                        Slog.v(TAG, "Returning persistent preferred activity: " +
3668                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3669                    }
3670                    return ri;
3671                }
3672            }
3673        }
3674        return null;
3675    }
3676
3677    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3678            List<ResolveInfo> query, int priority, boolean always,
3679            boolean removeMatches, boolean debug, int userId) {
3680        if (!sUserManager.exists(userId)) return null;
3681        // writer
3682        synchronized (mPackages) {
3683            if (intent.getSelector() != null) {
3684                intent = intent.getSelector();
3685            }
3686            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3687
3688            // Try to find a matching persistent preferred activity.
3689            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3690                    debug, userId);
3691
3692            // If a persistent preferred activity matched, use it.
3693            if (pri != null) {
3694                return pri;
3695            }
3696
3697            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3698            // Get the list of preferred activities that handle the intent
3699            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3700            List<PreferredActivity> prefs = pir != null
3701                    ? pir.queryIntent(intent, resolvedType,
3702                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3703                    : null;
3704            if (prefs != null && prefs.size() > 0) {
3705                boolean changed = false;
3706                try {
3707                    // First figure out how good the original match set is.
3708                    // We will only allow preferred activities that came
3709                    // from the same match quality.
3710                    int match = 0;
3711
3712                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3713
3714                    final int N = query.size();
3715                    for (int j=0; j<N; j++) {
3716                        final ResolveInfo ri = query.get(j);
3717                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3718                                + ": 0x" + Integer.toHexString(match));
3719                        if (ri.match > match) {
3720                            match = ri.match;
3721                        }
3722                    }
3723
3724                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3725                            + Integer.toHexString(match));
3726
3727                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3728                    final int M = prefs.size();
3729                    for (int i=0; i<M; i++) {
3730                        final PreferredActivity pa = prefs.get(i);
3731                        if (DEBUG_PREFERRED || debug) {
3732                            Slog.v(TAG, "Checking PreferredActivity ds="
3733                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3734                                    + "\n  component=" + pa.mPref.mComponent);
3735                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3736                        }
3737                        if (pa.mPref.mMatch != match) {
3738                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3739                                    + Integer.toHexString(pa.mPref.mMatch));
3740                            continue;
3741                        }
3742                        // If it's not an "always" type preferred activity and that's what we're
3743                        // looking for, skip it.
3744                        if (always && !pa.mPref.mAlways) {
3745                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3746                            continue;
3747                        }
3748                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3749                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3750                        if (DEBUG_PREFERRED || debug) {
3751                            Slog.v(TAG, "Found preferred activity:");
3752                            if (ai != null) {
3753                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3754                            } else {
3755                                Slog.v(TAG, "  null");
3756                            }
3757                        }
3758                        if (ai == null) {
3759                            // This previously registered preferred activity
3760                            // component is no longer known.  Most likely an update
3761                            // to the app was installed and in the new version this
3762                            // component no longer exists.  Clean it up by removing
3763                            // it from the preferred activities list, and skip it.
3764                            Slog.w(TAG, "Removing dangling preferred activity: "
3765                                    + pa.mPref.mComponent);
3766                            pir.removeFilter(pa);
3767                            changed = true;
3768                            continue;
3769                        }
3770                        for (int j=0; j<N; j++) {
3771                            final ResolveInfo ri = query.get(j);
3772                            if (!ri.activityInfo.applicationInfo.packageName
3773                                    .equals(ai.applicationInfo.packageName)) {
3774                                continue;
3775                            }
3776                            if (!ri.activityInfo.name.equals(ai.name)) {
3777                                continue;
3778                            }
3779
3780                            if (removeMatches) {
3781                                pir.removeFilter(pa);
3782                                changed = true;
3783                                if (DEBUG_PREFERRED) {
3784                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3785                                }
3786                                break;
3787                            }
3788
3789                            // Okay we found a previously set preferred or last chosen app.
3790                            // If the result set is different from when this
3791                            // was created, we need to clear it and re-ask the
3792                            // user their preference, if we're looking for an "always" type entry.
3793                            if (always && !pa.mPref.sameSet(query)) {
3794                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3795                                        + intent + " type " + resolvedType);
3796                                if (DEBUG_PREFERRED) {
3797                                    Slog.v(TAG, "Removing preferred activity since set changed "
3798                                            + pa.mPref.mComponent);
3799                                }
3800                                pir.removeFilter(pa);
3801                                // Re-add the filter as a "last chosen" entry (!always)
3802                                PreferredActivity lastChosen = new PreferredActivity(
3803                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3804                                pir.addFilter(lastChosen);
3805                                changed = true;
3806                                return null;
3807                            }
3808
3809                            // Yay! Either the set matched or we're looking for the last chosen
3810                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3811                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3812                            return ri;
3813                        }
3814                    }
3815                } finally {
3816                    if (changed) {
3817                        if (DEBUG_PREFERRED) {
3818                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3819                        }
3820                        scheduleWritePackageRestrictionsLocked(userId);
3821                    }
3822                }
3823            }
3824        }
3825        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3826        return null;
3827    }
3828
3829    /*
3830     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3831     */
3832    @Override
3833    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3834            int targetUserId) {
3835        mContext.enforceCallingOrSelfPermission(
3836                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3837        List<CrossProfileIntentFilter> matches =
3838                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3839        if (matches != null) {
3840            int size = matches.size();
3841            for (int i = 0; i < size; i++) {
3842                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3843            }
3844        }
3845        return false;
3846    }
3847
3848    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3849            String resolvedType, int userId) {
3850        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3851        if (resolver != null) {
3852            return resolver.queryIntent(intent, resolvedType, false, userId);
3853        }
3854        return null;
3855    }
3856
3857    @Override
3858    public List<ResolveInfo> queryIntentActivities(Intent intent,
3859            String resolvedType, int flags, int userId) {
3860        if (!sUserManager.exists(userId)) return Collections.emptyList();
3861        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3862        ComponentName comp = intent.getComponent();
3863        if (comp == null) {
3864            if (intent.getSelector() != null) {
3865                intent = intent.getSelector();
3866                comp = intent.getComponent();
3867            }
3868        }
3869
3870        if (comp != null) {
3871            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3872            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3873            if (ai != null) {
3874                final ResolveInfo ri = new ResolveInfo();
3875                ri.activityInfo = ai;
3876                list.add(ri);
3877            }
3878            return list;
3879        }
3880
3881        // reader
3882        synchronized (mPackages) {
3883            final String pkgName = intent.getPackage();
3884            if (pkgName == null) {
3885                List<CrossProfileIntentFilter> matchingFilters =
3886                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3887                // Check for results that need to skip the current profile.
3888                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3889                        resolvedType, flags, userId);
3890                if (resolveInfo != null) {
3891                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3892                    result.add(resolveInfo);
3893                    return filterIfNotPrimaryUser(result, userId);
3894                }
3895                // Check for cross profile results.
3896                resolveInfo = queryCrossProfileIntents(
3897                        matchingFilters, intent, resolvedType, flags, userId);
3898
3899                // Check for results in the current profile. Adding GET_RESOLVED_FILTER flags
3900                // as we need it later
3901                List<ResolveInfo> result = mActivities.queryIntent(
3902                        intent, resolvedType, flags, userId);
3903                if (resolveInfo != null) {
3904                    result.add(resolveInfo);
3905                    Collections.sort(result, mResolvePrioritySorter);
3906                }
3907                result = filterIfNotPrimaryUser(result, userId);
3908                if (result.size() > 1) {
3909                    return filterCandidatesWithDomainPreferedActivitiesLPw(result);
3910                }
3911
3912                return result;
3913            }
3914            final PackageParser.Package pkg = mPackages.get(pkgName);
3915            if (pkg != null) {
3916                return filterIfNotPrimaryUser(
3917                        mActivities.queryIntentForPackage(
3918                                intent, resolvedType, flags, pkg.activities, userId),
3919                        userId);
3920            }
3921            return new ArrayList<ResolveInfo>();
3922        }
3923    }
3924
3925    /**
3926     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
3927     *
3928     * @return filtered list
3929     */
3930    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
3931        if (userId == UserHandle.USER_OWNER) {
3932            return resolveInfos;
3933        }
3934        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
3935            ResolveInfo info = resolveInfos.get(i);
3936            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
3937                resolveInfos.remove(i);
3938            }
3939        }
3940        return resolveInfos;
3941    }
3942
3943    private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPw(
3944            List<ResolveInfo> candidates) {
3945        if (DEBUG_PREFERRED) {
3946            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
3947                    candidates.size());
3948        }
3949        final int userId = UserHandle.getCallingUserId();
3950        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(candidates);
3951        synchronized (mPackages) {
3952            final int count = result.size();
3953            for (int n = count-1; n >= 0; n--) {
3954                ResolveInfo info = result.get(n);
3955                if (!info.filterNeedsVerification) {
3956                    continue;
3957                }
3958                String packageName = info.activityInfo.packageName;
3959                PackageSetting ps = mSettings.mPackages.get(packageName);
3960                if (ps != null) {
3961                    // Try to get the status from User settings first
3962                    int status = ps.getDomainVerificationStatusForUser(userId);
3963                    // if none available, get the master status
3964                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
3965                        if (ps.getIntentFilterVerificationInfo() != null) {
3966                            status = ps.getIntentFilterVerificationInfo().getStatus();
3967                        }
3968                    }
3969                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
3970                        result.clear();
3971                        result.add(info);
3972                        // We break the for loop as we are good to go
3973                        break;
3974                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
3975                        result.remove(n);
3976                    }
3977                }
3978            }
3979        }
3980        if (DEBUG_PREFERRED) {
3981            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
3982                    result.size());
3983        }
3984        return result;
3985    }
3986
3987    private ResolveInfo querySkipCurrentProfileIntents(
3988            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3989            int flags, int sourceUserId) {
3990        if (matchingFilters != null) {
3991            int size = matchingFilters.size();
3992            for (int i = 0; i < size; i ++) {
3993                CrossProfileIntentFilter filter = matchingFilters.get(i);
3994                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3995                    // Checking if there are activities in the target user that can handle the
3996                    // intent.
3997                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3998                            flags, sourceUserId);
3999                    if (resolveInfo != null) {
4000                        return resolveInfo;
4001                    }
4002                }
4003            }
4004        }
4005        return null;
4006    }
4007
4008    // Return matching ResolveInfo if any for skip current profile intent filters.
4009    private ResolveInfo queryCrossProfileIntents(
4010            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4011            int flags, int sourceUserId) {
4012        if (matchingFilters != null) {
4013            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4014            // match the same intent. For performance reasons, it is better not to
4015            // run queryIntent twice for the same userId
4016            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4017            int size = matchingFilters.size();
4018            for (int i = 0; i < size; i++) {
4019                CrossProfileIntentFilter filter = matchingFilters.get(i);
4020                int targetUserId = filter.getTargetUserId();
4021                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4022                        && !alreadyTriedUserIds.get(targetUserId)) {
4023                    // Checking if there are activities in the target user that can handle the
4024                    // intent.
4025                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4026                            flags, sourceUserId);
4027                    if (resolveInfo != null) return resolveInfo;
4028                    alreadyTriedUserIds.put(targetUserId, true);
4029                }
4030            }
4031        }
4032        return null;
4033    }
4034
4035    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4036            String resolvedType, int flags, int sourceUserId) {
4037        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4038                resolvedType, flags, filter.getTargetUserId());
4039        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4040            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4041        }
4042        return null;
4043    }
4044
4045    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4046            int sourceUserId, int targetUserId) {
4047        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4048        String className;
4049        if (targetUserId == UserHandle.USER_OWNER) {
4050            className = FORWARD_INTENT_TO_USER_OWNER;
4051        } else {
4052            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4053        }
4054        ComponentName forwardingActivityComponentName = new ComponentName(
4055                mAndroidApplication.packageName, className);
4056        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4057                sourceUserId);
4058        if (targetUserId == UserHandle.USER_OWNER) {
4059            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4060            forwardingResolveInfo.noResourceId = true;
4061        }
4062        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4063        forwardingResolveInfo.priority = 0;
4064        forwardingResolveInfo.preferredOrder = 0;
4065        forwardingResolveInfo.match = 0;
4066        forwardingResolveInfo.isDefault = true;
4067        forwardingResolveInfo.filter = filter;
4068        forwardingResolveInfo.targetUserId = targetUserId;
4069        return forwardingResolveInfo;
4070    }
4071
4072    @Override
4073    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4074            Intent[] specifics, String[] specificTypes, Intent intent,
4075            String resolvedType, int flags, int userId) {
4076        if (!sUserManager.exists(userId)) return Collections.emptyList();
4077        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4078                false, "query intent activity options");
4079        final String resultsAction = intent.getAction();
4080
4081        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4082                | PackageManager.GET_RESOLVED_FILTER, userId);
4083
4084        if (DEBUG_INTENT_MATCHING) {
4085            Log.v(TAG, "Query " + intent + ": " + results);
4086        }
4087
4088        int specificsPos = 0;
4089        int N;
4090
4091        // todo: note that the algorithm used here is O(N^2).  This
4092        // isn't a problem in our current environment, but if we start running
4093        // into situations where we have more than 5 or 10 matches then this
4094        // should probably be changed to something smarter...
4095
4096        // First we go through and resolve each of the specific items
4097        // that were supplied, taking care of removing any corresponding
4098        // duplicate items in the generic resolve list.
4099        if (specifics != null) {
4100            for (int i=0; i<specifics.length; i++) {
4101                final Intent sintent = specifics[i];
4102                if (sintent == null) {
4103                    continue;
4104                }
4105
4106                if (DEBUG_INTENT_MATCHING) {
4107                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4108                }
4109
4110                String action = sintent.getAction();
4111                if (resultsAction != null && resultsAction.equals(action)) {
4112                    // If this action was explicitly requested, then don't
4113                    // remove things that have it.
4114                    action = null;
4115                }
4116
4117                ResolveInfo ri = null;
4118                ActivityInfo ai = null;
4119
4120                ComponentName comp = sintent.getComponent();
4121                if (comp == null) {
4122                    ri = resolveIntent(
4123                        sintent,
4124                        specificTypes != null ? specificTypes[i] : null,
4125                            flags, userId);
4126                    if (ri == null) {
4127                        continue;
4128                    }
4129                    if (ri == mResolveInfo) {
4130                        // ACK!  Must do something better with this.
4131                    }
4132                    ai = ri.activityInfo;
4133                    comp = new ComponentName(ai.applicationInfo.packageName,
4134                            ai.name);
4135                } else {
4136                    ai = getActivityInfo(comp, flags, userId);
4137                    if (ai == null) {
4138                        continue;
4139                    }
4140                }
4141
4142                // Look for any generic query activities that are duplicates
4143                // of this specific one, and remove them from the results.
4144                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4145                N = results.size();
4146                int j;
4147                for (j=specificsPos; j<N; j++) {
4148                    ResolveInfo sri = results.get(j);
4149                    if ((sri.activityInfo.name.equals(comp.getClassName())
4150                            && sri.activityInfo.applicationInfo.packageName.equals(
4151                                    comp.getPackageName()))
4152                        || (action != null && sri.filter.matchAction(action))) {
4153                        results.remove(j);
4154                        if (DEBUG_INTENT_MATCHING) Log.v(
4155                            TAG, "Removing duplicate item from " + j
4156                            + " due to specific " + specificsPos);
4157                        if (ri == null) {
4158                            ri = sri;
4159                        }
4160                        j--;
4161                        N--;
4162                    }
4163                }
4164
4165                // Add this specific item to its proper place.
4166                if (ri == null) {
4167                    ri = new ResolveInfo();
4168                    ri.activityInfo = ai;
4169                }
4170                results.add(specificsPos, ri);
4171                ri.specificIndex = i;
4172                specificsPos++;
4173            }
4174        }
4175
4176        // Now we go through the remaining generic results and remove any
4177        // duplicate actions that are found here.
4178        N = results.size();
4179        for (int i=specificsPos; i<N-1; i++) {
4180            final ResolveInfo rii = results.get(i);
4181            if (rii.filter == null) {
4182                continue;
4183            }
4184
4185            // Iterate over all of the actions of this result's intent
4186            // filter...  typically this should be just one.
4187            final Iterator<String> it = rii.filter.actionsIterator();
4188            if (it == null) {
4189                continue;
4190            }
4191            while (it.hasNext()) {
4192                final String action = it.next();
4193                if (resultsAction != null && resultsAction.equals(action)) {
4194                    // If this action was explicitly requested, then don't
4195                    // remove things that have it.
4196                    continue;
4197                }
4198                for (int j=i+1; j<N; j++) {
4199                    final ResolveInfo rij = results.get(j);
4200                    if (rij.filter != null && rij.filter.hasAction(action)) {
4201                        results.remove(j);
4202                        if (DEBUG_INTENT_MATCHING) Log.v(
4203                            TAG, "Removing duplicate item from " + j
4204                            + " due to action " + action + " at " + i);
4205                        j--;
4206                        N--;
4207                    }
4208                }
4209            }
4210
4211            // If the caller didn't request filter information, drop it now
4212            // so we don't have to marshall/unmarshall it.
4213            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4214                rii.filter = null;
4215            }
4216        }
4217
4218        // Filter out the caller activity if so requested.
4219        if (caller != null) {
4220            N = results.size();
4221            for (int i=0; i<N; i++) {
4222                ActivityInfo ainfo = results.get(i).activityInfo;
4223                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4224                        && caller.getClassName().equals(ainfo.name)) {
4225                    results.remove(i);
4226                    break;
4227                }
4228            }
4229        }
4230
4231        // If the caller didn't request filter information,
4232        // drop them now so we don't have to
4233        // marshall/unmarshall it.
4234        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4235            N = results.size();
4236            for (int i=0; i<N; i++) {
4237                results.get(i).filter = null;
4238            }
4239        }
4240
4241        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4242        return results;
4243    }
4244
4245    @Override
4246    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4247            int userId) {
4248        if (!sUserManager.exists(userId)) return Collections.emptyList();
4249        ComponentName comp = intent.getComponent();
4250        if (comp == null) {
4251            if (intent.getSelector() != null) {
4252                intent = intent.getSelector();
4253                comp = intent.getComponent();
4254            }
4255        }
4256        if (comp != null) {
4257            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4258            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4259            if (ai != null) {
4260                ResolveInfo ri = new ResolveInfo();
4261                ri.activityInfo = ai;
4262                list.add(ri);
4263            }
4264            return list;
4265        }
4266
4267        // reader
4268        synchronized (mPackages) {
4269            String pkgName = intent.getPackage();
4270            if (pkgName == null) {
4271                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4272            }
4273            final PackageParser.Package pkg = mPackages.get(pkgName);
4274            if (pkg != null) {
4275                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4276                        userId);
4277            }
4278            return null;
4279        }
4280    }
4281
4282    @Override
4283    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4284        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4285        if (!sUserManager.exists(userId)) return null;
4286        if (query != null) {
4287            if (query.size() >= 1) {
4288                // If there is more than one service with the same priority,
4289                // just arbitrarily pick the first one.
4290                return query.get(0);
4291            }
4292        }
4293        return null;
4294    }
4295
4296    @Override
4297    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4298            int userId) {
4299        if (!sUserManager.exists(userId)) return Collections.emptyList();
4300        ComponentName comp = intent.getComponent();
4301        if (comp == null) {
4302            if (intent.getSelector() != null) {
4303                intent = intent.getSelector();
4304                comp = intent.getComponent();
4305            }
4306        }
4307        if (comp != null) {
4308            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4309            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4310            if (si != null) {
4311                final ResolveInfo ri = new ResolveInfo();
4312                ri.serviceInfo = si;
4313                list.add(ri);
4314            }
4315            return list;
4316        }
4317
4318        // reader
4319        synchronized (mPackages) {
4320            String pkgName = intent.getPackage();
4321            if (pkgName == null) {
4322                return mServices.queryIntent(intent, resolvedType, flags, userId);
4323            }
4324            final PackageParser.Package pkg = mPackages.get(pkgName);
4325            if (pkg != null) {
4326                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4327                        userId);
4328            }
4329            return null;
4330        }
4331    }
4332
4333    @Override
4334    public List<ResolveInfo> queryIntentContentProviders(
4335            Intent intent, String resolvedType, int flags, int userId) {
4336        if (!sUserManager.exists(userId)) return Collections.emptyList();
4337        ComponentName comp = intent.getComponent();
4338        if (comp == null) {
4339            if (intent.getSelector() != null) {
4340                intent = intent.getSelector();
4341                comp = intent.getComponent();
4342            }
4343        }
4344        if (comp != null) {
4345            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4346            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4347            if (pi != null) {
4348                final ResolveInfo ri = new ResolveInfo();
4349                ri.providerInfo = pi;
4350                list.add(ri);
4351            }
4352            return list;
4353        }
4354
4355        // reader
4356        synchronized (mPackages) {
4357            String pkgName = intent.getPackage();
4358            if (pkgName == null) {
4359                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4360            }
4361            final PackageParser.Package pkg = mPackages.get(pkgName);
4362            if (pkg != null) {
4363                return mProviders.queryIntentForPackage(
4364                        intent, resolvedType, flags, pkg.providers, userId);
4365            }
4366            return null;
4367        }
4368    }
4369
4370    @Override
4371    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4372        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4373
4374        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4375
4376        // writer
4377        synchronized (mPackages) {
4378            ArrayList<PackageInfo> list;
4379            if (listUninstalled) {
4380                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4381                for (PackageSetting ps : mSettings.mPackages.values()) {
4382                    PackageInfo pi;
4383                    if (ps.pkg != null) {
4384                        pi = generatePackageInfo(ps.pkg, flags, userId);
4385                    } else {
4386                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4387                    }
4388                    if (pi != null) {
4389                        list.add(pi);
4390                    }
4391                }
4392            } else {
4393                list = new ArrayList<PackageInfo>(mPackages.size());
4394                for (PackageParser.Package p : mPackages.values()) {
4395                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4396                    if (pi != null) {
4397                        list.add(pi);
4398                    }
4399                }
4400            }
4401
4402            return new ParceledListSlice<PackageInfo>(list);
4403        }
4404    }
4405
4406    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4407            String[] permissions, boolean[] tmp, int flags, int userId) {
4408        int numMatch = 0;
4409        final PermissionsState permissionsState = ps.getPermissionsState();
4410        for (int i=0; i<permissions.length; i++) {
4411            final String permission = permissions[i];
4412            if (permissionsState.hasPermission(permission, userId)) {
4413                tmp[i] = true;
4414                numMatch++;
4415            } else {
4416                tmp[i] = false;
4417            }
4418        }
4419        if (numMatch == 0) {
4420            return;
4421        }
4422        PackageInfo pi;
4423        if (ps.pkg != null) {
4424            pi = generatePackageInfo(ps.pkg, flags, userId);
4425        } else {
4426            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4427        }
4428        // The above might return null in cases of uninstalled apps or install-state
4429        // skew across users/profiles.
4430        if (pi != null) {
4431            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4432                if (numMatch == permissions.length) {
4433                    pi.requestedPermissions = permissions;
4434                } else {
4435                    pi.requestedPermissions = new String[numMatch];
4436                    numMatch = 0;
4437                    for (int i=0; i<permissions.length; i++) {
4438                        if (tmp[i]) {
4439                            pi.requestedPermissions[numMatch] = permissions[i];
4440                            numMatch++;
4441                        }
4442                    }
4443                }
4444            }
4445            list.add(pi);
4446        }
4447    }
4448
4449    @Override
4450    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4451            String[] permissions, int flags, int userId) {
4452        if (!sUserManager.exists(userId)) return null;
4453        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4454
4455        // writer
4456        synchronized (mPackages) {
4457            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4458            boolean[] tmpBools = new boolean[permissions.length];
4459            if (listUninstalled) {
4460                for (PackageSetting ps : mSettings.mPackages.values()) {
4461                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4462                }
4463            } else {
4464                for (PackageParser.Package pkg : mPackages.values()) {
4465                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4466                    if (ps != null) {
4467                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4468                                userId);
4469                    }
4470                }
4471            }
4472
4473            return new ParceledListSlice<PackageInfo>(list);
4474        }
4475    }
4476
4477    @Override
4478    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4479        if (!sUserManager.exists(userId)) return null;
4480        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4481
4482        // writer
4483        synchronized (mPackages) {
4484            ArrayList<ApplicationInfo> list;
4485            if (listUninstalled) {
4486                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4487                for (PackageSetting ps : mSettings.mPackages.values()) {
4488                    ApplicationInfo ai;
4489                    if (ps.pkg != null) {
4490                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4491                                ps.readUserState(userId), userId);
4492                    } else {
4493                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4494                    }
4495                    if (ai != null) {
4496                        list.add(ai);
4497                    }
4498                }
4499            } else {
4500                list = new ArrayList<ApplicationInfo>(mPackages.size());
4501                for (PackageParser.Package p : mPackages.values()) {
4502                    if (p.mExtras != null) {
4503                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4504                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4505                        if (ai != null) {
4506                            list.add(ai);
4507                        }
4508                    }
4509                }
4510            }
4511
4512            return new ParceledListSlice<ApplicationInfo>(list);
4513        }
4514    }
4515
4516    public List<ApplicationInfo> getPersistentApplications(int flags) {
4517        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4518
4519        // reader
4520        synchronized (mPackages) {
4521            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4522            final int userId = UserHandle.getCallingUserId();
4523            while (i.hasNext()) {
4524                final PackageParser.Package p = i.next();
4525                if (p.applicationInfo != null
4526                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4527                        && (!mSafeMode || isSystemApp(p))) {
4528                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4529                    if (ps != null) {
4530                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4531                                ps.readUserState(userId), userId);
4532                        if (ai != null) {
4533                            finalList.add(ai);
4534                        }
4535                    }
4536                }
4537            }
4538        }
4539
4540        return finalList;
4541    }
4542
4543    @Override
4544    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4545        if (!sUserManager.exists(userId)) return null;
4546        // reader
4547        synchronized (mPackages) {
4548            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4549            PackageSetting ps = provider != null
4550                    ? mSettings.mPackages.get(provider.owner.packageName)
4551                    : null;
4552            return ps != null
4553                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4554                    && (!mSafeMode || (provider.info.applicationInfo.flags
4555                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4556                    ? PackageParser.generateProviderInfo(provider, flags,
4557                            ps.readUserState(userId), userId)
4558                    : null;
4559        }
4560    }
4561
4562    /**
4563     * @deprecated
4564     */
4565    @Deprecated
4566    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4567        // reader
4568        synchronized (mPackages) {
4569            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4570                    .entrySet().iterator();
4571            final int userId = UserHandle.getCallingUserId();
4572            while (i.hasNext()) {
4573                Map.Entry<String, PackageParser.Provider> entry = i.next();
4574                PackageParser.Provider p = entry.getValue();
4575                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4576
4577                if (ps != null && p.syncable
4578                        && (!mSafeMode || (p.info.applicationInfo.flags
4579                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4580                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4581                            ps.readUserState(userId), userId);
4582                    if (info != null) {
4583                        outNames.add(entry.getKey());
4584                        outInfo.add(info);
4585                    }
4586                }
4587            }
4588        }
4589    }
4590
4591    @Override
4592    public List<ProviderInfo> queryContentProviders(String processName,
4593            int uid, int flags) {
4594        ArrayList<ProviderInfo> finalList = null;
4595        // reader
4596        synchronized (mPackages) {
4597            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4598            final int userId = processName != null ?
4599                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4600            while (i.hasNext()) {
4601                final PackageParser.Provider p = i.next();
4602                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4603                if (ps != null && p.info.authority != null
4604                        && (processName == null
4605                                || (p.info.processName.equals(processName)
4606                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4607                        && mSettings.isEnabledLPr(p.info, flags, userId)
4608                        && (!mSafeMode
4609                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4610                    if (finalList == null) {
4611                        finalList = new ArrayList<ProviderInfo>(3);
4612                    }
4613                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4614                            ps.readUserState(userId), userId);
4615                    if (info != null) {
4616                        finalList.add(info);
4617                    }
4618                }
4619            }
4620        }
4621
4622        if (finalList != null) {
4623            Collections.sort(finalList, mProviderInitOrderSorter);
4624        }
4625
4626        return finalList;
4627    }
4628
4629    @Override
4630    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4631            int flags) {
4632        // reader
4633        synchronized (mPackages) {
4634            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4635            return PackageParser.generateInstrumentationInfo(i, flags);
4636        }
4637    }
4638
4639    @Override
4640    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4641            int flags) {
4642        ArrayList<InstrumentationInfo> finalList =
4643            new ArrayList<InstrumentationInfo>();
4644
4645        // reader
4646        synchronized (mPackages) {
4647            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4648            while (i.hasNext()) {
4649                final PackageParser.Instrumentation p = i.next();
4650                if (targetPackage == null
4651                        || targetPackage.equals(p.info.targetPackage)) {
4652                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4653                            flags);
4654                    if (ii != null) {
4655                        finalList.add(ii);
4656                    }
4657                }
4658            }
4659        }
4660
4661        return finalList;
4662    }
4663
4664    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4665        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4666        if (overlays == null) {
4667            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4668            return;
4669        }
4670        for (PackageParser.Package opkg : overlays.values()) {
4671            // Not much to do if idmap fails: we already logged the error
4672            // and we certainly don't want to abort installation of pkg simply
4673            // because an overlay didn't fit properly. For these reasons,
4674            // ignore the return value of createIdmapForPackagePairLI.
4675            createIdmapForPackagePairLI(pkg, opkg);
4676        }
4677    }
4678
4679    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4680            PackageParser.Package opkg) {
4681        if (!opkg.mTrustedOverlay) {
4682            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4683                    opkg.baseCodePath + ": overlay not trusted");
4684            return false;
4685        }
4686        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4687        if (overlaySet == null) {
4688            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4689                    opkg.baseCodePath + " but target package has no known overlays");
4690            return false;
4691        }
4692        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4693        // TODO: generate idmap for split APKs
4694        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4695            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4696                    + opkg.baseCodePath);
4697            return false;
4698        }
4699        PackageParser.Package[] overlayArray =
4700            overlaySet.values().toArray(new PackageParser.Package[0]);
4701        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4702            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4703                return p1.mOverlayPriority - p2.mOverlayPriority;
4704            }
4705        };
4706        Arrays.sort(overlayArray, cmp);
4707
4708        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4709        int i = 0;
4710        for (PackageParser.Package p : overlayArray) {
4711            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4712        }
4713        return true;
4714    }
4715
4716    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4717        final File[] files = dir.listFiles();
4718        if (ArrayUtils.isEmpty(files)) {
4719            Log.d(TAG, "No files in app dir " + dir);
4720            return;
4721        }
4722
4723        if (DEBUG_PACKAGE_SCANNING) {
4724            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4725                    + " flags=0x" + Integer.toHexString(parseFlags));
4726        }
4727
4728        for (File file : files) {
4729            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4730                    && !PackageInstallerService.isStageName(file.getName());
4731            if (!isPackage) {
4732                // Ignore entries which are not packages
4733                continue;
4734            }
4735            try {
4736                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4737                        scanFlags, currentTime, null);
4738            } catch (PackageManagerException e) {
4739                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4740
4741                // Delete invalid userdata apps
4742                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4743                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4744                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4745                    if (file.isDirectory()) {
4746                        mInstaller.rmPackageDir(file.getAbsolutePath());
4747                    } else {
4748                        file.delete();
4749                    }
4750                }
4751            }
4752        }
4753    }
4754
4755    private static File getSettingsProblemFile() {
4756        File dataDir = Environment.getDataDirectory();
4757        File systemDir = new File(dataDir, "system");
4758        File fname = new File(systemDir, "uiderrors.txt");
4759        return fname;
4760    }
4761
4762    static void reportSettingsProblem(int priority, String msg) {
4763        logCriticalInfo(priority, msg);
4764    }
4765
4766    static void logCriticalInfo(int priority, String msg) {
4767        Slog.println(priority, TAG, msg);
4768        EventLogTags.writePmCriticalInfo(msg);
4769        try {
4770            File fname = getSettingsProblemFile();
4771            FileOutputStream out = new FileOutputStream(fname, true);
4772            PrintWriter pw = new FastPrintWriter(out);
4773            SimpleDateFormat formatter = new SimpleDateFormat();
4774            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4775            pw.println(dateString + ": " + msg);
4776            pw.close();
4777            FileUtils.setPermissions(
4778                    fname.toString(),
4779                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4780                    -1, -1);
4781        } catch (java.io.IOException e) {
4782        }
4783    }
4784
4785    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4786            PackageParser.Package pkg, File srcFile, int parseFlags)
4787            throws PackageManagerException {
4788        if (ps != null
4789                && ps.codePath.equals(srcFile)
4790                && ps.timeStamp == srcFile.lastModified()
4791                && !isCompatSignatureUpdateNeeded(pkg)
4792                && !isRecoverSignatureUpdateNeeded(pkg)) {
4793            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4794            if (ps.signatures.mSignatures != null
4795                    && ps.signatures.mSignatures.length != 0
4796                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4797                // Optimization: reuse the existing cached certificates
4798                // if the package appears to be unchanged.
4799                pkg.mSignatures = ps.signatures.mSignatures;
4800                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4801                synchronized (mPackages) {
4802                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4803                }
4804                return;
4805            }
4806
4807            Slog.w(TAG, "PackageSetting for " + ps.name
4808                    + " is missing signatures.  Collecting certs again to recover them.");
4809        } else {
4810            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4811        }
4812
4813        try {
4814            pp.collectCertificates(pkg, parseFlags);
4815            pp.collectManifestDigest(pkg);
4816        } catch (PackageParserException e) {
4817            throw PackageManagerException.from(e);
4818        }
4819    }
4820
4821    /*
4822     *  Scan a package and return the newly parsed package.
4823     *  Returns null in case of errors and the error code is stored in mLastScanError
4824     */
4825    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4826            long currentTime, UserHandle user) throws PackageManagerException {
4827        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4828        parseFlags |= mDefParseFlags;
4829        PackageParser pp = new PackageParser();
4830        pp.setSeparateProcesses(mSeparateProcesses);
4831        pp.setOnlyCoreApps(mOnlyCore);
4832        pp.setDisplayMetrics(mMetrics);
4833
4834        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4835            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4836        }
4837
4838        final PackageParser.Package pkg;
4839        try {
4840            pkg = pp.parsePackage(scanFile, parseFlags);
4841        } catch (PackageParserException e) {
4842            throw PackageManagerException.from(e);
4843        }
4844
4845        PackageSetting ps = null;
4846        PackageSetting updatedPkg;
4847        // reader
4848        synchronized (mPackages) {
4849            // Look to see if we already know about this package.
4850            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4851            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4852                // This package has been renamed to its original name.  Let's
4853                // use that.
4854                ps = mSettings.peekPackageLPr(oldName);
4855            }
4856            // If there was no original package, see one for the real package name.
4857            if (ps == null) {
4858                ps = mSettings.peekPackageLPr(pkg.packageName);
4859            }
4860            // Check to see if this package could be hiding/updating a system
4861            // package.  Must look for it either under the original or real
4862            // package name depending on our state.
4863            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4864            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4865        }
4866        boolean updatedPkgBetter = false;
4867        // First check if this is a system package that may involve an update
4868        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4869            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
4870            // it needs to drop FLAG_PRIVILEGED.
4871            if (locationIsPrivileged(scanFile)) {
4872                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4873            } else {
4874                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4875            }
4876
4877            if (ps != null && !ps.codePath.equals(scanFile)) {
4878                // The path has changed from what was last scanned...  check the
4879                // version of the new path against what we have stored to determine
4880                // what to do.
4881                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4882                if (pkg.mVersionCode <= ps.versionCode) {
4883                    // The system package has been updated and the code path does not match
4884                    // Ignore entry. Skip it.
4885                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
4886                            + " ignored: updated version " + ps.versionCode
4887                            + " better than this " + pkg.mVersionCode);
4888                    if (!updatedPkg.codePath.equals(scanFile)) {
4889                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4890                                + ps.name + " changing from " + updatedPkg.codePathString
4891                                + " to " + scanFile);
4892                        updatedPkg.codePath = scanFile;
4893                        updatedPkg.codePathString = scanFile.toString();
4894                        updatedPkg.resourcePath = scanFile;
4895                        updatedPkg.resourcePathString = scanFile.toString();
4896                    }
4897                    updatedPkg.pkg = pkg;
4898                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4899                } else {
4900                    // The current app on the system partition is better than
4901                    // what we have updated to on the data partition; switch
4902                    // back to the system partition version.
4903                    // At this point, its safely assumed that package installation for
4904                    // apps in system partition will go through. If not there won't be a working
4905                    // version of the app
4906                    // writer
4907                    synchronized (mPackages) {
4908                        // Just remove the loaded entries from package lists.
4909                        mPackages.remove(ps.name);
4910                    }
4911
4912                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4913                            + " reverting from " + ps.codePathString
4914                            + ": new version " + pkg.mVersionCode
4915                            + " better than installed " + ps.versionCode);
4916
4917                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4918                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4919                            getAppDexInstructionSets(ps));
4920                    synchronized (mInstallLock) {
4921                        args.cleanUpResourcesLI();
4922                    }
4923                    synchronized (mPackages) {
4924                        mSettings.enableSystemPackageLPw(ps.name);
4925                    }
4926                    updatedPkgBetter = true;
4927                }
4928            }
4929        }
4930
4931        if (updatedPkg != null) {
4932            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4933            // initially
4934            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4935
4936            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4937            // flag set initially
4938            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
4939                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4940            }
4941        }
4942
4943        // Verify certificates against what was last scanned
4944        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4945
4946        /*
4947         * A new system app appeared, but we already had a non-system one of the
4948         * same name installed earlier.
4949         */
4950        boolean shouldHideSystemApp = false;
4951        if (updatedPkg == null && ps != null
4952                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4953            /*
4954             * Check to make sure the signatures match first. If they don't,
4955             * wipe the installed application and its data.
4956             */
4957            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4958                    != PackageManager.SIGNATURE_MATCH) {
4959                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
4960                        + " signatures don't match existing userdata copy; removing");
4961                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4962                ps = null;
4963            } else {
4964                /*
4965                 * If the newly-added system app is an older version than the
4966                 * already installed version, hide it. It will be scanned later
4967                 * and re-added like an update.
4968                 */
4969                if (pkg.mVersionCode <= ps.versionCode) {
4970                    shouldHideSystemApp = true;
4971                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
4972                            + " but new version " + pkg.mVersionCode + " better than installed "
4973                            + ps.versionCode + "; hiding system");
4974                } else {
4975                    /*
4976                     * The newly found system app is a newer version that the
4977                     * one previously installed. Simply remove the
4978                     * already-installed application and replace it with our own
4979                     * while keeping the application data.
4980                     */
4981                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4982                            + " reverting from " + ps.codePathString + ": new version "
4983                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
4984                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4985                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4986                            getAppDexInstructionSets(ps));
4987                    synchronized (mInstallLock) {
4988                        args.cleanUpResourcesLI();
4989                    }
4990                }
4991            }
4992        }
4993
4994        // The apk is forward locked (not public) if its code and resources
4995        // are kept in different files. (except for app in either system or
4996        // vendor path).
4997        // TODO grab this value from PackageSettings
4998        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4999            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5000                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5001            }
5002        }
5003
5004        // TODO: extend to support forward-locked splits
5005        String resourcePath = null;
5006        String baseResourcePath = null;
5007        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5008            if (ps != null && ps.resourcePathString != null) {
5009                resourcePath = ps.resourcePathString;
5010                baseResourcePath = ps.resourcePathString;
5011            } else {
5012                // Should not happen at all. Just log an error.
5013                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5014            }
5015        } else {
5016            resourcePath = pkg.codePath;
5017            baseResourcePath = pkg.baseCodePath;
5018        }
5019
5020        // Set application objects path explicitly.
5021        pkg.applicationInfo.setCodePath(pkg.codePath);
5022        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5023        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5024        pkg.applicationInfo.setResourcePath(resourcePath);
5025        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5026        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5027
5028        // Note that we invoke the following method only if we are about to unpack an application
5029        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5030                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5031
5032        /*
5033         * If the system app should be overridden by a previously installed
5034         * data, hide the system app now and let the /data/app scan pick it up
5035         * again.
5036         */
5037        if (shouldHideSystemApp) {
5038            synchronized (mPackages) {
5039                /*
5040                 * We have to grant systems permissions before we hide, because
5041                 * grantPermissions will assume the package update is trying to
5042                 * expand its permissions.
5043                 */
5044                grantPermissionsLPw(pkg, true, pkg.packageName);
5045                mSettings.disableSystemPackageLPw(pkg.packageName);
5046            }
5047        }
5048
5049        return scannedPkg;
5050    }
5051
5052    private static String fixProcessName(String defProcessName,
5053            String processName, int uid) {
5054        if (processName == null) {
5055            return defProcessName;
5056        }
5057        return processName;
5058    }
5059
5060    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5061            throws PackageManagerException {
5062        if (pkgSetting.signatures.mSignatures != null) {
5063            // Already existing package. Make sure signatures match
5064            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5065                    == PackageManager.SIGNATURE_MATCH;
5066            if (!match) {
5067                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5068                        == PackageManager.SIGNATURE_MATCH;
5069            }
5070            if (!match) {
5071                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5072                        == PackageManager.SIGNATURE_MATCH;
5073            }
5074            if (!match) {
5075                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5076                        + pkg.packageName + " signatures do not match the "
5077                        + "previously installed version; ignoring!");
5078            }
5079        }
5080
5081        // Check for shared user signatures
5082        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5083            // Already existing package. Make sure signatures match
5084            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5085                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5086            if (!match) {
5087                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5088                        == PackageManager.SIGNATURE_MATCH;
5089            }
5090            if (!match) {
5091                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5092                        == PackageManager.SIGNATURE_MATCH;
5093            }
5094            if (!match) {
5095                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5096                        "Package " + pkg.packageName
5097                        + " has no signatures that match those in shared user "
5098                        + pkgSetting.sharedUser.name + "; ignoring!");
5099            }
5100        }
5101    }
5102
5103    /**
5104     * Enforces that only the system UID or root's UID can call a method exposed
5105     * via Binder.
5106     *
5107     * @param message used as message if SecurityException is thrown
5108     * @throws SecurityException if the caller is not system or root
5109     */
5110    private static final void enforceSystemOrRoot(String message) {
5111        final int uid = Binder.getCallingUid();
5112        if (uid != Process.SYSTEM_UID && uid != 0) {
5113            throw new SecurityException(message);
5114        }
5115    }
5116
5117    @Override
5118    public void performBootDexOpt() {
5119        enforceSystemOrRoot("Only the system can request dexopt be performed");
5120
5121        // Before everything else, see whether we need to fstrim.
5122        try {
5123            IMountService ms = PackageHelper.getMountService();
5124            if (ms != null) {
5125                final boolean isUpgrade = isUpgrade();
5126                boolean doTrim = isUpgrade;
5127                if (doTrim) {
5128                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5129                } else {
5130                    final long interval = android.provider.Settings.Global.getLong(
5131                            mContext.getContentResolver(),
5132                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5133                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5134                    if (interval > 0) {
5135                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5136                        if (timeSinceLast > interval) {
5137                            doTrim = true;
5138                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5139                                    + "; running immediately");
5140                        }
5141                    }
5142                }
5143                if (doTrim) {
5144                    if (!isFirstBoot()) {
5145                        try {
5146                            ActivityManagerNative.getDefault().showBootMessage(
5147                                    mContext.getResources().getString(
5148                                            R.string.android_upgrading_fstrim), true);
5149                        } catch (RemoteException e) {
5150                        }
5151                    }
5152                    ms.runMaintenance();
5153                }
5154            } else {
5155                Slog.e(TAG, "Mount service unavailable!");
5156            }
5157        } catch (RemoteException e) {
5158            // Can't happen; MountService is local
5159        }
5160
5161        final ArraySet<PackageParser.Package> pkgs;
5162        synchronized (mPackages) {
5163            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5164        }
5165
5166        if (pkgs != null) {
5167            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5168            // in case the device runs out of space.
5169            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5170            // Give priority to core apps.
5171            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5172                PackageParser.Package pkg = it.next();
5173                if (pkg.coreApp) {
5174                    if (DEBUG_DEXOPT) {
5175                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5176                    }
5177                    sortedPkgs.add(pkg);
5178                    it.remove();
5179                }
5180            }
5181            // Give priority to system apps that listen for pre boot complete.
5182            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5183            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5184            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5185                PackageParser.Package pkg = it.next();
5186                if (pkgNames.contains(pkg.packageName)) {
5187                    if (DEBUG_DEXOPT) {
5188                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5189                    }
5190                    sortedPkgs.add(pkg);
5191                    it.remove();
5192                }
5193            }
5194            // Give priority to system apps.
5195            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5196                PackageParser.Package pkg = it.next();
5197                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5198                    if (DEBUG_DEXOPT) {
5199                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5200                    }
5201                    sortedPkgs.add(pkg);
5202                    it.remove();
5203                }
5204            }
5205            // Give priority to updated system apps.
5206            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5207                PackageParser.Package pkg = it.next();
5208                if (pkg.isUpdatedSystemApp()) {
5209                    if (DEBUG_DEXOPT) {
5210                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5211                    }
5212                    sortedPkgs.add(pkg);
5213                    it.remove();
5214                }
5215            }
5216            // Give priority to apps that listen for boot complete.
5217            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5218            pkgNames = getPackageNamesForIntent(intent);
5219            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5220                PackageParser.Package pkg = it.next();
5221                if (pkgNames.contains(pkg.packageName)) {
5222                    if (DEBUG_DEXOPT) {
5223                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5224                    }
5225                    sortedPkgs.add(pkg);
5226                    it.remove();
5227                }
5228            }
5229            // Filter out packages that aren't recently used.
5230            filterRecentlyUsedApps(pkgs);
5231            // Add all remaining apps.
5232            for (PackageParser.Package pkg : pkgs) {
5233                if (DEBUG_DEXOPT) {
5234                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5235                }
5236                sortedPkgs.add(pkg);
5237            }
5238
5239            // If we want to be lazy, filter everything that wasn't recently used.
5240            if (mLazyDexOpt) {
5241                filterRecentlyUsedApps(sortedPkgs);
5242            }
5243
5244            int i = 0;
5245            int total = sortedPkgs.size();
5246            File dataDir = Environment.getDataDirectory();
5247            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5248            if (lowThreshold == 0) {
5249                throw new IllegalStateException("Invalid low memory threshold");
5250            }
5251            for (PackageParser.Package pkg : sortedPkgs) {
5252                long usableSpace = dataDir.getUsableSpace();
5253                if (usableSpace < lowThreshold) {
5254                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5255                    break;
5256                }
5257                performBootDexOpt(pkg, ++i, total);
5258            }
5259        }
5260    }
5261
5262    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5263        // Filter out packages that aren't recently used.
5264        //
5265        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5266        // should do a full dexopt.
5267        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5268            int total = pkgs.size();
5269            int skipped = 0;
5270            long now = System.currentTimeMillis();
5271            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5272                PackageParser.Package pkg = i.next();
5273                long then = pkg.mLastPackageUsageTimeInMills;
5274                if (then + mDexOptLRUThresholdInMills < now) {
5275                    if (DEBUG_DEXOPT) {
5276                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5277                              ((then == 0) ? "never" : new Date(then)));
5278                    }
5279                    i.remove();
5280                    skipped++;
5281                }
5282            }
5283            if (DEBUG_DEXOPT) {
5284                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5285            }
5286        }
5287    }
5288
5289    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5290        List<ResolveInfo> ris = null;
5291        try {
5292            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5293                    intent, null, 0, UserHandle.USER_OWNER);
5294        } catch (RemoteException e) {
5295        }
5296        ArraySet<String> pkgNames = new ArraySet<String>();
5297        if (ris != null) {
5298            for (ResolveInfo ri : ris) {
5299                pkgNames.add(ri.activityInfo.packageName);
5300            }
5301        }
5302        return pkgNames;
5303    }
5304
5305    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5306        if (DEBUG_DEXOPT) {
5307            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5308        }
5309        if (!isFirstBoot()) {
5310            try {
5311                ActivityManagerNative.getDefault().showBootMessage(
5312                        mContext.getResources().getString(R.string.android_upgrading_apk,
5313                                curr, total), true);
5314            } catch (RemoteException e) {
5315            }
5316        }
5317        PackageParser.Package p = pkg;
5318        synchronized (mInstallLock) {
5319            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5320                    false /* force dex */, false /* defer */, true /* include dependencies */);
5321        }
5322    }
5323
5324    @Override
5325    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5326        return performDexOpt(packageName, instructionSet, false);
5327    }
5328
5329    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5330        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5331        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5332        if (!dexopt && !updateUsage) {
5333            // We aren't going to dexopt or update usage, so bail early.
5334            return false;
5335        }
5336        PackageParser.Package p;
5337        final String targetInstructionSet;
5338        synchronized (mPackages) {
5339            p = mPackages.get(packageName);
5340            if (p == null) {
5341                return false;
5342            }
5343            if (updateUsage) {
5344                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5345            }
5346            mPackageUsage.write(false);
5347            if (!dexopt) {
5348                // We aren't going to dexopt, so bail early.
5349                return false;
5350            }
5351
5352            targetInstructionSet = instructionSet != null ? instructionSet :
5353                    getPrimaryInstructionSet(p.applicationInfo);
5354            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5355                return false;
5356            }
5357        }
5358
5359        synchronized (mInstallLock) {
5360            final String[] instructionSets = new String[] { targetInstructionSet };
5361            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5362                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5363            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5364        }
5365    }
5366
5367    public ArraySet<String> getPackagesThatNeedDexOpt() {
5368        ArraySet<String> pkgs = null;
5369        synchronized (mPackages) {
5370            for (PackageParser.Package p : mPackages.values()) {
5371                if (DEBUG_DEXOPT) {
5372                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5373                }
5374                if (!p.mDexOptPerformed.isEmpty()) {
5375                    continue;
5376                }
5377                if (pkgs == null) {
5378                    pkgs = new ArraySet<String>();
5379                }
5380                pkgs.add(p.packageName);
5381            }
5382        }
5383        return pkgs;
5384    }
5385
5386    public void shutdown() {
5387        mPackageUsage.write(true);
5388    }
5389
5390    @Override
5391    public void forceDexOpt(String packageName) {
5392        enforceSystemOrRoot("forceDexOpt");
5393
5394        PackageParser.Package pkg;
5395        synchronized (mPackages) {
5396            pkg = mPackages.get(packageName);
5397            if (pkg == null) {
5398                throw new IllegalArgumentException("Missing package: " + packageName);
5399            }
5400        }
5401
5402        synchronized (mInstallLock) {
5403            final String[] instructionSets = new String[] {
5404                    getPrimaryInstructionSet(pkg.applicationInfo) };
5405            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5406                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5407            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5408                throw new IllegalStateException("Failed to dexopt: " + res);
5409            }
5410        }
5411    }
5412
5413    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5414        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5415            Slog.w(TAG, "Unable to update from " + oldPkg.name
5416                    + " to " + newPkg.packageName
5417                    + ": old package not in system partition");
5418            return false;
5419        } else if (mPackages.get(oldPkg.name) != null) {
5420            Slog.w(TAG, "Unable to update from " + oldPkg.name
5421                    + " to " + newPkg.packageName
5422                    + ": old package still exists");
5423            return false;
5424        }
5425        return true;
5426    }
5427
5428    private File getDataPathForPackage(String packageName, int userId) {
5429        /*
5430         * Until we fully support multiple users, return the directory we
5431         * previously would have. The PackageManagerTests will need to be
5432         * revised when this is changed back..
5433         */
5434        if (userId == 0) {
5435            return new File(mAppDataDir, packageName);
5436        } else {
5437            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
5438                + File.separator + packageName);
5439        }
5440    }
5441
5442    private int createDataDirsLI(String packageName, int uid, String seinfo) {
5443        int[] users = sUserManager.getUserIds();
5444        int res = mInstaller.install(packageName, uid, uid, seinfo);
5445        if (res < 0) {
5446            return res;
5447        }
5448        for (int user : users) {
5449            if (user != 0) {
5450                res = mInstaller.createUserData(packageName,
5451                        UserHandle.getUid(user, uid), user, seinfo);
5452                if (res < 0) {
5453                    return res;
5454                }
5455            }
5456        }
5457        return res;
5458    }
5459
5460    private int removeDataDirsLI(String packageName) {
5461        int[] users = sUserManager.getUserIds();
5462        int res = 0;
5463        for (int user : users) {
5464            int resInner = mInstaller.remove(packageName, user);
5465            if (resInner < 0) {
5466                res = resInner;
5467            }
5468        }
5469
5470        return res;
5471    }
5472
5473    private int deleteCodeCacheDirsLI(String packageName) {
5474        int[] users = sUserManager.getUserIds();
5475        int res = 0;
5476        for (int user : users) {
5477            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
5478            if (resInner < 0) {
5479                res = resInner;
5480            }
5481        }
5482        return res;
5483    }
5484
5485    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5486            PackageParser.Package changingLib) {
5487        if (file.path != null) {
5488            usesLibraryFiles.add(file.path);
5489            return;
5490        }
5491        PackageParser.Package p = mPackages.get(file.apk);
5492        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5493            // If we are doing this while in the middle of updating a library apk,
5494            // then we need to make sure to use that new apk for determining the
5495            // dependencies here.  (We haven't yet finished committing the new apk
5496            // to the package manager state.)
5497            if (p == null || p.packageName.equals(changingLib.packageName)) {
5498                p = changingLib;
5499            }
5500        }
5501        if (p != null) {
5502            usesLibraryFiles.addAll(p.getAllCodePaths());
5503        }
5504    }
5505
5506    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5507            PackageParser.Package changingLib) throws PackageManagerException {
5508        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5509            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5510            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5511            for (int i=0; i<N; i++) {
5512                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5513                if (file == null) {
5514                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5515                            "Package " + pkg.packageName + " requires unavailable shared library "
5516                            + pkg.usesLibraries.get(i) + "; failing!");
5517                }
5518                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5519            }
5520            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5521            for (int i=0; i<N; i++) {
5522                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5523                if (file == null) {
5524                    Slog.w(TAG, "Package " + pkg.packageName
5525                            + " desires unavailable shared library "
5526                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5527                } else {
5528                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5529                }
5530            }
5531            N = usesLibraryFiles.size();
5532            if (N > 0) {
5533                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5534            } else {
5535                pkg.usesLibraryFiles = null;
5536            }
5537        }
5538    }
5539
5540    private static boolean hasString(List<String> list, List<String> which) {
5541        if (list == null) {
5542            return false;
5543        }
5544        for (int i=list.size()-1; i>=0; i--) {
5545            for (int j=which.size()-1; j>=0; j--) {
5546                if (which.get(j).equals(list.get(i))) {
5547                    return true;
5548                }
5549            }
5550        }
5551        return false;
5552    }
5553
5554    private void updateAllSharedLibrariesLPw() {
5555        for (PackageParser.Package pkg : mPackages.values()) {
5556            try {
5557                updateSharedLibrariesLPw(pkg, null);
5558            } catch (PackageManagerException e) {
5559                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5560            }
5561        }
5562    }
5563
5564    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5565            PackageParser.Package changingPkg) {
5566        ArrayList<PackageParser.Package> res = null;
5567        for (PackageParser.Package pkg : mPackages.values()) {
5568            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5569                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5570                if (res == null) {
5571                    res = new ArrayList<PackageParser.Package>();
5572                }
5573                res.add(pkg);
5574                try {
5575                    updateSharedLibrariesLPw(pkg, changingPkg);
5576                } catch (PackageManagerException e) {
5577                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5578                }
5579            }
5580        }
5581        return res;
5582    }
5583
5584    /**
5585     * Derive the value of the {@code cpuAbiOverride} based on the provided
5586     * value and an optional stored value from the package settings.
5587     */
5588    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5589        String cpuAbiOverride = null;
5590
5591        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5592            cpuAbiOverride = null;
5593        } else if (abiOverride != null) {
5594            cpuAbiOverride = abiOverride;
5595        } else if (settings != null) {
5596            cpuAbiOverride = settings.cpuAbiOverrideString;
5597        }
5598
5599        return cpuAbiOverride;
5600    }
5601
5602    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5603            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5604        boolean success = false;
5605        try {
5606            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5607                    currentTime, user);
5608            success = true;
5609            return res;
5610        } finally {
5611            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5612                removeDataDirsLI(pkg.packageName);
5613            }
5614        }
5615    }
5616
5617    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5618            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5619        final File scanFile = new File(pkg.codePath);
5620        if (pkg.applicationInfo.getCodePath() == null ||
5621                pkg.applicationInfo.getResourcePath() == null) {
5622            // Bail out. The resource and code paths haven't been set.
5623            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5624                    "Code and resource paths haven't been set correctly");
5625        }
5626
5627        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5628            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5629        } else {
5630            // Only allow system apps to be flagged as core apps.
5631            pkg.coreApp = false;
5632        }
5633
5634        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5635            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5636        }
5637
5638        if (mCustomResolverComponentName != null &&
5639                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5640            setUpCustomResolverActivity(pkg);
5641        }
5642
5643        if (pkg.packageName.equals("android")) {
5644            synchronized (mPackages) {
5645                if (mAndroidApplication != null) {
5646                    Slog.w(TAG, "*************************************************");
5647                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5648                    Slog.w(TAG, " file=" + scanFile);
5649                    Slog.w(TAG, "*************************************************");
5650                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5651                            "Core android package being redefined.  Skipping.");
5652                }
5653
5654                // Set up information for our fall-back user intent resolution activity.
5655                mPlatformPackage = pkg;
5656                pkg.mVersionCode = mSdkVersion;
5657                mAndroidApplication = pkg.applicationInfo;
5658
5659                if (!mResolverReplaced) {
5660                    mResolveActivity.applicationInfo = mAndroidApplication;
5661                    mResolveActivity.name = ResolverActivity.class.getName();
5662                    mResolveActivity.packageName = mAndroidApplication.packageName;
5663                    mResolveActivity.processName = "system:ui";
5664                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5665                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5666                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5667                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5668                    mResolveActivity.exported = true;
5669                    mResolveActivity.enabled = true;
5670                    mResolveInfo.activityInfo = mResolveActivity;
5671                    mResolveInfo.priority = 0;
5672                    mResolveInfo.preferredOrder = 0;
5673                    mResolveInfo.match = 0;
5674                    mResolveComponentName = new ComponentName(
5675                            mAndroidApplication.packageName, mResolveActivity.name);
5676                }
5677            }
5678        }
5679
5680        if (DEBUG_PACKAGE_SCANNING) {
5681            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5682                Log.d(TAG, "Scanning package " + pkg.packageName);
5683        }
5684
5685        if (mPackages.containsKey(pkg.packageName)
5686                || mSharedLibraries.containsKey(pkg.packageName)) {
5687            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5688                    "Application package " + pkg.packageName
5689                    + " already installed.  Skipping duplicate.");
5690        }
5691
5692        // If we're only installing presumed-existing packages, require that the
5693        // scanned APK is both already known and at the path previously established
5694        // for it.  Previously unknown packages we pick up normally, but if we have an
5695        // a priori expectation about this package's install presence, enforce it.
5696        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
5697            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
5698            if (known != null) {
5699                if (DEBUG_PACKAGE_SCANNING) {
5700                    Log.d(TAG, "Examining " + pkg.codePath
5701                            + " and requiring known paths " + known.codePathString
5702                            + " & " + known.resourcePathString);
5703                }
5704                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
5705                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
5706                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
5707                            "Application package " + pkg.packageName
5708                            + " found at " + pkg.applicationInfo.getCodePath()
5709                            + " but expected at " + known.codePathString + "; ignoring.");
5710                }
5711            }
5712        }
5713
5714        // Initialize package source and resource directories
5715        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5716        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5717
5718        SharedUserSetting suid = null;
5719        PackageSetting pkgSetting = null;
5720
5721        if (!isSystemApp(pkg)) {
5722            // Only system apps can use these features.
5723            pkg.mOriginalPackages = null;
5724            pkg.mRealPackage = null;
5725            pkg.mAdoptPermissions = null;
5726        }
5727
5728        // writer
5729        synchronized (mPackages) {
5730            if (pkg.mSharedUserId != null) {
5731                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5732                if (suid == null) {
5733                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5734                            "Creating application package " + pkg.packageName
5735                            + " for shared user failed");
5736                }
5737                if (DEBUG_PACKAGE_SCANNING) {
5738                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5739                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5740                                + "): packages=" + suid.packages);
5741                }
5742            }
5743
5744            // Check if we are renaming from an original package name.
5745            PackageSetting origPackage = null;
5746            String realName = null;
5747            if (pkg.mOriginalPackages != null) {
5748                // This package may need to be renamed to a previously
5749                // installed name.  Let's check on that...
5750                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5751                if (pkg.mOriginalPackages.contains(renamed)) {
5752                    // This package had originally been installed as the
5753                    // original name, and we have already taken care of
5754                    // transitioning to the new one.  Just update the new
5755                    // one to continue using the old name.
5756                    realName = pkg.mRealPackage;
5757                    if (!pkg.packageName.equals(renamed)) {
5758                        // Callers into this function may have already taken
5759                        // care of renaming the package; only do it here if
5760                        // it is not already done.
5761                        pkg.setPackageName(renamed);
5762                    }
5763
5764                } else {
5765                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5766                        if ((origPackage = mSettings.peekPackageLPr(
5767                                pkg.mOriginalPackages.get(i))) != null) {
5768                            // We do have the package already installed under its
5769                            // original name...  should we use it?
5770                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5771                                // New package is not compatible with original.
5772                                origPackage = null;
5773                                continue;
5774                            } else if (origPackage.sharedUser != null) {
5775                                // Make sure uid is compatible between packages.
5776                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5777                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5778                                            + " to " + pkg.packageName + ": old uid "
5779                                            + origPackage.sharedUser.name
5780                                            + " differs from " + pkg.mSharedUserId);
5781                                    origPackage = null;
5782                                    continue;
5783                                }
5784                            } else {
5785                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5786                                        + pkg.packageName + " to old name " + origPackage.name);
5787                            }
5788                            break;
5789                        }
5790                    }
5791                }
5792            }
5793
5794            if (mTransferedPackages.contains(pkg.packageName)) {
5795                Slog.w(TAG, "Package " + pkg.packageName
5796                        + " was transferred to another, but its .apk remains");
5797            }
5798
5799            // Just create the setting, don't add it yet. For already existing packages
5800            // the PkgSetting exists already and doesn't have to be created.
5801            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5802                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5803                    pkg.applicationInfo.primaryCpuAbi,
5804                    pkg.applicationInfo.secondaryCpuAbi,
5805                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
5806                    user, false);
5807            if (pkgSetting == null) {
5808                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5809                        "Creating application package " + pkg.packageName + " failed");
5810            }
5811
5812            if (pkgSetting.origPackage != null) {
5813                // If we are first transitioning from an original package,
5814                // fix up the new package's name now.  We need to do this after
5815                // looking up the package under its new name, so getPackageLP
5816                // can take care of fiddling things correctly.
5817                pkg.setPackageName(origPackage.name);
5818
5819                // File a report about this.
5820                String msg = "New package " + pkgSetting.realName
5821                        + " renamed to replace old package " + pkgSetting.name;
5822                reportSettingsProblem(Log.WARN, msg);
5823
5824                // Make a note of it.
5825                mTransferedPackages.add(origPackage.name);
5826
5827                // No longer need to retain this.
5828                pkgSetting.origPackage = null;
5829            }
5830
5831            if (realName != null) {
5832                // Make a note of it.
5833                mTransferedPackages.add(pkg.packageName);
5834            }
5835
5836            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5837                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5838            }
5839
5840            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5841                // Check all shared libraries and map to their actual file path.
5842                // We only do this here for apps not on a system dir, because those
5843                // are the only ones that can fail an install due to this.  We
5844                // will take care of the system apps by updating all of their
5845                // library paths after the scan is done.
5846                updateSharedLibrariesLPw(pkg, null);
5847            }
5848
5849            if (mFoundPolicyFile) {
5850                SELinuxMMAC.assignSeinfoValue(pkg);
5851            }
5852
5853            pkg.applicationInfo.uid = pkgSetting.appId;
5854            pkg.mExtras = pkgSetting;
5855            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5856                try {
5857                    verifySignaturesLP(pkgSetting, pkg);
5858                    // We just determined the app is signed correctly, so bring
5859                    // over the latest parsed certs.
5860                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5861                } catch (PackageManagerException e) {
5862                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5863                        throw e;
5864                    }
5865                    // The signature has changed, but this package is in the system
5866                    // image...  let's recover!
5867                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5868                    // However...  if this package is part of a shared user, but it
5869                    // doesn't match the signature of the shared user, let's fail.
5870                    // What this means is that you can't change the signatures
5871                    // associated with an overall shared user, which doesn't seem all
5872                    // that unreasonable.
5873                    if (pkgSetting.sharedUser != null) {
5874                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5875                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5876                            throw new PackageManagerException(
5877                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5878                                            "Signature mismatch for shared user : "
5879                                            + pkgSetting.sharedUser);
5880                        }
5881                    }
5882                    // File a report about this.
5883                    String msg = "System package " + pkg.packageName
5884                        + " signature changed; retaining data.";
5885                    reportSettingsProblem(Log.WARN, msg);
5886                }
5887            } else {
5888                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5889                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5890                            + pkg.packageName + " upgrade keys do not match the "
5891                            + "previously installed version");
5892                } else {
5893                    // We just determined the app is signed correctly, so bring
5894                    // over the latest parsed certs.
5895                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5896                }
5897            }
5898            // Verify that this new package doesn't have any content providers
5899            // that conflict with existing packages.  Only do this if the
5900            // package isn't already installed, since we don't want to break
5901            // things that are installed.
5902            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5903                final int N = pkg.providers.size();
5904                int i;
5905                for (i=0; i<N; i++) {
5906                    PackageParser.Provider p = pkg.providers.get(i);
5907                    if (p.info.authority != null) {
5908                        String names[] = p.info.authority.split(";");
5909                        for (int j = 0; j < names.length; j++) {
5910                            if (mProvidersByAuthority.containsKey(names[j])) {
5911                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5912                                final String otherPackageName =
5913                                        ((other != null && other.getComponentName() != null) ?
5914                                                other.getComponentName().getPackageName() : "?");
5915                                throw new PackageManagerException(
5916                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5917                                                "Can't install because provider name " + names[j]
5918                                                + " (in package " + pkg.applicationInfo.packageName
5919                                                + ") is already used by " + otherPackageName);
5920                            }
5921                        }
5922                    }
5923                }
5924            }
5925
5926            if (pkg.mAdoptPermissions != null) {
5927                // This package wants to adopt ownership of permissions from
5928                // another package.
5929                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5930                    final String origName = pkg.mAdoptPermissions.get(i);
5931                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5932                    if (orig != null) {
5933                        if (verifyPackageUpdateLPr(orig, pkg)) {
5934                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5935                                    + pkg.packageName);
5936                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5937                        }
5938                    }
5939                }
5940            }
5941        }
5942
5943        final String pkgName = pkg.packageName;
5944
5945        final long scanFileTime = scanFile.lastModified();
5946        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5947        pkg.applicationInfo.processName = fixProcessName(
5948                pkg.applicationInfo.packageName,
5949                pkg.applicationInfo.processName,
5950                pkg.applicationInfo.uid);
5951
5952        File dataPath;
5953        if (mPlatformPackage == pkg) {
5954            // The system package is special.
5955            dataPath = new File(Environment.getDataDirectory(), "system");
5956
5957            pkg.applicationInfo.dataDir = dataPath.getPath();
5958
5959        } else {
5960            // This is a normal package, need to make its data directory.
5961            dataPath = getDataPathForPackage(pkg.packageName, 0);
5962
5963            boolean uidError = false;
5964            if (dataPath.exists()) {
5965                int currentUid = 0;
5966                try {
5967                    StructStat stat = Os.stat(dataPath.getPath());
5968                    currentUid = stat.st_uid;
5969                } catch (ErrnoException e) {
5970                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5971                }
5972
5973                // If we have mismatched owners for the data path, we have a problem.
5974                if (currentUid != pkg.applicationInfo.uid) {
5975                    boolean recovered = false;
5976                    if (currentUid == 0) {
5977                        // The directory somehow became owned by root.  Wow.
5978                        // This is probably because the system was stopped while
5979                        // installd was in the middle of messing with its libs
5980                        // directory.  Ask installd to fix that.
5981                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5982                                pkg.applicationInfo.uid);
5983                        if (ret >= 0) {
5984                            recovered = true;
5985                            String msg = "Package " + pkg.packageName
5986                                    + " unexpectedly changed to uid 0; recovered to " +
5987                                    + pkg.applicationInfo.uid;
5988                            reportSettingsProblem(Log.WARN, msg);
5989                        }
5990                    }
5991                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5992                            || (scanFlags&SCAN_BOOTING) != 0)) {
5993                        // If this is a system app, we can at least delete its
5994                        // current data so the application will still work.
5995                        int ret = removeDataDirsLI(pkgName);
5996                        if (ret >= 0) {
5997                            // TODO: Kill the processes first
5998                            // Old data gone!
5999                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6000                                    ? "System package " : "Third party package ";
6001                            String msg = prefix + pkg.packageName
6002                                    + " has changed from uid: "
6003                                    + currentUid + " to "
6004                                    + pkg.applicationInfo.uid + "; old data erased";
6005                            reportSettingsProblem(Log.WARN, msg);
6006                            recovered = true;
6007
6008                            // And now re-install the app.
6009                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
6010                                                   pkg.applicationInfo.seinfo);
6011                            if (ret == -1) {
6012                                // Ack should not happen!
6013                                msg = prefix + pkg.packageName
6014                                        + " could not have data directory re-created after delete.";
6015                                reportSettingsProblem(Log.WARN, msg);
6016                                throw new PackageManagerException(
6017                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6018                            }
6019                        }
6020                        if (!recovered) {
6021                            mHasSystemUidErrors = true;
6022                        }
6023                    } else if (!recovered) {
6024                        // If we allow this install to proceed, we will be broken.
6025                        // Abort, abort!
6026                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6027                                "scanPackageLI");
6028                    }
6029                    if (!recovered) {
6030                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6031                            + pkg.applicationInfo.uid + "/fs_"
6032                            + currentUid;
6033                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6034                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6035                        String msg = "Package " + pkg.packageName
6036                                + " has mismatched uid: "
6037                                + currentUid + " on disk, "
6038                                + pkg.applicationInfo.uid + " in settings";
6039                        // writer
6040                        synchronized (mPackages) {
6041                            mSettings.mReadMessages.append(msg);
6042                            mSettings.mReadMessages.append('\n');
6043                            uidError = true;
6044                            if (!pkgSetting.uidError) {
6045                                reportSettingsProblem(Log.ERROR, msg);
6046                            }
6047                        }
6048                    }
6049                }
6050                pkg.applicationInfo.dataDir = dataPath.getPath();
6051                if (mShouldRestoreconData) {
6052                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6053                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
6054                                pkg.applicationInfo.uid);
6055                }
6056            } else {
6057                if (DEBUG_PACKAGE_SCANNING) {
6058                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6059                        Log.v(TAG, "Want this data dir: " + dataPath);
6060                }
6061                //invoke installer to do the actual installation
6062                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
6063                                           pkg.applicationInfo.seinfo);
6064                if (ret < 0) {
6065                    // Error from installer
6066                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6067                            "Unable to create data dirs [errorCode=" + ret + "]");
6068                }
6069
6070                if (dataPath.exists()) {
6071                    pkg.applicationInfo.dataDir = dataPath.getPath();
6072                } else {
6073                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6074                    pkg.applicationInfo.dataDir = null;
6075                }
6076            }
6077
6078            pkgSetting.uidError = uidError;
6079        }
6080
6081        final String path = scanFile.getPath();
6082        final String codePath = pkg.applicationInfo.getCodePath();
6083        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6084        if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6085            setBundledAppAbisAndRoots(pkg, pkgSetting);
6086
6087            // If we haven't found any native libraries for the app, check if it has
6088            // renderscript code. We'll need to force the app to 32 bit if it has
6089            // renderscript bitcode.
6090            if (pkg.applicationInfo.primaryCpuAbi == null
6091                    && pkg.applicationInfo.secondaryCpuAbi == null
6092                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
6093                NativeLibraryHelper.Handle handle = null;
6094                try {
6095                    handle = NativeLibraryHelper.Handle.create(scanFile);
6096                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6097                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6098                    }
6099                } catch (IOException ioe) {
6100                    Slog.w(TAG, "Error scanning system app : " + ioe);
6101                } finally {
6102                    IoUtils.closeQuietly(handle);
6103                }
6104            }
6105
6106            setNativeLibraryPaths(pkg);
6107        } else {
6108            // TODO: We can probably be smarter about this stuff. For installed apps,
6109            // we can calculate this information at install time once and for all. For
6110            // system apps, we can probably assume that this information doesn't change
6111            // after the first boot scan. As things stand, we do lots of unnecessary work.
6112
6113            // Give ourselves some initial paths; we'll come back for another
6114            // pass once we've determined ABI below.
6115            setNativeLibraryPaths(pkg);
6116
6117            final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg);
6118            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6119            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6120
6121            NativeLibraryHelper.Handle handle = null;
6122            try {
6123                handle = NativeLibraryHelper.Handle.create(scanFile);
6124                // TODO(multiArch): This can be null for apps that didn't go through the
6125                // usual installation process. We can calculate it again, like we
6126                // do during install time.
6127                //
6128                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6129                // unnecessary.
6130                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6131
6132                // Null out the abis so that they can be recalculated.
6133                pkg.applicationInfo.primaryCpuAbi = null;
6134                pkg.applicationInfo.secondaryCpuAbi = null;
6135                if (isMultiArch(pkg.applicationInfo)) {
6136                    // Warn if we've set an abiOverride for multi-lib packages..
6137                    // By definition, we need to copy both 32 and 64 bit libraries for
6138                    // such packages.
6139                    if (pkg.cpuAbiOverride != null
6140                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
6141                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
6142                    }
6143
6144                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
6145                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
6146                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
6147                        if (isAsec) {
6148                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
6149                        } else {
6150                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6151                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
6152                                    useIsaSpecificSubdirs);
6153                        }
6154                    }
6155
6156                    maybeThrowExceptionForMultiArchCopy(
6157                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
6158
6159                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
6160                        if (isAsec) {
6161                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
6162                        } else {
6163                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6164                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
6165                                    useIsaSpecificSubdirs);
6166                        }
6167                    }
6168
6169                    maybeThrowExceptionForMultiArchCopy(
6170                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
6171
6172                    if (abi64 >= 0) {
6173                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
6174                    }
6175
6176                    if (abi32 >= 0) {
6177                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
6178                        if (abi64 >= 0) {
6179                            pkg.applicationInfo.secondaryCpuAbi = abi;
6180                        } else {
6181                            pkg.applicationInfo.primaryCpuAbi = abi;
6182                        }
6183                    }
6184                } else {
6185                    String[] abiList = (cpuAbiOverride != null) ?
6186                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
6187
6188                    // Enable gross and lame hacks for apps that are built with old
6189                    // SDK tools. We must scan their APKs for renderscript bitcode and
6190                    // not launch them if it's present. Don't bother checking on devices
6191                    // that don't have 64 bit support.
6192                    boolean needsRenderScriptOverride = false;
6193                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
6194                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6195                        abiList = Build.SUPPORTED_32_BIT_ABIS;
6196                        needsRenderScriptOverride = true;
6197                    }
6198
6199                    final int copyRet;
6200                    if (isAsec) {
6201                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6202                    } else {
6203                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6204                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
6205                    }
6206
6207                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
6208                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6209                                "Error unpackaging native libs for app, errorCode=" + copyRet);
6210                    }
6211
6212                    if (copyRet >= 0) {
6213                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
6214                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
6215                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
6216                    } else if (needsRenderScriptOverride) {
6217                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
6218                    }
6219                }
6220            } catch (IOException ioe) {
6221                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
6222            } finally {
6223                IoUtils.closeQuietly(handle);
6224            }
6225
6226            // Now that we've calculated the ABIs and determined if it's an internal app,
6227            // we will go ahead and populate the nativeLibraryPath.
6228            setNativeLibraryPaths(pkg);
6229
6230            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6231            final int[] userIds = sUserManager.getUserIds();
6232            synchronized (mInstallLock) {
6233                // Create a native library symlink only if we have native libraries
6234                // and if the native libraries are 32 bit libraries. We do not provide
6235                // this symlink for 64 bit libraries.
6236                if (pkg.applicationInfo.primaryCpuAbi != null &&
6237                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6238                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6239                    for (int userId : userIds) {
6240                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
6241                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6242                                    "Failed linking native library dir (user=" + userId + ")");
6243                        }
6244                    }
6245                }
6246            }
6247        }
6248
6249        // This is a special case for the "system" package, where the ABI is
6250        // dictated by the zygote configuration (and init.rc). We should keep track
6251        // of this ABI so that we can deal with "normal" applications that run under
6252        // the same UID correctly.
6253        if (mPlatformPackage == pkg) {
6254            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6255                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6256        }
6257
6258        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6259        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6260        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6261        // Copy the derived override back to the parsed package, so that we can
6262        // update the package settings accordingly.
6263        pkg.cpuAbiOverride = cpuAbiOverride;
6264
6265        if (DEBUG_ABI_SELECTION) {
6266            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6267                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6268                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6269        }
6270
6271        // Push the derived path down into PackageSettings so we know what to
6272        // clean up at uninstall time.
6273        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6274
6275        if (DEBUG_ABI_SELECTION) {
6276            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6277                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6278                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6279        }
6280
6281        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6282            // We don't do this here during boot because we can do it all
6283            // at once after scanning all existing packages.
6284            //
6285            // We also do this *before* we perform dexopt on this package, so that
6286            // we can avoid redundant dexopts, and also to make sure we've got the
6287            // code and package path correct.
6288            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6289                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6290        }
6291
6292        if ((scanFlags & SCAN_NO_DEX) == 0) {
6293            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6294                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6295            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6296                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6297            }
6298        }
6299        if (mFactoryTest && pkg.requestedPermissions.contains(
6300                android.Manifest.permission.FACTORY_TEST)) {
6301            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6302        }
6303
6304        ArrayList<PackageParser.Package> clientLibPkgs = null;
6305
6306        // writer
6307        synchronized (mPackages) {
6308            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6309                // Only system apps can add new shared libraries.
6310                if (pkg.libraryNames != null) {
6311                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6312                        String name = pkg.libraryNames.get(i);
6313                        boolean allowed = false;
6314                        if (pkg.isUpdatedSystemApp()) {
6315                            // New library entries can only be added through the
6316                            // system image.  This is important to get rid of a lot
6317                            // of nasty edge cases: for example if we allowed a non-
6318                            // system update of the app to add a library, then uninstalling
6319                            // the update would make the library go away, and assumptions
6320                            // we made such as through app install filtering would now
6321                            // have allowed apps on the device which aren't compatible
6322                            // with it.  Better to just have the restriction here, be
6323                            // conservative, and create many fewer cases that can negatively
6324                            // impact the user experience.
6325                            final PackageSetting sysPs = mSettings
6326                                    .getDisabledSystemPkgLPr(pkg.packageName);
6327                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6328                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6329                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6330                                        allowed = true;
6331                                        allowed = true;
6332                                        break;
6333                                    }
6334                                }
6335                            }
6336                        } else {
6337                            allowed = true;
6338                        }
6339                        if (allowed) {
6340                            if (!mSharedLibraries.containsKey(name)) {
6341                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6342                            } else if (!name.equals(pkg.packageName)) {
6343                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6344                                        + name + " already exists; skipping");
6345                            }
6346                        } else {
6347                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6348                                    + name + " that is not declared on system image; skipping");
6349                        }
6350                    }
6351                    if ((scanFlags&SCAN_BOOTING) == 0) {
6352                        // If we are not booting, we need to update any applications
6353                        // that are clients of our shared library.  If we are booting,
6354                        // this will all be done once the scan is complete.
6355                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6356                    }
6357                }
6358            }
6359        }
6360
6361        // We also need to dexopt any apps that are dependent on this library.  Note that
6362        // if these fail, we should abort the install since installing the library will
6363        // result in some apps being broken.
6364        if (clientLibPkgs != null) {
6365            if ((scanFlags & SCAN_NO_DEX) == 0) {
6366                for (int i = 0; i < clientLibPkgs.size(); i++) {
6367                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6368                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6369                            null /* instruction sets */, forceDex,
6370                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6371                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6372                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6373                                "scanPackageLI failed to dexopt clientLibPkgs");
6374                    }
6375                }
6376            }
6377        }
6378
6379        // Request the ActivityManager to kill the process(only for existing packages)
6380        // so that we do not end up in a confused state while the user is still using the older
6381        // version of the application while the new one gets installed.
6382        if ((scanFlags & SCAN_REPLACING) != 0) {
6383            killApplication(pkg.applicationInfo.packageName,
6384                        pkg.applicationInfo.uid, "update pkg");
6385        }
6386
6387        // Also need to kill any apps that are dependent on the library.
6388        if (clientLibPkgs != null) {
6389            for (int i=0; i<clientLibPkgs.size(); i++) {
6390                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6391                killApplication(clientPkg.applicationInfo.packageName,
6392                        clientPkg.applicationInfo.uid, "update lib");
6393            }
6394        }
6395
6396        // writer
6397        synchronized (mPackages) {
6398            // We don't expect installation to fail beyond this point
6399
6400            // Add the new setting to mSettings
6401            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6402            // Add the new setting to mPackages
6403            mPackages.put(pkg.applicationInfo.packageName, pkg);
6404            // Make sure we don't accidentally delete its data.
6405            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6406            while (iter.hasNext()) {
6407                PackageCleanItem item = iter.next();
6408                if (pkgName.equals(item.packageName)) {
6409                    iter.remove();
6410                }
6411            }
6412
6413            // Take care of first install / last update times.
6414            if (currentTime != 0) {
6415                if (pkgSetting.firstInstallTime == 0) {
6416                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6417                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6418                    pkgSetting.lastUpdateTime = currentTime;
6419                }
6420            } else if (pkgSetting.firstInstallTime == 0) {
6421                // We need *something*.  Take time time stamp of the file.
6422                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6423            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6424                if (scanFileTime != pkgSetting.timeStamp) {
6425                    // A package on the system image has changed; consider this
6426                    // to be an update.
6427                    pkgSetting.lastUpdateTime = scanFileTime;
6428                }
6429            }
6430
6431            // Add the package's KeySets to the global KeySetManagerService
6432            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6433            try {
6434                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6435                if (pkg.mKeySetMapping != null) {
6436                    ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping);
6437                    if (pkg.mUpgradeKeySets != null) {
6438                        ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets);
6439                    }
6440                }
6441            } catch (NullPointerException e) {
6442                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6443            } catch (IllegalArgumentException e) {
6444                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6445            }
6446
6447            int N = pkg.providers.size();
6448            StringBuilder r = null;
6449            int i;
6450            for (i=0; i<N; i++) {
6451                PackageParser.Provider p = pkg.providers.get(i);
6452                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6453                        p.info.processName, pkg.applicationInfo.uid);
6454                mProviders.addProvider(p);
6455                p.syncable = p.info.isSyncable;
6456                if (p.info.authority != null) {
6457                    String names[] = p.info.authority.split(";");
6458                    p.info.authority = null;
6459                    for (int j = 0; j < names.length; j++) {
6460                        if (j == 1 && p.syncable) {
6461                            // We only want the first authority for a provider to possibly be
6462                            // syncable, so if we already added this provider using a different
6463                            // authority clear the syncable flag. We copy the provider before
6464                            // changing it because the mProviders object contains a reference
6465                            // to a provider that we don't want to change.
6466                            // Only do this for the second authority since the resulting provider
6467                            // object can be the same for all future authorities for this provider.
6468                            p = new PackageParser.Provider(p);
6469                            p.syncable = false;
6470                        }
6471                        if (!mProvidersByAuthority.containsKey(names[j])) {
6472                            mProvidersByAuthority.put(names[j], p);
6473                            if (p.info.authority == null) {
6474                                p.info.authority = names[j];
6475                            } else {
6476                                p.info.authority = p.info.authority + ";" + names[j];
6477                            }
6478                            if (DEBUG_PACKAGE_SCANNING) {
6479                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6480                                    Log.d(TAG, "Registered content provider: " + names[j]
6481                                            + ", className = " + p.info.name + ", isSyncable = "
6482                                            + p.info.isSyncable);
6483                            }
6484                        } else {
6485                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6486                            Slog.w(TAG, "Skipping provider name " + names[j] +
6487                                    " (in package " + pkg.applicationInfo.packageName +
6488                                    "): name already used by "
6489                                    + ((other != null && other.getComponentName() != null)
6490                                            ? other.getComponentName().getPackageName() : "?"));
6491                        }
6492                    }
6493                }
6494                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6495                    if (r == null) {
6496                        r = new StringBuilder(256);
6497                    } else {
6498                        r.append(' ');
6499                    }
6500                    r.append(p.info.name);
6501                }
6502            }
6503            if (r != null) {
6504                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6505            }
6506
6507            N = pkg.services.size();
6508            r = null;
6509            for (i=0; i<N; i++) {
6510                PackageParser.Service s = pkg.services.get(i);
6511                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6512                        s.info.processName, pkg.applicationInfo.uid);
6513                mServices.addService(s);
6514                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6515                    if (r == null) {
6516                        r = new StringBuilder(256);
6517                    } else {
6518                        r.append(' ');
6519                    }
6520                    r.append(s.info.name);
6521                }
6522            }
6523            if (r != null) {
6524                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6525            }
6526
6527            N = pkg.receivers.size();
6528            r = null;
6529            for (i=0; i<N; i++) {
6530                PackageParser.Activity a = pkg.receivers.get(i);
6531                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6532                        a.info.processName, pkg.applicationInfo.uid);
6533                mReceivers.addActivity(a, "receiver");
6534                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6535                    if (r == null) {
6536                        r = new StringBuilder(256);
6537                    } else {
6538                        r.append(' ');
6539                    }
6540                    r.append(a.info.name);
6541                }
6542            }
6543            if (r != null) {
6544                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6545            }
6546
6547            N = pkg.activities.size();
6548            r = null;
6549            for (i=0; i<N; i++) {
6550                PackageParser.Activity a = pkg.activities.get(i);
6551                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6552                        a.info.processName, pkg.applicationInfo.uid);
6553                mActivities.addActivity(a, "activity");
6554                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6555                    if (r == null) {
6556                        r = new StringBuilder(256);
6557                    } else {
6558                        r.append(' ');
6559                    }
6560                    r.append(a.info.name);
6561                }
6562            }
6563            if (r != null) {
6564                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6565            }
6566
6567            N = pkg.permissionGroups.size();
6568            r = null;
6569            for (i=0; i<N; i++) {
6570                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6571                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6572                if (cur == null) {
6573                    mPermissionGroups.put(pg.info.name, pg);
6574                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6575                        if (r == null) {
6576                            r = new StringBuilder(256);
6577                        } else {
6578                            r.append(' ');
6579                        }
6580                        r.append(pg.info.name);
6581                    }
6582                } else {
6583                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6584                            + pg.info.packageName + " ignored: original from "
6585                            + cur.info.packageName);
6586                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6587                        if (r == null) {
6588                            r = new StringBuilder(256);
6589                        } else {
6590                            r.append(' ');
6591                        }
6592                        r.append("DUP:");
6593                        r.append(pg.info.name);
6594                    }
6595                }
6596            }
6597            if (r != null) {
6598                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6599            }
6600
6601            N = pkg.permissions.size();
6602            r = null;
6603            for (i=0; i<N; i++) {
6604                PackageParser.Permission p = pkg.permissions.get(i);
6605                ArrayMap<String, BasePermission> permissionMap =
6606                        p.tree ? mSettings.mPermissionTrees
6607                        : mSettings.mPermissions;
6608                p.group = mPermissionGroups.get(p.info.group);
6609                if (p.info.group == null || p.group != null) {
6610                    BasePermission bp = permissionMap.get(p.info.name);
6611
6612                    // Allow system apps to redefine non-system permissions
6613                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6614                        final boolean currentOwnerIsSystem = (bp.perm != null
6615                                && isSystemApp(bp.perm.owner));
6616                        if (isSystemApp(p.owner)) {
6617                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6618                                // It's a built-in permission and no owner, take ownership now
6619                                bp.packageSetting = pkgSetting;
6620                                bp.perm = p;
6621                                bp.uid = pkg.applicationInfo.uid;
6622                                bp.sourcePackage = p.info.packageName;
6623                            } else if (!currentOwnerIsSystem) {
6624                                String msg = "New decl " + p.owner + " of permission  "
6625                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6626                                reportSettingsProblem(Log.WARN, msg);
6627                                bp = null;
6628                            }
6629                        }
6630                    }
6631
6632                    if (bp == null) {
6633                        bp = new BasePermission(p.info.name, p.info.packageName,
6634                                BasePermission.TYPE_NORMAL);
6635                        permissionMap.put(p.info.name, bp);
6636                    }
6637
6638                    if (bp.perm == null) {
6639                        if (bp.sourcePackage == null
6640                                || bp.sourcePackage.equals(p.info.packageName)) {
6641                            BasePermission tree = findPermissionTreeLP(p.info.name);
6642                            if (tree == null
6643                                    || tree.sourcePackage.equals(p.info.packageName)) {
6644                                bp.packageSetting = pkgSetting;
6645                                bp.perm = p;
6646                                bp.uid = pkg.applicationInfo.uid;
6647                                bp.sourcePackage = p.info.packageName;
6648                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6649                                    if (r == null) {
6650                                        r = new StringBuilder(256);
6651                                    } else {
6652                                        r.append(' ');
6653                                    }
6654                                    r.append(p.info.name);
6655                                }
6656                            } else {
6657                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6658                                        + p.info.packageName + " ignored: base tree "
6659                                        + tree.name + " is from package "
6660                                        + tree.sourcePackage);
6661                            }
6662                        } else {
6663                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6664                                    + p.info.packageName + " ignored: original from "
6665                                    + bp.sourcePackage);
6666                        }
6667                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6668                        if (r == null) {
6669                            r = new StringBuilder(256);
6670                        } else {
6671                            r.append(' ');
6672                        }
6673                        r.append("DUP:");
6674                        r.append(p.info.name);
6675                    }
6676                    if (bp.perm == p) {
6677                        bp.protectionLevel = p.info.protectionLevel;
6678                    }
6679                } else {
6680                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6681                            + p.info.packageName + " ignored: no group "
6682                            + p.group);
6683                }
6684            }
6685            if (r != null) {
6686                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6687            }
6688
6689            N = pkg.instrumentation.size();
6690            r = null;
6691            for (i=0; i<N; i++) {
6692                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6693                a.info.packageName = pkg.applicationInfo.packageName;
6694                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6695                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6696                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6697                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6698                a.info.dataDir = pkg.applicationInfo.dataDir;
6699
6700                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6701                // need other information about the application, like the ABI and what not ?
6702                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6703                mInstrumentation.put(a.getComponentName(), a);
6704                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6705                    if (r == null) {
6706                        r = new StringBuilder(256);
6707                    } else {
6708                        r.append(' ');
6709                    }
6710                    r.append(a.info.name);
6711                }
6712            }
6713            if (r != null) {
6714                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6715            }
6716
6717            if (pkg.protectedBroadcasts != null) {
6718                N = pkg.protectedBroadcasts.size();
6719                for (i=0; i<N; i++) {
6720                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6721                }
6722            }
6723
6724            pkgSetting.setTimeStamp(scanFileTime);
6725
6726            // Create idmap files for pairs of (packages, overlay packages).
6727            // Note: "android", ie framework-res.apk, is handled by native layers.
6728            if (pkg.mOverlayTarget != null) {
6729                // This is an overlay package.
6730                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6731                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6732                        mOverlays.put(pkg.mOverlayTarget,
6733                                new ArrayMap<String, PackageParser.Package>());
6734                    }
6735                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6736                    map.put(pkg.packageName, pkg);
6737                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6738                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6739                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6740                                "scanPackageLI failed to createIdmap");
6741                    }
6742                }
6743            } else if (mOverlays.containsKey(pkg.packageName) &&
6744                    !pkg.packageName.equals("android")) {
6745                // This is a regular package, with one or more known overlay packages.
6746                createIdmapsForPackageLI(pkg);
6747            }
6748        }
6749
6750        return pkg;
6751    }
6752
6753    /**
6754     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6755     * i.e, so that all packages can be run inside a single process if required.
6756     *
6757     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6758     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6759     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6760     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6761     * updating a package that belongs to a shared user.
6762     *
6763     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6764     * adds unnecessary complexity.
6765     */
6766    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6767            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6768        String requiredInstructionSet = null;
6769        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6770            requiredInstructionSet = VMRuntime.getInstructionSet(
6771                     scannedPackage.applicationInfo.primaryCpuAbi);
6772        }
6773
6774        PackageSetting requirer = null;
6775        for (PackageSetting ps : packagesForUser) {
6776            // If packagesForUser contains scannedPackage, we skip it. This will happen
6777            // when scannedPackage is an update of an existing package. Without this check,
6778            // we will never be able to change the ABI of any package belonging to a shared
6779            // user, even if it's compatible with other packages.
6780            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6781                if (ps.primaryCpuAbiString == null) {
6782                    continue;
6783                }
6784
6785                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6786                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6787                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6788                    // this but there's not much we can do.
6789                    String errorMessage = "Instruction set mismatch, "
6790                            + ((requirer == null) ? "[caller]" : requirer)
6791                            + " requires " + requiredInstructionSet + " whereas " + ps
6792                            + " requires " + instructionSet;
6793                    Slog.w(TAG, errorMessage);
6794                }
6795
6796                if (requiredInstructionSet == null) {
6797                    requiredInstructionSet = instructionSet;
6798                    requirer = ps;
6799                }
6800            }
6801        }
6802
6803        if (requiredInstructionSet != null) {
6804            String adjustedAbi;
6805            if (requirer != null) {
6806                // requirer != null implies that either scannedPackage was null or that scannedPackage
6807                // did not require an ABI, in which case we have to adjust scannedPackage to match
6808                // the ABI of the set (which is the same as requirer's ABI)
6809                adjustedAbi = requirer.primaryCpuAbiString;
6810                if (scannedPackage != null) {
6811                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6812                }
6813            } else {
6814                // requirer == null implies that we're updating all ABIs in the set to
6815                // match scannedPackage.
6816                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6817            }
6818
6819            for (PackageSetting ps : packagesForUser) {
6820                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6821                    if (ps.primaryCpuAbiString != null) {
6822                        continue;
6823                    }
6824
6825                    ps.primaryCpuAbiString = adjustedAbi;
6826                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6827                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6828                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6829
6830                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
6831                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
6832                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6833                            ps.primaryCpuAbiString = null;
6834                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6835                            return;
6836                        } else {
6837                            mInstaller.rmdex(ps.codePathString,
6838                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
6839                        }
6840                    }
6841                }
6842            }
6843        }
6844    }
6845
6846    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6847        synchronized (mPackages) {
6848            mResolverReplaced = true;
6849            // Set up information for custom user intent resolution activity.
6850            mResolveActivity.applicationInfo = pkg.applicationInfo;
6851            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6852            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6853            mResolveActivity.processName = pkg.applicationInfo.packageName;
6854            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6855            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6856                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6857            mResolveActivity.theme = 0;
6858            mResolveActivity.exported = true;
6859            mResolveActivity.enabled = true;
6860            mResolveInfo.activityInfo = mResolveActivity;
6861            mResolveInfo.priority = 0;
6862            mResolveInfo.preferredOrder = 0;
6863            mResolveInfo.match = 0;
6864            mResolveComponentName = mCustomResolverComponentName;
6865            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6866                    mResolveComponentName);
6867        }
6868    }
6869
6870    private static String calculateBundledApkRoot(final String codePathString) {
6871        final File codePath = new File(codePathString);
6872        final File codeRoot;
6873        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6874            codeRoot = Environment.getRootDirectory();
6875        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6876            codeRoot = Environment.getOemDirectory();
6877        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6878            codeRoot = Environment.getVendorDirectory();
6879        } else {
6880            // Unrecognized code path; take its top real segment as the apk root:
6881            // e.g. /something/app/blah.apk => /something
6882            try {
6883                File f = codePath.getCanonicalFile();
6884                File parent = f.getParentFile();    // non-null because codePath is a file
6885                File tmp;
6886                while ((tmp = parent.getParentFile()) != null) {
6887                    f = parent;
6888                    parent = tmp;
6889                }
6890                codeRoot = f;
6891                Slog.w(TAG, "Unrecognized code path "
6892                        + codePath + " - using " + codeRoot);
6893            } catch (IOException e) {
6894                // Can't canonicalize the code path -- shenanigans?
6895                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6896                return Environment.getRootDirectory().getPath();
6897            }
6898        }
6899        return codeRoot.getPath();
6900    }
6901
6902    /**
6903     * Derive and set the location of native libraries for the given package,
6904     * which varies depending on where and how the package was installed.
6905     */
6906    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6907        final ApplicationInfo info = pkg.applicationInfo;
6908        final String codePath = pkg.codePath;
6909        final File codeFile = new File(codePath);
6910        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
6911        final boolean asecApp = info.isForwardLocked() || isExternal(info);
6912
6913        info.nativeLibraryRootDir = null;
6914        info.nativeLibraryRootRequiresIsa = false;
6915        info.nativeLibraryDir = null;
6916        info.secondaryNativeLibraryDir = null;
6917
6918        if (isApkFile(codeFile)) {
6919            // Monolithic install
6920            if (bundledApp) {
6921                // If "/system/lib64/apkname" exists, assume that is the per-package
6922                // native library directory to use; otherwise use "/system/lib/apkname".
6923                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6924                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6925                        getPrimaryInstructionSet(info));
6926
6927                // This is a bundled system app so choose the path based on the ABI.
6928                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6929                // is just the default path.
6930                final String apkName = deriveCodePathName(codePath);
6931                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6932                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6933                        apkName).getAbsolutePath();
6934
6935                if (info.secondaryCpuAbi != null) {
6936                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6937                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6938                            secondaryLibDir, apkName).getAbsolutePath();
6939                }
6940            } else if (asecApp) {
6941                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6942                        .getAbsolutePath();
6943            } else {
6944                final String apkName = deriveCodePathName(codePath);
6945                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6946                        .getAbsolutePath();
6947            }
6948
6949            info.nativeLibraryRootRequiresIsa = false;
6950            info.nativeLibraryDir = info.nativeLibraryRootDir;
6951        } else {
6952            // Cluster install
6953            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6954            info.nativeLibraryRootRequiresIsa = true;
6955
6956            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6957                    getPrimaryInstructionSet(info)).getAbsolutePath();
6958
6959            if (info.secondaryCpuAbi != null) {
6960                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6961                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6962            }
6963        }
6964    }
6965
6966    /**
6967     * Calculate the abis and roots for a bundled app. These can uniquely
6968     * be determined from the contents of the system partition, i.e whether
6969     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6970     * of this information, and instead assume that the system was built
6971     * sensibly.
6972     */
6973    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6974                                           PackageSetting pkgSetting) {
6975        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6976
6977        // If "/system/lib64/apkname" exists, assume that is the per-package
6978        // native library directory to use; otherwise use "/system/lib/apkname".
6979        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6980        setBundledAppAbi(pkg, apkRoot, apkName);
6981        // pkgSetting might be null during rescan following uninstall of updates
6982        // to a bundled app, so accommodate that possibility.  The settings in
6983        // that case will be established later from the parsed package.
6984        //
6985        // If the settings aren't null, sync them up with what we've just derived.
6986        // note that apkRoot isn't stored in the package settings.
6987        if (pkgSetting != null) {
6988            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6989            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6990        }
6991    }
6992
6993    /**
6994     * Deduces the ABI of a bundled app and sets the relevant fields on the
6995     * parsed pkg object.
6996     *
6997     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6998     *        under which system libraries are installed.
6999     * @param apkName the name of the installed package.
7000     */
7001    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7002        final File codeFile = new File(pkg.codePath);
7003
7004        final boolean has64BitLibs;
7005        final boolean has32BitLibs;
7006        if (isApkFile(codeFile)) {
7007            // Monolithic install
7008            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7009            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7010        } else {
7011            // Cluster install
7012            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7013            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7014                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7015                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7016                has64BitLibs = (new File(rootDir, isa)).exists();
7017            } else {
7018                has64BitLibs = false;
7019            }
7020            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7021                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7022                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7023                has32BitLibs = (new File(rootDir, isa)).exists();
7024            } else {
7025                has32BitLibs = false;
7026            }
7027        }
7028
7029        if (has64BitLibs && !has32BitLibs) {
7030            // The package has 64 bit libs, but not 32 bit libs. Its primary
7031            // ABI should be 64 bit. We can safely assume here that the bundled
7032            // native libraries correspond to the most preferred ABI in the list.
7033
7034            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7035            pkg.applicationInfo.secondaryCpuAbi = null;
7036        } else if (has32BitLibs && !has64BitLibs) {
7037            // The package has 32 bit libs but not 64 bit libs. Its primary
7038            // ABI should be 32 bit.
7039
7040            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7041            pkg.applicationInfo.secondaryCpuAbi = null;
7042        } else if (has32BitLibs && has64BitLibs) {
7043            // The application has both 64 and 32 bit bundled libraries. We check
7044            // here that the app declares multiArch support, and warn if it doesn't.
7045            //
7046            // We will be lenient here and record both ABIs. The primary will be the
7047            // ABI that's higher on the list, i.e, a device that's configured to prefer
7048            // 64 bit apps will see a 64 bit primary ABI,
7049
7050            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7051                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7052            }
7053
7054            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7055                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7056                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7057            } else {
7058                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7059                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7060            }
7061        } else {
7062            pkg.applicationInfo.primaryCpuAbi = null;
7063            pkg.applicationInfo.secondaryCpuAbi = null;
7064        }
7065    }
7066
7067    private void killApplication(String pkgName, int appId, String reason) {
7068        // Request the ActivityManager to kill the process(only for existing packages)
7069        // so that we do not end up in a confused state while the user is still using the older
7070        // version of the application while the new one gets installed.
7071        IActivityManager am = ActivityManagerNative.getDefault();
7072        if (am != null) {
7073            try {
7074                am.killApplicationWithAppId(pkgName, appId, reason);
7075            } catch (RemoteException e) {
7076            }
7077        }
7078    }
7079
7080    void removePackageLI(PackageSetting ps, boolean chatty) {
7081        if (DEBUG_INSTALL) {
7082            if (chatty)
7083                Log.d(TAG, "Removing package " + ps.name);
7084        }
7085
7086        // writer
7087        synchronized (mPackages) {
7088            mPackages.remove(ps.name);
7089            final PackageParser.Package pkg = ps.pkg;
7090            if (pkg != null) {
7091                cleanPackageDataStructuresLILPw(pkg, chatty);
7092            }
7093        }
7094    }
7095
7096    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7097        if (DEBUG_INSTALL) {
7098            if (chatty)
7099                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7100        }
7101
7102        // writer
7103        synchronized (mPackages) {
7104            mPackages.remove(pkg.applicationInfo.packageName);
7105            cleanPackageDataStructuresLILPw(pkg, chatty);
7106        }
7107    }
7108
7109    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7110        int N = pkg.providers.size();
7111        StringBuilder r = null;
7112        int i;
7113        for (i=0; i<N; i++) {
7114            PackageParser.Provider p = pkg.providers.get(i);
7115            mProviders.removeProvider(p);
7116            if (p.info.authority == null) {
7117
7118                /* There was another ContentProvider with this authority when
7119                 * this app was installed so this authority is null,
7120                 * Ignore it as we don't have to unregister the provider.
7121                 */
7122                continue;
7123            }
7124            String names[] = p.info.authority.split(";");
7125            for (int j = 0; j < names.length; j++) {
7126                if (mProvidersByAuthority.get(names[j]) == p) {
7127                    mProvidersByAuthority.remove(names[j]);
7128                    if (DEBUG_REMOVE) {
7129                        if (chatty)
7130                            Log.d(TAG, "Unregistered content provider: " + names[j]
7131                                    + ", className = " + p.info.name + ", isSyncable = "
7132                                    + p.info.isSyncable);
7133                    }
7134                }
7135            }
7136            if (DEBUG_REMOVE && chatty) {
7137                if (r == null) {
7138                    r = new StringBuilder(256);
7139                } else {
7140                    r.append(' ');
7141                }
7142                r.append(p.info.name);
7143            }
7144        }
7145        if (r != null) {
7146            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7147        }
7148
7149        N = pkg.services.size();
7150        r = null;
7151        for (i=0; i<N; i++) {
7152            PackageParser.Service s = pkg.services.get(i);
7153            mServices.removeService(s);
7154            if (chatty) {
7155                if (r == null) {
7156                    r = new StringBuilder(256);
7157                } else {
7158                    r.append(' ');
7159                }
7160                r.append(s.info.name);
7161            }
7162        }
7163        if (r != null) {
7164            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7165        }
7166
7167        N = pkg.receivers.size();
7168        r = null;
7169        for (i=0; i<N; i++) {
7170            PackageParser.Activity a = pkg.receivers.get(i);
7171            mReceivers.removeActivity(a, "receiver");
7172            if (DEBUG_REMOVE && chatty) {
7173                if (r == null) {
7174                    r = new StringBuilder(256);
7175                } else {
7176                    r.append(' ');
7177                }
7178                r.append(a.info.name);
7179            }
7180        }
7181        if (r != null) {
7182            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7183        }
7184
7185        N = pkg.activities.size();
7186        r = null;
7187        for (i=0; i<N; i++) {
7188            PackageParser.Activity a = pkg.activities.get(i);
7189            mActivities.removeActivity(a, "activity");
7190            if (DEBUG_REMOVE && chatty) {
7191                if (r == null) {
7192                    r = new StringBuilder(256);
7193                } else {
7194                    r.append(' ');
7195                }
7196                r.append(a.info.name);
7197            }
7198        }
7199        if (r != null) {
7200            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7201        }
7202
7203        N = pkg.permissions.size();
7204        r = null;
7205        for (i=0; i<N; i++) {
7206            PackageParser.Permission p = pkg.permissions.get(i);
7207            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7208            if (bp == null) {
7209                bp = mSettings.mPermissionTrees.get(p.info.name);
7210            }
7211            if (bp != null && bp.perm == p) {
7212                bp.perm = null;
7213                if (DEBUG_REMOVE && chatty) {
7214                    if (r == null) {
7215                        r = new StringBuilder(256);
7216                    } else {
7217                        r.append(' ');
7218                    }
7219                    r.append(p.info.name);
7220                }
7221            }
7222            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7223                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7224                if (appOpPerms != null) {
7225                    appOpPerms.remove(pkg.packageName);
7226                }
7227            }
7228        }
7229        if (r != null) {
7230            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7231        }
7232
7233        N = pkg.requestedPermissions.size();
7234        r = null;
7235        for (i=0; i<N; i++) {
7236            String perm = pkg.requestedPermissions.get(i);
7237            BasePermission bp = mSettings.mPermissions.get(perm);
7238            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7239                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7240                if (appOpPerms != null) {
7241                    appOpPerms.remove(pkg.packageName);
7242                    if (appOpPerms.isEmpty()) {
7243                        mAppOpPermissionPackages.remove(perm);
7244                    }
7245                }
7246            }
7247        }
7248        if (r != null) {
7249            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7250        }
7251
7252        N = pkg.instrumentation.size();
7253        r = null;
7254        for (i=0; i<N; i++) {
7255            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7256            mInstrumentation.remove(a.getComponentName());
7257            if (DEBUG_REMOVE && chatty) {
7258                if (r == null) {
7259                    r = new StringBuilder(256);
7260                } else {
7261                    r.append(' ');
7262                }
7263                r.append(a.info.name);
7264            }
7265        }
7266        if (r != null) {
7267            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7268        }
7269
7270        r = null;
7271        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7272            // Only system apps can hold shared libraries.
7273            if (pkg.libraryNames != null) {
7274                for (i=0; i<pkg.libraryNames.size(); i++) {
7275                    String name = pkg.libraryNames.get(i);
7276                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7277                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7278                        mSharedLibraries.remove(name);
7279                        if (DEBUG_REMOVE && chatty) {
7280                            if (r == null) {
7281                                r = new StringBuilder(256);
7282                            } else {
7283                                r.append(' ');
7284                            }
7285                            r.append(name);
7286                        }
7287                    }
7288                }
7289            }
7290        }
7291        if (r != null) {
7292            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7293        }
7294    }
7295
7296    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7297        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7298            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7299                return true;
7300            }
7301        }
7302        return false;
7303    }
7304
7305    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7306    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7307    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7308
7309    private void updatePermissionsLPw(String changingPkg,
7310            PackageParser.Package pkgInfo, int flags) {
7311        // Make sure there are no dangling permission trees.
7312        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7313        while (it.hasNext()) {
7314            final BasePermission bp = it.next();
7315            if (bp.packageSetting == null) {
7316                // We may not yet have parsed the package, so just see if
7317                // we still know about its settings.
7318                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7319            }
7320            if (bp.packageSetting == null) {
7321                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7322                        + " from package " + bp.sourcePackage);
7323                it.remove();
7324            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7325                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7326                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7327                            + " from package " + bp.sourcePackage);
7328                    flags |= UPDATE_PERMISSIONS_ALL;
7329                    it.remove();
7330                }
7331            }
7332        }
7333
7334        // Make sure all dynamic permissions have been assigned to a package,
7335        // and make sure there are no dangling permissions.
7336        it = mSettings.mPermissions.values().iterator();
7337        while (it.hasNext()) {
7338            final BasePermission bp = it.next();
7339            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7340                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7341                        + bp.name + " pkg=" + bp.sourcePackage
7342                        + " info=" + bp.pendingInfo);
7343                if (bp.packageSetting == null && bp.pendingInfo != null) {
7344                    final BasePermission tree = findPermissionTreeLP(bp.name);
7345                    if (tree != null && tree.perm != null) {
7346                        bp.packageSetting = tree.packageSetting;
7347                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7348                                new PermissionInfo(bp.pendingInfo));
7349                        bp.perm.info.packageName = tree.perm.info.packageName;
7350                        bp.perm.info.name = bp.name;
7351                        bp.uid = tree.uid;
7352                    }
7353                }
7354            }
7355            if (bp.packageSetting == null) {
7356                // We may not yet have parsed the package, so just see if
7357                // we still know about its settings.
7358                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7359            }
7360            if (bp.packageSetting == null) {
7361                Slog.w(TAG, "Removing dangling permission: " + bp.name
7362                        + " from package " + bp.sourcePackage);
7363                it.remove();
7364            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7365                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7366                    Slog.i(TAG, "Removing old permission: " + bp.name
7367                            + " from package " + bp.sourcePackage);
7368                    flags |= UPDATE_PERMISSIONS_ALL;
7369                    it.remove();
7370                }
7371            }
7372        }
7373
7374        // Now update the permissions for all packages, in particular
7375        // replace the granted permissions of the system packages.
7376        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7377            for (PackageParser.Package pkg : mPackages.values()) {
7378                if (pkg != pkgInfo) {
7379                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7380                            changingPkg);
7381                }
7382            }
7383        }
7384
7385        if (pkgInfo != null) {
7386            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7387        }
7388    }
7389
7390    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7391            String packageOfInterest) {
7392        // IMPORTANT: There are two types of permissions: install and runtime.
7393        // Install time permissions are granted when the app is installed to
7394        // all device users and users added in the future. Runtime permissions
7395        // are granted at runtime explicitly to specific users. Normal and signature
7396        // protected permissions are install time permissions. Dangerous permissions
7397        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7398        // otherwise they are runtime permissions. This function does not manage
7399        // runtime permissions except for the case an app targeting Lollipop MR1
7400        // being upgraded to target a newer SDK, in which case dangerous permissions
7401        // are transformed from install time to runtime ones.
7402
7403        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7404        if (ps == null) {
7405            return;
7406        }
7407
7408        PermissionsState permissionsState = ps.getPermissionsState();
7409        PermissionsState origPermissions = permissionsState;
7410
7411        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7412
7413        int[] upgradeUserIds = PermissionsState.USERS_NONE;
7414        int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE;
7415
7416        boolean changedInstallPermission = false;
7417
7418        if (replace) {
7419            ps.installPermissionsFixed = false;
7420            if (!ps.isSharedUser()) {
7421                origPermissions = new PermissionsState(permissionsState);
7422                permissionsState.reset();
7423            }
7424        }
7425
7426        permissionsState.setGlobalGids(mGlobalGids);
7427
7428        final int N = pkg.requestedPermissions.size();
7429        for (int i=0; i<N; i++) {
7430            final String name = pkg.requestedPermissions.get(i);
7431            final BasePermission bp = mSettings.mPermissions.get(name);
7432
7433            if (DEBUG_INSTALL) {
7434                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7435            }
7436
7437            if (bp == null || bp.packageSetting == null) {
7438                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7439                    Slog.w(TAG, "Unknown permission " + name
7440                            + " in package " + pkg.packageName);
7441                }
7442                continue;
7443            }
7444
7445            final String perm = bp.name;
7446            boolean allowedSig = false;
7447            int grant = GRANT_DENIED;
7448
7449            // Keep track of app op permissions.
7450            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7451                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7452                if (pkgs == null) {
7453                    pkgs = new ArraySet<>();
7454                    mAppOpPermissionPackages.put(bp.name, pkgs);
7455                }
7456                pkgs.add(pkg.packageName);
7457            }
7458
7459            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7460            switch (level) {
7461                case PermissionInfo.PROTECTION_NORMAL: {
7462                    // For all apps normal permissions are install time ones.
7463                    grant = GRANT_INSTALL;
7464                } break;
7465
7466                case PermissionInfo.PROTECTION_DANGEROUS: {
7467                    if (!RUNTIME_PERMISSIONS_ENABLED
7468                            || pkg.applicationInfo.targetSdkVersion
7469                                    <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7470                        // For legacy apps dangerous permissions are install time ones.
7471                        grant = GRANT_INSTALL;
7472                    } else if (ps.isSystem()) {
7473                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7474                        if (origPermissions.hasInstallPermission(bp.name)) {
7475                            // If a system app had an install permission, then the app was
7476                            // upgraded and we grant the permissions as runtime to all users.
7477                            grant = GRANT_UPGRADE;
7478                            upgradeUserIds = currentUserIds;
7479                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7480                            // If users changed since the last permissions update for a
7481                            // system app, we grant the permission as runtime to the new users.
7482                            grant = GRANT_UPGRADE;
7483                            upgradeUserIds = currentUserIds;
7484                            for (int userId : updatedUserIds) {
7485                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7486                            }
7487                        } else {
7488                            // Otherwise, we grant the permission as runtime if the app
7489                            // already had it, i.e. we preserve runtime permissions.
7490                            grant = GRANT_RUNTIME;
7491                        }
7492                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7493                        // For legacy apps that became modern, install becomes runtime.
7494                        grant = GRANT_UPGRADE;
7495                        upgradeUserIds = currentUserIds;
7496                    } else if (replace) {
7497                        // For upgraded modern apps keep runtime permissions unchanged.
7498                        grant = GRANT_RUNTIME;
7499                    }
7500                } break;
7501
7502                case PermissionInfo.PROTECTION_SIGNATURE: {
7503                    // For all apps signature permissions are install time ones.
7504                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7505                    if (allowedSig) {
7506                        grant = GRANT_INSTALL;
7507                    }
7508                } break;
7509            }
7510
7511            if (DEBUG_INSTALL) {
7512                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7513            }
7514
7515            if (grant != GRANT_DENIED) {
7516                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7517                    // If this is an existing, non-system package, then
7518                    // we can't add any new permissions to it.
7519                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7520                        // Except...  if this is a permission that was added
7521                        // to the platform (note: need to only do this when
7522                        // updating the platform).
7523                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7524                            grant = GRANT_DENIED;
7525                        }
7526                    }
7527                }
7528
7529                switch (grant) {
7530                    case GRANT_INSTALL: {
7531                        // Grant an install permission.
7532                        if (permissionsState.grantInstallPermission(bp) !=
7533                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7534                            changedInstallPermission = true;
7535                        }
7536                    } break;
7537
7538                    case GRANT_RUNTIME: {
7539                        // Grant previously granted runtime permissions.
7540                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7541                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7542                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7543                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7544                                    // If we cannot put the permission as it was, we have to write.
7545                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7546                                            changedRuntimePermissionUserIds, userId);
7547                                }
7548                            }
7549                        }
7550                    } break;
7551
7552                    case GRANT_UPGRADE: {
7553                        // Grant runtime permissions for a previously held install permission.
7554                        permissionsState.revokeInstallPermission(bp);
7555                        for (int userId : upgradeUserIds) {
7556                            if (permissionsState.grantRuntimePermission(bp, userId) !=
7557                                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
7558                                // If we granted the permission, we have to write.
7559                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7560                                        changedRuntimePermissionUserIds, userId);
7561                            }
7562                        }
7563                    } break;
7564
7565                    default: {
7566                        if (packageOfInterest == null
7567                                || packageOfInterest.equals(pkg.packageName)) {
7568                            Slog.w(TAG, "Not granting permission " + perm
7569                                    + " to package " + pkg.packageName
7570                                    + " because it was previously installed without");
7571                        }
7572                    } break;
7573                }
7574            } else {
7575                if (permissionsState.revokeInstallPermission(bp) !=
7576                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7577                    changedInstallPermission = true;
7578                    Slog.i(TAG, "Un-granting permission " + perm
7579                            + " from package " + pkg.packageName
7580                            + " (protectionLevel=" + bp.protectionLevel
7581                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7582                            + ")");
7583                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7584                    // Don't print warning for app op permissions, since it is fine for them
7585                    // not to be granted, there is a UI for the user to decide.
7586                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7587                        Slog.w(TAG, "Not granting permission " + perm
7588                                + " to package " + pkg.packageName
7589                                + " (protectionLevel=" + bp.protectionLevel
7590                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7591                                + ")");
7592                    }
7593                }
7594            }
7595        }
7596
7597        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7598                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7599            // This is the first that we have heard about this package, so the
7600            // permissions we have now selected are fixed until explicitly
7601            // changed.
7602            ps.installPermissionsFixed = true;
7603        }
7604
7605        ps.setPermissionsUpdatedForUserIds(currentUserIds);
7606
7607        // Persist the runtime permissions state for users with changes.
7608        if (RUNTIME_PERMISSIONS_ENABLED) {
7609            for (int userId : changedRuntimePermissionUserIds) {
7610                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
7611            }
7612        }
7613    }
7614
7615    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7616        boolean allowed = false;
7617        final int NP = PackageParser.NEW_PERMISSIONS.length;
7618        for (int ip=0; ip<NP; ip++) {
7619            final PackageParser.NewPermissionInfo npi
7620                    = PackageParser.NEW_PERMISSIONS[ip];
7621            if (npi.name.equals(perm)
7622                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7623                allowed = true;
7624                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7625                        + pkg.packageName);
7626                break;
7627            }
7628        }
7629        return allowed;
7630    }
7631
7632    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7633            BasePermission bp, PermissionsState origPermissions) {
7634        boolean allowed;
7635        allowed = (compareSignatures(
7636                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7637                        == PackageManager.SIGNATURE_MATCH)
7638                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7639                        == PackageManager.SIGNATURE_MATCH);
7640        if (!allowed && (bp.protectionLevel
7641                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7642            if (isSystemApp(pkg)) {
7643                // For updated system applications, a system permission
7644                // is granted only if it had been defined by the original application.
7645                if (pkg.isUpdatedSystemApp()) {
7646                    final PackageSetting sysPs = mSettings
7647                            .getDisabledSystemPkgLPr(pkg.packageName);
7648                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
7649                        // If the original was granted this permission, we take
7650                        // that grant decision as read and propagate it to the
7651                        // update.
7652                        if (sysPs.isPrivileged()) {
7653                            allowed = true;
7654                        }
7655                    } else {
7656                        // The system apk may have been updated with an older
7657                        // version of the one on the data partition, but which
7658                        // granted a new system permission that it didn't have
7659                        // before.  In this case we do want to allow the app to
7660                        // now get the new permission if the ancestral apk is
7661                        // privileged to get it.
7662                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7663                            for (int j=0;
7664                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7665                                if (perm.equals(
7666                                        sysPs.pkg.requestedPermissions.get(j))) {
7667                                    allowed = true;
7668                                    break;
7669                                }
7670                            }
7671                        }
7672                    }
7673                } else {
7674                    allowed = isPrivilegedApp(pkg);
7675                }
7676            }
7677        }
7678        if (!allowed && (bp.protectionLevel
7679                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7680            // For development permissions, a development permission
7681            // is granted only if it was already granted.
7682            allowed = origPermissions.hasInstallPermission(perm);
7683        }
7684        return allowed;
7685    }
7686
7687    final class ActivityIntentResolver
7688            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7689        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7690                boolean defaultOnly, int userId) {
7691            if (!sUserManager.exists(userId)) return null;
7692            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7693            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7694        }
7695
7696        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7697                int userId) {
7698            if (!sUserManager.exists(userId)) return null;
7699            mFlags = flags;
7700            return super.queryIntent(intent, resolvedType,
7701                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7702        }
7703
7704        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7705                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7706            if (!sUserManager.exists(userId)) return null;
7707            if (packageActivities == null) {
7708                return null;
7709            }
7710            mFlags = flags;
7711            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7712            final int N = packageActivities.size();
7713            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7714                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7715
7716            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7717            for (int i = 0; i < N; ++i) {
7718                intentFilters = packageActivities.get(i).intents;
7719                if (intentFilters != null && intentFilters.size() > 0) {
7720                    PackageParser.ActivityIntentInfo[] array =
7721                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7722                    intentFilters.toArray(array);
7723                    listCut.add(array);
7724                }
7725            }
7726            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7727        }
7728
7729        public final void addActivity(PackageParser.Activity a, String type) {
7730            final boolean systemApp = a.info.applicationInfo.isSystemApp();
7731            mActivities.put(a.getComponentName(), a);
7732            if (DEBUG_SHOW_INFO)
7733                Log.v(
7734                TAG, "  " + type + " " +
7735                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7736            if (DEBUG_SHOW_INFO)
7737                Log.v(TAG, "    Class=" + a.info.name);
7738            final int NI = a.intents.size();
7739            for (int j=0; j<NI; j++) {
7740                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7741                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7742                    intent.setPriority(0);
7743                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7744                            + a.className + " with priority > 0, forcing to 0");
7745                }
7746                if (DEBUG_SHOW_INFO) {
7747                    Log.v(TAG, "    IntentFilter:");
7748                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7749                }
7750                if (!intent.debugCheck()) {
7751                    Log.w(TAG, "==> For Activity " + a.info.name);
7752                }
7753                addFilter(intent);
7754            }
7755        }
7756
7757        public final void removeActivity(PackageParser.Activity a, String type) {
7758            mActivities.remove(a.getComponentName());
7759            if (DEBUG_SHOW_INFO) {
7760                Log.v(TAG, "  " + type + " "
7761                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7762                                : a.info.name) + ":");
7763                Log.v(TAG, "    Class=" + a.info.name);
7764            }
7765            final int NI = a.intents.size();
7766            for (int j=0; j<NI; j++) {
7767                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7768                if (DEBUG_SHOW_INFO) {
7769                    Log.v(TAG, "    IntentFilter:");
7770                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7771                }
7772                removeFilter(intent);
7773            }
7774        }
7775
7776        @Override
7777        protected boolean allowFilterResult(
7778                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7779            ActivityInfo filterAi = filter.activity.info;
7780            for (int i=dest.size()-1; i>=0; i--) {
7781                ActivityInfo destAi = dest.get(i).activityInfo;
7782                if (destAi.name == filterAi.name
7783                        && destAi.packageName == filterAi.packageName) {
7784                    return false;
7785                }
7786            }
7787            return true;
7788        }
7789
7790        @Override
7791        protected ActivityIntentInfo[] newArray(int size) {
7792            return new ActivityIntentInfo[size];
7793        }
7794
7795        @Override
7796        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7797            if (!sUserManager.exists(userId)) return true;
7798            PackageParser.Package p = filter.activity.owner;
7799            if (p != null) {
7800                PackageSetting ps = (PackageSetting)p.mExtras;
7801                if (ps != null) {
7802                    // System apps are never considered stopped for purposes of
7803                    // filtering, because there may be no way for the user to
7804                    // actually re-launch them.
7805                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7806                            && ps.getStopped(userId);
7807                }
7808            }
7809            return false;
7810        }
7811
7812        @Override
7813        protected boolean isPackageForFilter(String packageName,
7814                PackageParser.ActivityIntentInfo info) {
7815            return packageName.equals(info.activity.owner.packageName);
7816        }
7817
7818        @Override
7819        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7820                int match, int userId) {
7821            if (!sUserManager.exists(userId)) return null;
7822            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7823                return null;
7824            }
7825            final PackageParser.Activity activity = info.activity;
7826            if (mSafeMode && (activity.info.applicationInfo.flags
7827                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7828                return null;
7829            }
7830            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7831            if (ps == null) {
7832                return null;
7833            }
7834            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7835                    ps.readUserState(userId), userId);
7836            if (ai == null) {
7837                return null;
7838            }
7839            final ResolveInfo res = new ResolveInfo();
7840            res.activityInfo = ai;
7841            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7842                res.filter = info;
7843            }
7844            if (info != null) {
7845                res.filterNeedsVerification = info.needsVerification();
7846            }
7847            res.priority = info.getPriority();
7848            res.preferredOrder = activity.owner.mPreferredOrder;
7849            //System.out.println("Result: " + res.activityInfo.className +
7850            //                   " = " + res.priority);
7851            res.match = match;
7852            res.isDefault = info.hasDefault;
7853            res.labelRes = info.labelRes;
7854            res.nonLocalizedLabel = info.nonLocalizedLabel;
7855            if (userNeedsBadging(userId)) {
7856                res.noResourceId = true;
7857            } else {
7858                res.icon = info.icon;
7859            }
7860            res.system = res.activityInfo.applicationInfo.isSystemApp();
7861            return res;
7862        }
7863
7864        @Override
7865        protected void sortResults(List<ResolveInfo> results) {
7866            Collections.sort(results, mResolvePrioritySorter);
7867        }
7868
7869        @Override
7870        protected void dumpFilter(PrintWriter out, String prefix,
7871                PackageParser.ActivityIntentInfo filter) {
7872            out.print(prefix); out.print(
7873                    Integer.toHexString(System.identityHashCode(filter.activity)));
7874                    out.print(' ');
7875                    filter.activity.printComponentShortName(out);
7876                    out.print(" filter ");
7877                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7878        }
7879
7880        @Override
7881        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
7882            return filter.activity;
7883        }
7884
7885        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7886            PackageParser.Activity activity = (PackageParser.Activity)label;
7887            out.print(prefix); out.print(
7888                    Integer.toHexString(System.identityHashCode(activity)));
7889                    out.print(' ');
7890                    activity.printComponentShortName(out);
7891            if (count > 1) {
7892                out.print(" ("); out.print(count); out.print(" filters)");
7893            }
7894            out.println();
7895        }
7896
7897//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7898//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7899//            final List<ResolveInfo> retList = Lists.newArrayList();
7900//            while (i.hasNext()) {
7901//                final ResolveInfo resolveInfo = i.next();
7902//                if (isEnabledLP(resolveInfo.activityInfo)) {
7903//                    retList.add(resolveInfo);
7904//                }
7905//            }
7906//            return retList;
7907//        }
7908
7909        // Keys are String (activity class name), values are Activity.
7910        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
7911                = new ArrayMap<ComponentName, PackageParser.Activity>();
7912        private int mFlags;
7913    }
7914
7915    private final class ServiceIntentResolver
7916            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7917        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7918                boolean defaultOnly, int userId) {
7919            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7920            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7921        }
7922
7923        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7924                int userId) {
7925            if (!sUserManager.exists(userId)) return null;
7926            mFlags = flags;
7927            return super.queryIntent(intent, resolvedType,
7928                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7929        }
7930
7931        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7932                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7933            if (!sUserManager.exists(userId)) return null;
7934            if (packageServices == null) {
7935                return null;
7936            }
7937            mFlags = flags;
7938            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7939            final int N = packageServices.size();
7940            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7941                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7942
7943            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7944            for (int i = 0; i < N; ++i) {
7945                intentFilters = packageServices.get(i).intents;
7946                if (intentFilters != null && intentFilters.size() > 0) {
7947                    PackageParser.ServiceIntentInfo[] array =
7948                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7949                    intentFilters.toArray(array);
7950                    listCut.add(array);
7951                }
7952            }
7953            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7954        }
7955
7956        public final void addService(PackageParser.Service s) {
7957            mServices.put(s.getComponentName(), s);
7958            if (DEBUG_SHOW_INFO) {
7959                Log.v(TAG, "  "
7960                        + (s.info.nonLocalizedLabel != null
7961                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7962                Log.v(TAG, "    Class=" + s.info.name);
7963            }
7964            final int NI = s.intents.size();
7965            int j;
7966            for (j=0; j<NI; j++) {
7967                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7968                if (DEBUG_SHOW_INFO) {
7969                    Log.v(TAG, "    IntentFilter:");
7970                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7971                }
7972                if (!intent.debugCheck()) {
7973                    Log.w(TAG, "==> For Service " + s.info.name);
7974                }
7975                addFilter(intent);
7976            }
7977        }
7978
7979        public final void removeService(PackageParser.Service s) {
7980            mServices.remove(s.getComponentName());
7981            if (DEBUG_SHOW_INFO) {
7982                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7983                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7984                Log.v(TAG, "    Class=" + s.info.name);
7985            }
7986            final int NI = s.intents.size();
7987            int j;
7988            for (j=0; j<NI; j++) {
7989                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7990                if (DEBUG_SHOW_INFO) {
7991                    Log.v(TAG, "    IntentFilter:");
7992                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7993                }
7994                removeFilter(intent);
7995            }
7996        }
7997
7998        @Override
7999        protected boolean allowFilterResult(
8000                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8001            ServiceInfo filterSi = filter.service.info;
8002            for (int i=dest.size()-1; i>=0; i--) {
8003                ServiceInfo destAi = dest.get(i).serviceInfo;
8004                if (destAi.name == filterSi.name
8005                        && destAi.packageName == filterSi.packageName) {
8006                    return false;
8007                }
8008            }
8009            return true;
8010        }
8011
8012        @Override
8013        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8014            return new PackageParser.ServiceIntentInfo[size];
8015        }
8016
8017        @Override
8018        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8019            if (!sUserManager.exists(userId)) return true;
8020            PackageParser.Package p = filter.service.owner;
8021            if (p != null) {
8022                PackageSetting ps = (PackageSetting)p.mExtras;
8023                if (ps != null) {
8024                    // System apps are never considered stopped for purposes of
8025                    // filtering, because there may be no way for the user to
8026                    // actually re-launch them.
8027                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8028                            && ps.getStopped(userId);
8029                }
8030            }
8031            return false;
8032        }
8033
8034        @Override
8035        protected boolean isPackageForFilter(String packageName,
8036                PackageParser.ServiceIntentInfo info) {
8037            return packageName.equals(info.service.owner.packageName);
8038        }
8039
8040        @Override
8041        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8042                int match, int userId) {
8043            if (!sUserManager.exists(userId)) return null;
8044            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8045            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8046                return null;
8047            }
8048            final PackageParser.Service service = info.service;
8049            if (mSafeMode && (service.info.applicationInfo.flags
8050                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8051                return null;
8052            }
8053            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8054            if (ps == null) {
8055                return null;
8056            }
8057            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8058                    ps.readUserState(userId), userId);
8059            if (si == null) {
8060                return null;
8061            }
8062            final ResolveInfo res = new ResolveInfo();
8063            res.serviceInfo = si;
8064            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8065                res.filter = filter;
8066            }
8067            res.priority = info.getPriority();
8068            res.preferredOrder = service.owner.mPreferredOrder;
8069            res.match = match;
8070            res.isDefault = info.hasDefault;
8071            res.labelRes = info.labelRes;
8072            res.nonLocalizedLabel = info.nonLocalizedLabel;
8073            res.icon = info.icon;
8074            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8075            return res;
8076        }
8077
8078        @Override
8079        protected void sortResults(List<ResolveInfo> results) {
8080            Collections.sort(results, mResolvePrioritySorter);
8081        }
8082
8083        @Override
8084        protected void dumpFilter(PrintWriter out, String prefix,
8085                PackageParser.ServiceIntentInfo filter) {
8086            out.print(prefix); out.print(
8087                    Integer.toHexString(System.identityHashCode(filter.service)));
8088                    out.print(' ');
8089                    filter.service.printComponentShortName(out);
8090                    out.print(" filter ");
8091                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8092        }
8093
8094        @Override
8095        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8096            return filter.service;
8097        }
8098
8099        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8100            PackageParser.Service service = (PackageParser.Service)label;
8101            out.print(prefix); out.print(
8102                    Integer.toHexString(System.identityHashCode(service)));
8103                    out.print(' ');
8104                    service.printComponentShortName(out);
8105            if (count > 1) {
8106                out.print(" ("); out.print(count); out.print(" filters)");
8107            }
8108            out.println();
8109        }
8110
8111//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8112//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8113//            final List<ResolveInfo> retList = Lists.newArrayList();
8114//            while (i.hasNext()) {
8115//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8116//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8117//                    retList.add(resolveInfo);
8118//                }
8119//            }
8120//            return retList;
8121//        }
8122
8123        // Keys are String (activity class name), values are Activity.
8124        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8125                = new ArrayMap<ComponentName, PackageParser.Service>();
8126        private int mFlags;
8127    };
8128
8129    private final class ProviderIntentResolver
8130            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8131        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8132                boolean defaultOnly, int userId) {
8133            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8134            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8135        }
8136
8137        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8138                int userId) {
8139            if (!sUserManager.exists(userId))
8140                return null;
8141            mFlags = flags;
8142            return super.queryIntent(intent, resolvedType,
8143                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8144        }
8145
8146        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8147                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8148            if (!sUserManager.exists(userId))
8149                return null;
8150            if (packageProviders == null) {
8151                return null;
8152            }
8153            mFlags = flags;
8154            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8155            final int N = packageProviders.size();
8156            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8157                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8158
8159            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8160            for (int i = 0; i < N; ++i) {
8161                intentFilters = packageProviders.get(i).intents;
8162                if (intentFilters != null && intentFilters.size() > 0) {
8163                    PackageParser.ProviderIntentInfo[] array =
8164                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8165                    intentFilters.toArray(array);
8166                    listCut.add(array);
8167                }
8168            }
8169            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8170        }
8171
8172        public final void addProvider(PackageParser.Provider p) {
8173            if (mProviders.containsKey(p.getComponentName())) {
8174                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8175                return;
8176            }
8177
8178            mProviders.put(p.getComponentName(), p);
8179            if (DEBUG_SHOW_INFO) {
8180                Log.v(TAG, "  "
8181                        + (p.info.nonLocalizedLabel != null
8182                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8183                Log.v(TAG, "    Class=" + p.info.name);
8184            }
8185            final int NI = p.intents.size();
8186            int j;
8187            for (j = 0; j < NI; j++) {
8188                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8189                if (DEBUG_SHOW_INFO) {
8190                    Log.v(TAG, "    IntentFilter:");
8191                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8192                }
8193                if (!intent.debugCheck()) {
8194                    Log.w(TAG, "==> For Provider " + p.info.name);
8195                }
8196                addFilter(intent);
8197            }
8198        }
8199
8200        public final void removeProvider(PackageParser.Provider p) {
8201            mProviders.remove(p.getComponentName());
8202            if (DEBUG_SHOW_INFO) {
8203                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8204                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8205                Log.v(TAG, "    Class=" + p.info.name);
8206            }
8207            final int NI = p.intents.size();
8208            int j;
8209            for (j = 0; j < NI; j++) {
8210                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8211                if (DEBUG_SHOW_INFO) {
8212                    Log.v(TAG, "    IntentFilter:");
8213                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8214                }
8215                removeFilter(intent);
8216            }
8217        }
8218
8219        @Override
8220        protected boolean allowFilterResult(
8221                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8222            ProviderInfo filterPi = filter.provider.info;
8223            for (int i = dest.size() - 1; i >= 0; i--) {
8224                ProviderInfo destPi = dest.get(i).providerInfo;
8225                if (destPi.name == filterPi.name
8226                        && destPi.packageName == filterPi.packageName) {
8227                    return false;
8228                }
8229            }
8230            return true;
8231        }
8232
8233        @Override
8234        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8235            return new PackageParser.ProviderIntentInfo[size];
8236        }
8237
8238        @Override
8239        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8240            if (!sUserManager.exists(userId))
8241                return true;
8242            PackageParser.Package p = filter.provider.owner;
8243            if (p != null) {
8244                PackageSetting ps = (PackageSetting) p.mExtras;
8245                if (ps != null) {
8246                    // System apps are never considered stopped for purposes of
8247                    // filtering, because there may be no way for the user to
8248                    // actually re-launch them.
8249                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8250                            && ps.getStopped(userId);
8251                }
8252            }
8253            return false;
8254        }
8255
8256        @Override
8257        protected boolean isPackageForFilter(String packageName,
8258                PackageParser.ProviderIntentInfo info) {
8259            return packageName.equals(info.provider.owner.packageName);
8260        }
8261
8262        @Override
8263        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8264                int match, int userId) {
8265            if (!sUserManager.exists(userId))
8266                return null;
8267            final PackageParser.ProviderIntentInfo info = filter;
8268            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8269                return null;
8270            }
8271            final PackageParser.Provider provider = info.provider;
8272            if (mSafeMode && (provider.info.applicationInfo.flags
8273                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8274                return null;
8275            }
8276            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8277            if (ps == null) {
8278                return null;
8279            }
8280            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8281                    ps.readUserState(userId), userId);
8282            if (pi == null) {
8283                return null;
8284            }
8285            final ResolveInfo res = new ResolveInfo();
8286            res.providerInfo = pi;
8287            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8288                res.filter = filter;
8289            }
8290            res.priority = info.getPriority();
8291            res.preferredOrder = provider.owner.mPreferredOrder;
8292            res.match = match;
8293            res.isDefault = info.hasDefault;
8294            res.labelRes = info.labelRes;
8295            res.nonLocalizedLabel = info.nonLocalizedLabel;
8296            res.icon = info.icon;
8297            res.system = res.providerInfo.applicationInfo.isSystemApp();
8298            return res;
8299        }
8300
8301        @Override
8302        protected void sortResults(List<ResolveInfo> results) {
8303            Collections.sort(results, mResolvePrioritySorter);
8304        }
8305
8306        @Override
8307        protected void dumpFilter(PrintWriter out, String prefix,
8308                PackageParser.ProviderIntentInfo filter) {
8309            out.print(prefix);
8310            out.print(
8311                    Integer.toHexString(System.identityHashCode(filter.provider)));
8312            out.print(' ');
8313            filter.provider.printComponentShortName(out);
8314            out.print(" filter ");
8315            out.println(Integer.toHexString(System.identityHashCode(filter)));
8316        }
8317
8318        @Override
8319        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8320            return filter.provider;
8321        }
8322
8323        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8324            PackageParser.Provider provider = (PackageParser.Provider)label;
8325            out.print(prefix); out.print(
8326                    Integer.toHexString(System.identityHashCode(provider)));
8327                    out.print(' ');
8328                    provider.printComponentShortName(out);
8329            if (count > 1) {
8330                out.print(" ("); out.print(count); out.print(" filters)");
8331            }
8332            out.println();
8333        }
8334
8335        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8336                = new ArrayMap<ComponentName, PackageParser.Provider>();
8337        private int mFlags;
8338    };
8339
8340    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8341            new Comparator<ResolveInfo>() {
8342        public int compare(ResolveInfo r1, ResolveInfo r2) {
8343            int v1 = r1.priority;
8344            int v2 = r2.priority;
8345            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8346            if (v1 != v2) {
8347                return (v1 > v2) ? -1 : 1;
8348            }
8349            v1 = r1.preferredOrder;
8350            v2 = r2.preferredOrder;
8351            if (v1 != v2) {
8352                return (v1 > v2) ? -1 : 1;
8353            }
8354            if (r1.isDefault != r2.isDefault) {
8355                return r1.isDefault ? -1 : 1;
8356            }
8357            v1 = r1.match;
8358            v2 = r2.match;
8359            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8360            if (v1 != v2) {
8361                return (v1 > v2) ? -1 : 1;
8362            }
8363            if (r1.system != r2.system) {
8364                return r1.system ? -1 : 1;
8365            }
8366            return 0;
8367        }
8368    };
8369
8370    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8371            new Comparator<ProviderInfo>() {
8372        public int compare(ProviderInfo p1, ProviderInfo p2) {
8373            final int v1 = p1.initOrder;
8374            final int v2 = p2.initOrder;
8375            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8376        }
8377    };
8378
8379    static final void sendPackageBroadcast(String action, String pkg,
8380            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
8381            int[] userIds) {
8382        IActivityManager am = ActivityManagerNative.getDefault();
8383        if (am != null) {
8384            try {
8385                if (userIds == null) {
8386                    userIds = am.getRunningUserIds();
8387                }
8388                for (int id : userIds) {
8389                    final Intent intent = new Intent(action,
8390                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
8391                    if (extras != null) {
8392                        intent.putExtras(extras);
8393                    }
8394                    if (targetPkg != null) {
8395                        intent.setPackage(targetPkg);
8396                    }
8397                    // Modify the UID when posting to other users
8398                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8399                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
8400                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8401                        intent.putExtra(Intent.EXTRA_UID, uid);
8402                    }
8403                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8404                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8405                    if (DEBUG_BROADCASTS) {
8406                        RuntimeException here = new RuntimeException("here");
8407                        here.fillInStackTrace();
8408                        Slog.d(TAG, "Sending to user " + id + ": "
8409                                + intent.toShortString(false, true, false, false)
8410                                + " " + intent.getExtras(), here);
8411                    }
8412                    am.broadcastIntent(null, intent, null, finishedReceiver,
8413                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
8414                            finishedReceiver != null, false, id);
8415                }
8416            } catch (RemoteException ex) {
8417            }
8418        }
8419    }
8420
8421    /**
8422     * Check if the external storage media is available. This is true if there
8423     * is a mounted external storage medium or if the external storage is
8424     * emulated.
8425     */
8426    private boolean isExternalMediaAvailable() {
8427        return mMediaMounted || Environment.isExternalStorageEmulated();
8428    }
8429
8430    @Override
8431    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8432        // writer
8433        synchronized (mPackages) {
8434            if (!isExternalMediaAvailable()) {
8435                // If the external storage is no longer mounted at this point,
8436                // the caller may not have been able to delete all of this
8437                // packages files and can not delete any more.  Bail.
8438                return null;
8439            }
8440            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8441            if (lastPackage != null) {
8442                pkgs.remove(lastPackage);
8443            }
8444            if (pkgs.size() > 0) {
8445                return pkgs.get(0);
8446            }
8447        }
8448        return null;
8449    }
8450
8451    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8452        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8453                userId, andCode ? 1 : 0, packageName);
8454        if (mSystemReady) {
8455            msg.sendToTarget();
8456        } else {
8457            if (mPostSystemReadyMessages == null) {
8458                mPostSystemReadyMessages = new ArrayList<>();
8459            }
8460            mPostSystemReadyMessages.add(msg);
8461        }
8462    }
8463
8464    void startCleaningPackages() {
8465        // reader
8466        synchronized (mPackages) {
8467            if (!isExternalMediaAvailable()) {
8468                return;
8469            }
8470            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8471                return;
8472            }
8473        }
8474        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8475        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8476        IActivityManager am = ActivityManagerNative.getDefault();
8477        if (am != null) {
8478            try {
8479                am.startService(null, intent, null, UserHandle.USER_OWNER);
8480            } catch (RemoteException e) {
8481            }
8482        }
8483    }
8484
8485    @Override
8486    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8487            int installFlags, String installerPackageName, VerificationParams verificationParams,
8488            String packageAbiOverride) {
8489        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8490                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8491    }
8492
8493    @Override
8494    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8495            int installFlags, String installerPackageName, VerificationParams verificationParams,
8496            String packageAbiOverride, int userId) {
8497        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8498
8499        final int callingUid = Binder.getCallingUid();
8500        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8501
8502        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8503            try {
8504                if (observer != null) {
8505                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8506                }
8507            } catch (RemoteException re) {
8508            }
8509            return;
8510        }
8511
8512        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8513            installFlags |= PackageManager.INSTALL_FROM_ADB;
8514
8515        } else {
8516            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8517            // about installerPackageName.
8518
8519            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8520            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8521        }
8522
8523        UserHandle user;
8524        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8525            user = UserHandle.ALL;
8526        } else {
8527            user = new UserHandle(userId);
8528        }
8529
8530        verificationParams.setInstallerUid(callingUid);
8531
8532        final File originFile = new File(originPath);
8533        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8534
8535        final Message msg = mHandler.obtainMessage(INIT_COPY);
8536        msg.obj = new InstallParams(origin, observer, installFlags,
8537                installerPackageName, null, verificationParams, user, packageAbiOverride);
8538        mHandler.sendMessage(msg);
8539    }
8540
8541    void installStage(String packageName, File stagedDir, String stagedCid,
8542            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8543            String installerPackageName, int installerUid, UserHandle user) {
8544        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8545                params.referrerUri, installerUid, null);
8546
8547        final OriginInfo origin;
8548        if (stagedDir != null) {
8549            origin = OriginInfo.fromStagedFile(stagedDir);
8550        } else {
8551            origin = OriginInfo.fromStagedContainer(stagedCid);
8552        }
8553
8554        final Message msg = mHandler.obtainMessage(INIT_COPY);
8555        msg.obj = new InstallParams(origin, observer, params.installFlags,
8556                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8557        mHandler.sendMessage(msg);
8558    }
8559
8560    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8561        Bundle extras = new Bundle(1);
8562        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8563
8564        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8565                packageName, extras, null, null, new int[] {userId});
8566        try {
8567            IActivityManager am = ActivityManagerNative.getDefault();
8568            final boolean isSystem =
8569                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8570            if (isSystem && am.isUserRunning(userId, false)) {
8571                // The just-installed/enabled app is bundled on the system, so presumed
8572                // to be able to run automatically without needing an explicit launch.
8573                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8574                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8575                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8576                        .setPackage(packageName);
8577                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8578                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8579            }
8580        } catch (RemoteException e) {
8581            // shouldn't happen
8582            Slog.w(TAG, "Unable to bootstrap installed package", e);
8583        }
8584    }
8585
8586    @Override
8587    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8588            int userId) {
8589        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8590        PackageSetting pkgSetting;
8591        final int uid = Binder.getCallingUid();
8592        enforceCrossUserPermission(uid, userId, true, true,
8593                "setApplicationHiddenSetting for user " + userId);
8594
8595        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8596            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8597            return false;
8598        }
8599
8600        long callingId = Binder.clearCallingIdentity();
8601        try {
8602            boolean sendAdded = false;
8603            boolean sendRemoved = false;
8604            // writer
8605            synchronized (mPackages) {
8606                pkgSetting = mSettings.mPackages.get(packageName);
8607                if (pkgSetting == null) {
8608                    return false;
8609                }
8610                if (pkgSetting.getHidden(userId) != hidden) {
8611                    pkgSetting.setHidden(hidden, userId);
8612                    mSettings.writePackageRestrictionsLPr(userId);
8613                    if (hidden) {
8614                        sendRemoved = true;
8615                    } else {
8616                        sendAdded = true;
8617                    }
8618                }
8619            }
8620            if (sendAdded) {
8621                sendPackageAddedForUser(packageName, pkgSetting, userId);
8622                return true;
8623            }
8624            if (sendRemoved) {
8625                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8626                        "hiding pkg");
8627                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8628            }
8629        } finally {
8630            Binder.restoreCallingIdentity(callingId);
8631        }
8632        return false;
8633    }
8634
8635    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8636            int userId) {
8637        final PackageRemovedInfo info = new PackageRemovedInfo();
8638        info.removedPackage = packageName;
8639        info.removedUsers = new int[] {userId};
8640        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8641        info.sendBroadcast(false, false, false);
8642    }
8643
8644    /**
8645     * Returns true if application is not found or there was an error. Otherwise it returns
8646     * the hidden state of the package for the given user.
8647     */
8648    @Override
8649    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8650        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8651        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8652                false, "getApplicationHidden for user " + userId);
8653        PackageSetting pkgSetting;
8654        long callingId = Binder.clearCallingIdentity();
8655        try {
8656            // writer
8657            synchronized (mPackages) {
8658                pkgSetting = mSettings.mPackages.get(packageName);
8659                if (pkgSetting == null) {
8660                    return true;
8661                }
8662                return pkgSetting.getHidden(userId);
8663            }
8664        } finally {
8665            Binder.restoreCallingIdentity(callingId);
8666        }
8667    }
8668
8669    /**
8670     * @hide
8671     */
8672    @Override
8673    public int installExistingPackageAsUser(String packageName, int userId) {
8674        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8675                null);
8676        PackageSetting pkgSetting;
8677        final int uid = Binder.getCallingUid();
8678        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8679                + userId);
8680        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8681            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8682        }
8683
8684        long callingId = Binder.clearCallingIdentity();
8685        try {
8686            boolean sendAdded = false;
8687            Bundle extras = new Bundle(1);
8688
8689            // writer
8690            synchronized (mPackages) {
8691                pkgSetting = mSettings.mPackages.get(packageName);
8692                if (pkgSetting == null) {
8693                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8694                }
8695                if (!pkgSetting.getInstalled(userId)) {
8696                    pkgSetting.setInstalled(true, userId);
8697                    pkgSetting.setHidden(false, userId);
8698                    mSettings.writePackageRestrictionsLPr(userId);
8699                    sendAdded = true;
8700                }
8701            }
8702
8703            if (sendAdded) {
8704                sendPackageAddedForUser(packageName, pkgSetting, userId);
8705            }
8706        } finally {
8707            Binder.restoreCallingIdentity(callingId);
8708        }
8709
8710        return PackageManager.INSTALL_SUCCEEDED;
8711    }
8712
8713    boolean isUserRestricted(int userId, String restrictionKey) {
8714        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8715        if (restrictions.getBoolean(restrictionKey, false)) {
8716            Log.w(TAG, "User is restricted: " + restrictionKey);
8717            return true;
8718        }
8719        return false;
8720    }
8721
8722    @Override
8723    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8724        mContext.enforceCallingOrSelfPermission(
8725                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8726                "Only package verification agents can verify applications");
8727
8728        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8729        final PackageVerificationResponse response = new PackageVerificationResponse(
8730                verificationCode, Binder.getCallingUid());
8731        msg.arg1 = id;
8732        msg.obj = response;
8733        mHandler.sendMessage(msg);
8734    }
8735
8736    @Override
8737    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8738            long millisecondsToDelay) {
8739        mContext.enforceCallingOrSelfPermission(
8740                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8741                "Only package verification agents can extend verification timeouts");
8742
8743        final PackageVerificationState state = mPendingVerification.get(id);
8744        final PackageVerificationResponse response = new PackageVerificationResponse(
8745                verificationCodeAtTimeout, Binder.getCallingUid());
8746
8747        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8748            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8749        }
8750        if (millisecondsToDelay < 0) {
8751            millisecondsToDelay = 0;
8752        }
8753        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8754                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8755            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8756        }
8757
8758        if ((state != null) && !state.timeoutExtended()) {
8759            state.extendTimeout();
8760
8761            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8762            msg.arg1 = id;
8763            msg.obj = response;
8764            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8765        }
8766    }
8767
8768    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8769            int verificationCode, UserHandle user) {
8770        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8771        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8772        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8773        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8774        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8775
8776        mContext.sendBroadcastAsUser(intent, user,
8777                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8778    }
8779
8780    private ComponentName matchComponentForVerifier(String packageName,
8781            List<ResolveInfo> receivers) {
8782        ActivityInfo targetReceiver = null;
8783
8784        final int NR = receivers.size();
8785        for (int i = 0; i < NR; i++) {
8786            final ResolveInfo info = receivers.get(i);
8787            if (info.activityInfo == null) {
8788                continue;
8789            }
8790
8791            if (packageName.equals(info.activityInfo.packageName)) {
8792                targetReceiver = info.activityInfo;
8793                break;
8794            }
8795        }
8796
8797        if (targetReceiver == null) {
8798            return null;
8799        }
8800
8801        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8802    }
8803
8804    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8805            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8806        if (pkgInfo.verifiers.length == 0) {
8807            return null;
8808        }
8809
8810        final int N = pkgInfo.verifiers.length;
8811        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8812        for (int i = 0; i < N; i++) {
8813            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8814
8815            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8816                    receivers);
8817            if (comp == null) {
8818                continue;
8819            }
8820
8821            final int verifierUid = getUidForVerifier(verifierInfo);
8822            if (verifierUid == -1) {
8823                continue;
8824            }
8825
8826            if (DEBUG_VERIFY) {
8827                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8828                        + " with the correct signature");
8829            }
8830            sufficientVerifiers.add(comp);
8831            verificationState.addSufficientVerifier(verifierUid);
8832        }
8833
8834        return sufficientVerifiers;
8835    }
8836
8837    private int getUidForVerifier(VerifierInfo verifierInfo) {
8838        synchronized (mPackages) {
8839            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8840            if (pkg == null) {
8841                return -1;
8842            } else if (pkg.mSignatures.length != 1) {
8843                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8844                        + " has more than one signature; ignoring");
8845                return -1;
8846            }
8847
8848            /*
8849             * If the public key of the package's signature does not match
8850             * our expected public key, then this is a different package and
8851             * we should skip.
8852             */
8853
8854            final byte[] expectedPublicKey;
8855            try {
8856                final Signature verifierSig = pkg.mSignatures[0];
8857                final PublicKey publicKey = verifierSig.getPublicKey();
8858                expectedPublicKey = publicKey.getEncoded();
8859            } catch (CertificateException e) {
8860                return -1;
8861            }
8862
8863            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8864
8865            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8866                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8867                        + " does not have the expected public key; ignoring");
8868                return -1;
8869            }
8870
8871            return pkg.applicationInfo.uid;
8872        }
8873    }
8874
8875    @Override
8876    public void finishPackageInstall(int token) {
8877        enforceSystemOrRoot("Only the system is allowed to finish installs");
8878
8879        if (DEBUG_INSTALL) {
8880            Slog.v(TAG, "BM finishing package install for " + token);
8881        }
8882
8883        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8884        mHandler.sendMessage(msg);
8885    }
8886
8887    /**
8888     * Get the verification agent timeout.
8889     *
8890     * @return verification timeout in milliseconds
8891     */
8892    private long getVerificationTimeout() {
8893        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8894                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8895                DEFAULT_VERIFICATION_TIMEOUT);
8896    }
8897
8898    /**
8899     * Get the default verification agent response code.
8900     *
8901     * @return default verification response code
8902     */
8903    private int getDefaultVerificationResponse() {
8904        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8905                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8906                DEFAULT_VERIFICATION_RESPONSE);
8907    }
8908
8909    /**
8910     * Check whether or not package verification has been enabled.
8911     *
8912     * @return true if verification should be performed
8913     */
8914    private boolean isVerificationEnabled(int userId, int installFlags) {
8915        if (!DEFAULT_VERIFY_ENABLE) {
8916            return false;
8917        }
8918
8919        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8920
8921        // Check if installing from ADB
8922        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8923            // Do not run verification in a test harness environment
8924            if (ActivityManager.isRunningInTestHarness()) {
8925                return false;
8926            }
8927            if (ensureVerifyAppsEnabled) {
8928                return true;
8929            }
8930            // Check if the developer does not want package verification for ADB installs
8931            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8932                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8933                return false;
8934            }
8935        }
8936
8937        if (ensureVerifyAppsEnabled) {
8938            return true;
8939        }
8940
8941        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8942                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8943    }
8944
8945    @Override
8946    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
8947            throws RemoteException {
8948        mContext.enforceCallingOrSelfPermission(
8949                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
8950                "Only intentfilter verification agents can verify applications");
8951
8952        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
8953        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
8954                Binder.getCallingUid(), verificationCode, failedDomains);
8955        msg.arg1 = id;
8956        msg.obj = response;
8957        mHandler.sendMessage(msg);
8958    }
8959
8960    @Override
8961    public int getIntentVerificationStatus(String packageName, int userId) {
8962        synchronized (mPackages) {
8963            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
8964        }
8965    }
8966
8967    @Override
8968    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
8969        boolean result = false;
8970        synchronized (mPackages) {
8971            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
8972        }
8973        scheduleWritePackageRestrictionsLocked(userId);
8974        return result;
8975    }
8976
8977    @Override
8978    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
8979        synchronized (mPackages) {
8980            return mSettings.getIntentFilterVerificationsLPr(packageName);
8981        }
8982    }
8983
8984    /**
8985     * Get the "allow unknown sources" setting.
8986     *
8987     * @return the current "allow unknown sources" setting
8988     */
8989    private int getUnknownSourcesSettings() {
8990        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8991                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8992                -1);
8993    }
8994
8995    @Override
8996    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8997        final int uid = Binder.getCallingUid();
8998        // writer
8999        synchronized (mPackages) {
9000            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9001            if (targetPackageSetting == null) {
9002                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9003            }
9004
9005            PackageSetting installerPackageSetting;
9006            if (installerPackageName != null) {
9007                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9008                if (installerPackageSetting == null) {
9009                    throw new IllegalArgumentException("Unknown installer package: "
9010                            + installerPackageName);
9011                }
9012            } else {
9013                installerPackageSetting = null;
9014            }
9015
9016            Signature[] callerSignature;
9017            Object obj = mSettings.getUserIdLPr(uid);
9018            if (obj != null) {
9019                if (obj instanceof SharedUserSetting) {
9020                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9021                } else if (obj instanceof PackageSetting) {
9022                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9023                } else {
9024                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9025                }
9026            } else {
9027                throw new SecurityException("Unknown calling uid " + uid);
9028            }
9029
9030            // Verify: can't set installerPackageName to a package that is
9031            // not signed with the same cert as the caller.
9032            if (installerPackageSetting != null) {
9033                if (compareSignatures(callerSignature,
9034                        installerPackageSetting.signatures.mSignatures)
9035                        != PackageManager.SIGNATURE_MATCH) {
9036                    throw new SecurityException(
9037                            "Caller does not have same cert as new installer package "
9038                            + installerPackageName);
9039                }
9040            }
9041
9042            // Verify: if target already has an installer package, it must
9043            // be signed with the same cert as the caller.
9044            if (targetPackageSetting.installerPackageName != null) {
9045                PackageSetting setting = mSettings.mPackages.get(
9046                        targetPackageSetting.installerPackageName);
9047                // If the currently set package isn't valid, then it's always
9048                // okay to change it.
9049                if (setting != null) {
9050                    if (compareSignatures(callerSignature,
9051                            setting.signatures.mSignatures)
9052                            != PackageManager.SIGNATURE_MATCH) {
9053                        throw new SecurityException(
9054                                "Caller does not have same cert as old installer package "
9055                                + targetPackageSetting.installerPackageName);
9056                    }
9057                }
9058            }
9059
9060            // Okay!
9061            targetPackageSetting.installerPackageName = installerPackageName;
9062            scheduleWriteSettingsLocked();
9063        }
9064    }
9065
9066    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9067        // Queue up an async operation since the package installation may take a little while.
9068        mHandler.post(new Runnable() {
9069            public void run() {
9070                mHandler.removeCallbacks(this);
9071                 // Result object to be returned
9072                PackageInstalledInfo res = new PackageInstalledInfo();
9073                res.returnCode = currentStatus;
9074                res.uid = -1;
9075                res.pkg = null;
9076                res.removedInfo = new PackageRemovedInfo();
9077                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9078                    args.doPreInstall(res.returnCode);
9079                    synchronized (mInstallLock) {
9080                        installPackageLI(args, res);
9081                    }
9082                    args.doPostInstall(res.returnCode, res.uid);
9083                }
9084
9085                // A restore should be performed at this point if (a) the install
9086                // succeeded, (b) the operation is not an update, and (c) the new
9087                // package has not opted out of backup participation.
9088                final boolean update = res.removedInfo.removedPackage != null;
9089                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9090                boolean doRestore = !update
9091                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9092
9093                // Set up the post-install work request bookkeeping.  This will be used
9094                // and cleaned up by the post-install event handling regardless of whether
9095                // there's a restore pass performed.  Token values are >= 1.
9096                int token;
9097                if (mNextInstallToken < 0) mNextInstallToken = 1;
9098                token = mNextInstallToken++;
9099
9100                PostInstallData data = new PostInstallData(args, res);
9101                mRunningInstalls.put(token, data);
9102                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9103
9104                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9105                    // Pass responsibility to the Backup Manager.  It will perform a
9106                    // restore if appropriate, then pass responsibility back to the
9107                    // Package Manager to run the post-install observer callbacks
9108                    // and broadcasts.
9109                    IBackupManager bm = IBackupManager.Stub.asInterface(
9110                            ServiceManager.getService(Context.BACKUP_SERVICE));
9111                    if (bm != null) {
9112                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9113                                + " to BM for possible restore");
9114                        try {
9115                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9116                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9117                            } else {
9118                                doRestore = false;
9119                            }
9120                        } catch (RemoteException e) {
9121                            // can't happen; the backup manager is local
9122                        } catch (Exception e) {
9123                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9124                            doRestore = false;
9125                        }
9126                    } else {
9127                        Slog.e(TAG, "Backup Manager not found!");
9128                        doRestore = false;
9129                    }
9130                }
9131
9132                if (!doRestore) {
9133                    // No restore possible, or the Backup Manager was mysteriously not
9134                    // available -- just fire the post-install work request directly.
9135                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9136                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9137                    mHandler.sendMessage(msg);
9138                }
9139            }
9140        });
9141    }
9142
9143    private abstract class HandlerParams {
9144        private static final int MAX_RETRIES = 4;
9145
9146        /**
9147         * Number of times startCopy() has been attempted and had a non-fatal
9148         * error.
9149         */
9150        private int mRetries = 0;
9151
9152        /** User handle for the user requesting the information or installation. */
9153        private final UserHandle mUser;
9154
9155        HandlerParams(UserHandle user) {
9156            mUser = user;
9157        }
9158
9159        UserHandle getUser() {
9160            return mUser;
9161        }
9162
9163        final boolean startCopy() {
9164            boolean res;
9165            try {
9166                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9167
9168                if (++mRetries > MAX_RETRIES) {
9169                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9170                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9171                    handleServiceError();
9172                    return false;
9173                } else {
9174                    handleStartCopy();
9175                    res = true;
9176                }
9177            } catch (RemoteException e) {
9178                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9179                mHandler.sendEmptyMessage(MCS_RECONNECT);
9180                res = false;
9181            }
9182            handleReturnCode();
9183            return res;
9184        }
9185
9186        final void serviceError() {
9187            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9188            handleServiceError();
9189            handleReturnCode();
9190        }
9191
9192        abstract void handleStartCopy() throws RemoteException;
9193        abstract void handleServiceError();
9194        abstract void handleReturnCode();
9195    }
9196
9197    class MeasureParams extends HandlerParams {
9198        private final PackageStats mStats;
9199        private boolean mSuccess;
9200
9201        private final IPackageStatsObserver mObserver;
9202
9203        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9204            super(new UserHandle(stats.userHandle));
9205            mObserver = observer;
9206            mStats = stats;
9207        }
9208
9209        @Override
9210        public String toString() {
9211            return "MeasureParams{"
9212                + Integer.toHexString(System.identityHashCode(this))
9213                + " " + mStats.packageName + "}";
9214        }
9215
9216        @Override
9217        void handleStartCopy() throws RemoteException {
9218            synchronized (mInstallLock) {
9219                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9220            }
9221
9222            if (mSuccess) {
9223                final boolean mounted;
9224                if (Environment.isExternalStorageEmulated()) {
9225                    mounted = true;
9226                } else {
9227                    final String status = Environment.getExternalStorageState();
9228                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9229                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9230                }
9231
9232                if (mounted) {
9233                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9234
9235                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9236                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9237
9238                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9239                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9240
9241                    // Always subtract cache size, since it's a subdirectory
9242                    mStats.externalDataSize -= mStats.externalCacheSize;
9243
9244                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9245                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9246
9247                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9248                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9249                }
9250            }
9251        }
9252
9253        @Override
9254        void handleReturnCode() {
9255            if (mObserver != null) {
9256                try {
9257                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9258                } catch (RemoteException e) {
9259                    Slog.i(TAG, "Observer no longer exists.");
9260                }
9261            }
9262        }
9263
9264        @Override
9265        void handleServiceError() {
9266            Slog.e(TAG, "Could not measure application " + mStats.packageName
9267                            + " external storage");
9268        }
9269    }
9270
9271    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9272            throws RemoteException {
9273        long result = 0;
9274        for (File path : paths) {
9275            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9276        }
9277        return result;
9278    }
9279
9280    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9281        for (File path : paths) {
9282            try {
9283                mcs.clearDirectory(path.getAbsolutePath());
9284            } catch (RemoteException e) {
9285            }
9286        }
9287    }
9288
9289    static class OriginInfo {
9290        /**
9291         * Location where install is coming from, before it has been
9292         * copied/renamed into place. This could be a single monolithic APK
9293         * file, or a cluster directory. This location may be untrusted.
9294         */
9295        final File file;
9296        final String cid;
9297
9298        /**
9299         * Flag indicating that {@link #file} or {@link #cid} has already been
9300         * staged, meaning downstream users don't need to defensively copy the
9301         * contents.
9302         */
9303        final boolean staged;
9304
9305        /**
9306         * Flag indicating that {@link #file} or {@link #cid} is an already
9307         * installed app that is being moved.
9308         */
9309        final boolean existing;
9310
9311        final String resolvedPath;
9312        final File resolvedFile;
9313
9314        static OriginInfo fromNothing() {
9315            return new OriginInfo(null, null, false, false);
9316        }
9317
9318        static OriginInfo fromUntrustedFile(File file) {
9319            return new OriginInfo(file, null, false, false);
9320        }
9321
9322        static OriginInfo fromExistingFile(File file) {
9323            return new OriginInfo(file, null, false, true);
9324        }
9325
9326        static OriginInfo fromStagedFile(File file) {
9327            return new OriginInfo(file, null, true, false);
9328        }
9329
9330        static OriginInfo fromStagedContainer(String cid) {
9331            return new OriginInfo(null, cid, true, false);
9332        }
9333
9334        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9335            this.file = file;
9336            this.cid = cid;
9337            this.staged = staged;
9338            this.existing = existing;
9339
9340            if (cid != null) {
9341                resolvedPath = PackageHelper.getSdDir(cid);
9342                resolvedFile = new File(resolvedPath);
9343            } else if (file != null) {
9344                resolvedPath = file.getAbsolutePath();
9345                resolvedFile = file;
9346            } else {
9347                resolvedPath = null;
9348                resolvedFile = null;
9349            }
9350        }
9351    }
9352
9353    class InstallParams extends HandlerParams {
9354        final OriginInfo origin;
9355        final IPackageInstallObserver2 observer;
9356        int installFlags;
9357        final String installerPackageName;
9358        final String volumeUuid;
9359        final VerificationParams verificationParams;
9360        private InstallArgs mArgs;
9361        private int mRet;
9362        final String packageAbiOverride;
9363
9364        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9365                String installerPackageName, String volumeUuid,
9366                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9367            super(user);
9368            this.origin = origin;
9369            this.observer = observer;
9370            this.installFlags = installFlags;
9371            this.installerPackageName = installerPackageName;
9372            this.volumeUuid = volumeUuid;
9373            this.verificationParams = verificationParams;
9374            this.packageAbiOverride = packageAbiOverride;
9375        }
9376
9377        @Override
9378        public String toString() {
9379            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9380                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9381        }
9382
9383        public ManifestDigest getManifestDigest() {
9384            if (verificationParams == null) {
9385                return null;
9386            }
9387            return verificationParams.getManifestDigest();
9388        }
9389
9390        private int installLocationPolicy(PackageInfoLite pkgLite) {
9391            String packageName = pkgLite.packageName;
9392            int installLocation = pkgLite.installLocation;
9393            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9394            // reader
9395            synchronized (mPackages) {
9396                PackageParser.Package pkg = mPackages.get(packageName);
9397                if (pkg != null) {
9398                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9399                        // Check for downgrading.
9400                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9401                            try {
9402                                checkDowngrade(pkg, pkgLite);
9403                            } catch (PackageManagerException e) {
9404                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9405                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9406                            }
9407                        }
9408                        // Check for updated system application.
9409                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9410                            if (onSd) {
9411                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9412                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9413                            }
9414                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9415                        } else {
9416                            if (onSd) {
9417                                // Install flag overrides everything.
9418                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9419                            }
9420                            // If current upgrade specifies particular preference
9421                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9422                                // Application explicitly specified internal.
9423                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9424                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9425                                // App explictly prefers external. Let policy decide
9426                            } else {
9427                                // Prefer previous location
9428                                if (isExternal(pkg)) {
9429                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9430                                }
9431                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9432                            }
9433                        }
9434                    } else {
9435                        // Invalid install. Return error code
9436                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9437                    }
9438                }
9439            }
9440            // All the special cases have been taken care of.
9441            // Return result based on recommended install location.
9442            if (onSd) {
9443                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9444            }
9445            return pkgLite.recommendedInstallLocation;
9446        }
9447
9448        /*
9449         * Invoke remote method to get package information and install
9450         * location values. Override install location based on default
9451         * policy if needed and then create install arguments based
9452         * on the install location.
9453         */
9454        public void handleStartCopy() throws RemoteException {
9455            int ret = PackageManager.INSTALL_SUCCEEDED;
9456
9457            // If we're already staged, we've firmly committed to an install location
9458            if (origin.staged) {
9459                if (origin.file != null) {
9460                    installFlags |= PackageManager.INSTALL_INTERNAL;
9461                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9462                } else if (origin.cid != null) {
9463                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9464                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9465                } else {
9466                    throw new IllegalStateException("Invalid stage location");
9467                }
9468            }
9469
9470            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9471            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9472
9473            PackageInfoLite pkgLite = null;
9474
9475            if (onInt && onSd) {
9476                // Check if both bits are set.
9477                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9478                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9479            } else {
9480                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9481                        packageAbiOverride);
9482
9483                /*
9484                 * If we have too little free space, try to free cache
9485                 * before giving up.
9486                 */
9487                if (!origin.staged && pkgLite.recommendedInstallLocation
9488                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9489                    // TODO: focus freeing disk space on the target device
9490                    final StorageManager storage = StorageManager.from(mContext);
9491                    final long lowThreshold = storage.getStorageLowBytes(
9492                            Environment.getDataDirectory());
9493
9494                    final long sizeBytes = mContainerService.calculateInstalledSize(
9495                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9496
9497                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
9498                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9499                                installFlags, packageAbiOverride);
9500                    }
9501
9502                    /*
9503                     * The cache free must have deleted the file we
9504                     * downloaded to install.
9505                     *
9506                     * TODO: fix the "freeCache" call to not delete
9507                     *       the file we care about.
9508                     */
9509                    if (pkgLite.recommendedInstallLocation
9510                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9511                        pkgLite.recommendedInstallLocation
9512                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9513                    }
9514                }
9515            }
9516
9517            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9518                int loc = pkgLite.recommendedInstallLocation;
9519                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9520                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9521                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9522                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9523                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9524                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9525                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9526                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9527                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9528                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9529                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9530                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9531                } else {
9532                    // Override with defaults if needed.
9533                    loc = installLocationPolicy(pkgLite);
9534                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9535                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9536                    } else if (!onSd && !onInt) {
9537                        // Override install location with flags
9538                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9539                            // Set the flag to install on external media.
9540                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9541                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9542                        } else {
9543                            // Make sure the flag for installing on external
9544                            // media is unset
9545                            installFlags |= PackageManager.INSTALL_INTERNAL;
9546                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9547                        }
9548                    }
9549                }
9550            }
9551
9552            final InstallArgs args = createInstallArgs(this);
9553            mArgs = args;
9554
9555            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9556                 /*
9557                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9558                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9559                 */
9560                int userIdentifier = getUser().getIdentifier();
9561                if (userIdentifier == UserHandle.USER_ALL
9562                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9563                    userIdentifier = UserHandle.USER_OWNER;
9564                }
9565
9566                /*
9567                 * Determine if we have any installed package verifiers. If we
9568                 * do, then we'll defer to them to verify the packages.
9569                 */
9570                final int requiredUid = mRequiredVerifierPackage == null ? -1
9571                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9572                if (!origin.existing && requiredUid != -1
9573                        && isVerificationEnabled(userIdentifier, installFlags)) {
9574                    final Intent verification = new Intent(
9575                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9576                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9577                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9578                            PACKAGE_MIME_TYPE);
9579                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9580
9581                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9582                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9583                            0 /* TODO: Which userId? */);
9584
9585                    if (DEBUG_VERIFY) {
9586                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9587                                + verification.toString() + " with " + pkgLite.verifiers.length
9588                                + " optional verifiers");
9589                    }
9590
9591                    final int verificationId = mPendingVerificationToken++;
9592
9593                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9594
9595                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9596                            installerPackageName);
9597
9598                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9599                            installFlags);
9600
9601                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9602                            pkgLite.packageName);
9603
9604                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9605                            pkgLite.versionCode);
9606
9607                    if (verificationParams != null) {
9608                        if (verificationParams.getVerificationURI() != null) {
9609                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9610                                 verificationParams.getVerificationURI());
9611                        }
9612                        if (verificationParams.getOriginatingURI() != null) {
9613                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9614                                  verificationParams.getOriginatingURI());
9615                        }
9616                        if (verificationParams.getReferrer() != null) {
9617                            verification.putExtra(Intent.EXTRA_REFERRER,
9618                                  verificationParams.getReferrer());
9619                        }
9620                        if (verificationParams.getOriginatingUid() >= 0) {
9621                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9622                                  verificationParams.getOriginatingUid());
9623                        }
9624                        if (verificationParams.getInstallerUid() >= 0) {
9625                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9626                                  verificationParams.getInstallerUid());
9627                        }
9628                    }
9629
9630                    final PackageVerificationState verificationState = new PackageVerificationState(
9631                            requiredUid, args);
9632
9633                    mPendingVerification.append(verificationId, verificationState);
9634
9635                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9636                            receivers, verificationState);
9637
9638                    /*
9639                     * If any sufficient verifiers were listed in the package
9640                     * manifest, attempt to ask them.
9641                     */
9642                    if (sufficientVerifiers != null) {
9643                        final int N = sufficientVerifiers.size();
9644                        if (N == 0) {
9645                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9646                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9647                        } else {
9648                            for (int i = 0; i < N; i++) {
9649                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9650
9651                                final Intent sufficientIntent = new Intent(verification);
9652                                sufficientIntent.setComponent(verifierComponent);
9653
9654                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9655                            }
9656                        }
9657                    }
9658
9659                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9660                            mRequiredVerifierPackage, receivers);
9661                    if (ret == PackageManager.INSTALL_SUCCEEDED
9662                            && mRequiredVerifierPackage != null) {
9663                        /*
9664                         * Send the intent to the required verification agent,
9665                         * but only start the verification timeout after the
9666                         * target BroadcastReceivers have run.
9667                         */
9668                        verification.setComponent(requiredVerifierComponent);
9669                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9670                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9671                                new BroadcastReceiver() {
9672                                    @Override
9673                                    public void onReceive(Context context, Intent intent) {
9674                                        final Message msg = mHandler
9675                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9676                                        msg.arg1 = verificationId;
9677                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9678                                    }
9679                                }, null, 0, null, null);
9680
9681                        /*
9682                         * We don't want the copy to proceed until verification
9683                         * succeeds, so null out this field.
9684                         */
9685                        mArgs = null;
9686                    }
9687                } else {
9688                    /*
9689                     * No package verification is enabled, so immediately start
9690                     * the remote call to initiate copy using temporary file.
9691                     */
9692                    ret = args.copyApk(mContainerService, true);
9693                }
9694            }
9695
9696            mRet = ret;
9697        }
9698
9699        @Override
9700        void handleReturnCode() {
9701            // If mArgs is null, then MCS couldn't be reached. When it
9702            // reconnects, it will try again to install. At that point, this
9703            // will succeed.
9704            if (mArgs != null) {
9705                processPendingInstall(mArgs, mRet);
9706            }
9707        }
9708
9709        @Override
9710        void handleServiceError() {
9711            mArgs = createInstallArgs(this);
9712            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9713        }
9714
9715        public boolean isForwardLocked() {
9716            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9717        }
9718    }
9719
9720    /**
9721     * Used during creation of InstallArgs
9722     *
9723     * @param installFlags package installation flags
9724     * @return true if should be installed on external storage
9725     */
9726    private static boolean installOnExternalAsec(int installFlags) {
9727        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9728            return false;
9729        }
9730        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9731            return true;
9732        }
9733        return false;
9734    }
9735
9736    /**
9737     * Used during creation of InstallArgs
9738     *
9739     * @param installFlags package installation flags
9740     * @return true if should be installed as forward locked
9741     */
9742    private static boolean installForwardLocked(int installFlags) {
9743        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9744    }
9745
9746    private InstallArgs createInstallArgs(InstallParams params) {
9747        if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
9748            return new AsecInstallArgs(params);
9749        } else {
9750            return new FileInstallArgs(params);
9751        }
9752    }
9753
9754    /**
9755     * Create args that describe an existing installed package. Typically used
9756     * when cleaning up old installs, or used as a move source.
9757     */
9758    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9759            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9760        final boolean isInAsec;
9761        if (installOnExternalAsec(installFlags)) {
9762            /* Apps on SD card are always in ASEC containers. */
9763            isInAsec = true;
9764        } else if (installForwardLocked(installFlags)
9765                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9766            /*
9767             * Forward-locked apps are only in ASEC containers if they're the
9768             * new style
9769             */
9770            isInAsec = true;
9771        } else {
9772            isInAsec = false;
9773        }
9774
9775        if (isInAsec) {
9776            return new AsecInstallArgs(codePath, instructionSets,
9777                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
9778        } else {
9779            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9780                    instructionSets);
9781        }
9782    }
9783
9784    static abstract class InstallArgs {
9785        /** @see InstallParams#origin */
9786        final OriginInfo origin;
9787
9788        final IPackageInstallObserver2 observer;
9789        // Always refers to PackageManager flags only
9790        final int installFlags;
9791        final String installerPackageName;
9792        final String volumeUuid;
9793        final ManifestDigest manifestDigest;
9794        final UserHandle user;
9795        final String abiOverride;
9796
9797        // The list of instruction sets supported by this app. This is currently
9798        // only used during the rmdex() phase to clean up resources. We can get rid of this
9799        // if we move dex files under the common app path.
9800        /* nullable */ String[] instructionSets;
9801
9802        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9803                String installerPackageName, String volumeUuid, ManifestDigest manifestDigest,
9804                UserHandle user, String[] instructionSets, String abiOverride) {
9805            this.origin = origin;
9806            this.installFlags = installFlags;
9807            this.observer = observer;
9808            this.installerPackageName = installerPackageName;
9809            this.volumeUuid = volumeUuid;
9810            this.manifestDigest = manifestDigest;
9811            this.user = user;
9812            this.instructionSets = instructionSets;
9813            this.abiOverride = abiOverride;
9814        }
9815
9816        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9817        abstract int doPreInstall(int status);
9818
9819        /**
9820         * Rename package into final resting place. All paths on the given
9821         * scanned package should be updated to reflect the rename.
9822         */
9823        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9824        abstract int doPostInstall(int status, int uid);
9825
9826        /** @see PackageSettingBase#codePathString */
9827        abstract String getCodePath();
9828        /** @see PackageSettingBase#resourcePathString */
9829        abstract String getResourcePath();
9830        abstract String getLegacyNativeLibraryPath();
9831
9832        // Need installer lock especially for dex file removal.
9833        abstract void cleanUpResourcesLI();
9834        abstract boolean doPostDeleteLI(boolean delete);
9835        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9836
9837        /**
9838         * Called before the source arguments are copied. This is used mostly
9839         * for MoveParams when it needs to read the source file to put it in the
9840         * destination.
9841         */
9842        int doPreCopy() {
9843            return PackageManager.INSTALL_SUCCEEDED;
9844        }
9845
9846        /**
9847         * Called after the source arguments are copied. This is used mostly for
9848         * MoveParams when it needs to read the source file to put it in the
9849         * destination.
9850         *
9851         * @return
9852         */
9853        int doPostCopy(int uid) {
9854            return PackageManager.INSTALL_SUCCEEDED;
9855        }
9856
9857        protected boolean isFwdLocked() {
9858            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9859        }
9860
9861        protected boolean isExternalAsec() {
9862            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9863        }
9864
9865        UserHandle getUser() {
9866            return user;
9867        }
9868    }
9869
9870    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
9871        if (!allCodePaths.isEmpty()) {
9872            if (instructionSets == null) {
9873                throw new IllegalStateException("instructionSet == null");
9874            }
9875            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9876            for (String codePath : allCodePaths) {
9877                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9878                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9879                    if (retCode < 0) {
9880                        Slog.w(TAG, "Couldn't remove dex file for package: "
9881                                + " at location " + codePath + ", retcode=" + retCode);
9882                        // we don't consider this to be a failure of the core package deletion
9883                    }
9884                }
9885            }
9886        }
9887    }
9888
9889    /**
9890     * Logic to handle installation of non-ASEC applications, including copying
9891     * and renaming logic.
9892     */
9893    class FileInstallArgs extends InstallArgs {
9894        private File codeFile;
9895        private File resourceFile;
9896        private File legacyNativeLibraryPath;
9897
9898        // Example topology:
9899        // /data/app/com.example/base.apk
9900        // /data/app/com.example/split_foo.apk
9901        // /data/app/com.example/lib/arm/libfoo.so
9902        // /data/app/com.example/lib/arm64/libfoo.so
9903        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9904
9905        /** New install */
9906        FileInstallArgs(InstallParams params) {
9907            super(params.origin, params.observer, params.installFlags,
9908                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
9909                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
9910            if (isFwdLocked()) {
9911                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9912            }
9913        }
9914
9915        /** Existing install */
9916        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9917                String[] instructionSets) {
9918            super(OriginInfo.fromNothing(), null, 0, null, null, null, null, instructionSets, null);
9919            this.codeFile = (codePath != null) ? new File(codePath) : null;
9920            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9921            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9922                    new File(legacyNativeLibraryPath) : null;
9923        }
9924
9925        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9926            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9927                    isFwdLocked(), abiOverride);
9928
9929            final StorageManager storage = StorageManager.from(mContext);
9930            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9931        }
9932
9933        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9934            if (origin.staged) {
9935                Slog.d(TAG, origin.file + " already staged; skipping copy");
9936                codeFile = origin.file;
9937                resourceFile = origin.file;
9938                return PackageManager.INSTALL_SUCCEEDED;
9939            }
9940
9941            try {
9942                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
9943                codeFile = tempDir;
9944                resourceFile = tempDir;
9945            } catch (IOException e) {
9946                Slog.w(TAG, "Failed to create copy file: " + e);
9947                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9948            }
9949
9950            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9951                @Override
9952                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9953                    if (!FileUtils.isValidExtFilename(name)) {
9954                        throw new IllegalArgumentException("Invalid filename: " + name);
9955                    }
9956                    try {
9957                        final File file = new File(codeFile, name);
9958                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9959                                O_RDWR | O_CREAT, 0644);
9960                        Os.chmod(file.getAbsolutePath(), 0644);
9961                        return new ParcelFileDescriptor(fd);
9962                    } catch (ErrnoException e) {
9963                        throw new RemoteException("Failed to open: " + e.getMessage());
9964                    }
9965                }
9966            };
9967
9968            int ret = PackageManager.INSTALL_SUCCEEDED;
9969            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9970            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9971                Slog.e(TAG, "Failed to copy package");
9972                return ret;
9973            }
9974
9975            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9976            NativeLibraryHelper.Handle handle = null;
9977            try {
9978                handle = NativeLibraryHelper.Handle.create(codeFile);
9979                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9980                        abiOverride);
9981            } catch (IOException e) {
9982                Slog.e(TAG, "Copying native libraries failed", e);
9983                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9984            } finally {
9985                IoUtils.closeQuietly(handle);
9986            }
9987
9988            return ret;
9989        }
9990
9991        int doPreInstall(int status) {
9992            if (status != PackageManager.INSTALL_SUCCEEDED) {
9993                cleanUp();
9994            }
9995            return status;
9996        }
9997
9998        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9999            if (status != PackageManager.INSTALL_SUCCEEDED) {
10000                cleanUp();
10001                return false;
10002            } else {
10003                final File targetDir = codeFile.getParentFile();
10004                final File beforeCodeFile = codeFile;
10005                final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10006
10007                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10008                try {
10009                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10010                } catch (ErrnoException e) {
10011                    Slog.d(TAG, "Failed to rename", e);
10012                    return false;
10013                }
10014
10015                if (!SELinux.restoreconRecursive(afterCodeFile)) {
10016                    Slog.d(TAG, "Failed to restorecon");
10017                    return false;
10018                }
10019
10020                // Reflect the rename internally
10021                codeFile = afterCodeFile;
10022                resourceFile = afterCodeFile;
10023
10024                // Reflect the rename in scanned details
10025                pkg.codePath = afterCodeFile.getAbsolutePath();
10026                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10027                        pkg.baseCodePath);
10028                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10029                        pkg.splitCodePaths);
10030
10031                // Reflect the rename in app info
10032                pkg.applicationInfo.setCodePath(pkg.codePath);
10033                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10034                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10035                pkg.applicationInfo.setResourcePath(pkg.codePath);
10036                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10037                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10038
10039                return true;
10040            }
10041        }
10042
10043        int doPostInstall(int status, int uid) {
10044            if (status != PackageManager.INSTALL_SUCCEEDED) {
10045                cleanUp();
10046            }
10047            return status;
10048        }
10049
10050        @Override
10051        String getCodePath() {
10052            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10053        }
10054
10055        @Override
10056        String getResourcePath() {
10057            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10058        }
10059
10060        @Override
10061        String getLegacyNativeLibraryPath() {
10062            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
10063        }
10064
10065        private boolean cleanUp() {
10066            if (codeFile == null || !codeFile.exists()) {
10067                return false;
10068            }
10069
10070            if (codeFile.isDirectory()) {
10071                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10072            } else {
10073                codeFile.delete();
10074            }
10075
10076            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10077                resourceFile.delete();
10078            }
10079
10080            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
10081                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
10082                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
10083                }
10084                legacyNativeLibraryPath.delete();
10085            }
10086
10087            return true;
10088        }
10089
10090        void cleanUpResourcesLI() {
10091            // Try enumerating all code paths before deleting
10092            List<String> allCodePaths = Collections.EMPTY_LIST;
10093            if (codeFile != null && codeFile.exists()) {
10094                try {
10095                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10096                    allCodePaths = pkg.getAllCodePaths();
10097                } catch (PackageParserException e) {
10098                    // Ignored; we tried our best
10099                }
10100            }
10101
10102            cleanUp();
10103            removeDexFiles(allCodePaths, instructionSets);
10104        }
10105
10106        boolean doPostDeleteLI(boolean delete) {
10107            // XXX err, shouldn't we respect the delete flag?
10108            cleanUpResourcesLI();
10109            return true;
10110        }
10111    }
10112
10113    private boolean isAsecExternal(String cid) {
10114        final String asecPath = PackageHelper.getSdFilesystem(cid);
10115        return !asecPath.startsWith(mAsecInternalPath);
10116    }
10117
10118    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10119            PackageManagerException {
10120        if (copyRet < 0) {
10121            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10122                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10123                throw new PackageManagerException(copyRet, message);
10124            }
10125        }
10126    }
10127
10128    /**
10129     * Extract the MountService "container ID" from the full code path of an
10130     * .apk.
10131     */
10132    static String cidFromCodePath(String fullCodePath) {
10133        int eidx = fullCodePath.lastIndexOf("/");
10134        String subStr1 = fullCodePath.substring(0, eidx);
10135        int sidx = subStr1.lastIndexOf("/");
10136        return subStr1.substring(sidx+1, eidx);
10137    }
10138
10139    /**
10140     * Logic to handle installation of ASEC applications, including copying and
10141     * renaming logic.
10142     */
10143    class AsecInstallArgs extends InstallArgs {
10144        static final String RES_FILE_NAME = "pkg.apk";
10145        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10146
10147        String cid;
10148        String packagePath;
10149        String resourcePath;
10150        String legacyNativeLibraryDir;
10151
10152        /** New install */
10153        AsecInstallArgs(InstallParams params) {
10154            super(params.origin, params.observer, params.installFlags,
10155                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10156                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10157        }
10158
10159        /** Existing install */
10160        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10161                        boolean isExternal, boolean isForwardLocked) {
10162            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
10163                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10164                    instructionSets, null);
10165            // Hackily pretend we're still looking at a full code path
10166            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10167                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10168            }
10169
10170            // Extract cid from fullCodePath
10171            int eidx = fullCodePath.lastIndexOf("/");
10172            String subStr1 = fullCodePath.substring(0, eidx);
10173            int sidx = subStr1.lastIndexOf("/");
10174            cid = subStr1.substring(sidx+1, eidx);
10175            setMountPath(subStr1);
10176        }
10177
10178        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10179            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10180                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10181                    instructionSets, null);
10182            this.cid = cid;
10183            setMountPath(PackageHelper.getSdDir(cid));
10184        }
10185
10186        void createCopyFile() {
10187            cid = mInstallerService.allocateExternalStageCidLegacy();
10188        }
10189
10190        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
10191            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
10192                    abiOverride);
10193
10194            final File target;
10195            if (isExternalAsec()) {
10196                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
10197            } else {
10198                target = Environment.getDataDirectory();
10199            }
10200
10201            final StorageManager storage = StorageManager.from(mContext);
10202            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
10203        }
10204
10205        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10206            if (origin.staged) {
10207                Slog.d(TAG, origin.cid + " already staged; skipping copy");
10208                cid = origin.cid;
10209                setMountPath(PackageHelper.getSdDir(cid));
10210                return PackageManager.INSTALL_SUCCEEDED;
10211            }
10212
10213            if (temp) {
10214                createCopyFile();
10215            } else {
10216                /*
10217                 * Pre-emptively destroy the container since it's destroyed if
10218                 * copying fails due to it existing anyway.
10219                 */
10220                PackageHelper.destroySdDir(cid);
10221            }
10222
10223            final String newMountPath = imcs.copyPackageToContainer(
10224                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10225                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10226
10227            if (newMountPath != null) {
10228                setMountPath(newMountPath);
10229                return PackageManager.INSTALL_SUCCEEDED;
10230            } else {
10231                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10232            }
10233        }
10234
10235        @Override
10236        String getCodePath() {
10237            return packagePath;
10238        }
10239
10240        @Override
10241        String getResourcePath() {
10242            return resourcePath;
10243        }
10244
10245        @Override
10246        String getLegacyNativeLibraryPath() {
10247            return legacyNativeLibraryDir;
10248        }
10249
10250        int doPreInstall(int status) {
10251            if (status != PackageManager.INSTALL_SUCCEEDED) {
10252                // Destroy container
10253                PackageHelper.destroySdDir(cid);
10254            } else {
10255                boolean mounted = PackageHelper.isContainerMounted(cid);
10256                if (!mounted) {
10257                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10258                            Process.SYSTEM_UID);
10259                    if (newMountPath != null) {
10260                        setMountPath(newMountPath);
10261                    } else {
10262                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10263                    }
10264                }
10265            }
10266            return status;
10267        }
10268
10269        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10270            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10271            String newMountPath = null;
10272            if (PackageHelper.isContainerMounted(cid)) {
10273                // Unmount the container
10274                if (!PackageHelper.unMountSdDir(cid)) {
10275                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10276                    return false;
10277                }
10278            }
10279            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10280                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10281                        " which might be stale. Will try to clean up.");
10282                // Clean up the stale container and proceed to recreate.
10283                if (!PackageHelper.destroySdDir(newCacheId)) {
10284                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10285                    return false;
10286                }
10287                // Successfully cleaned up stale container. Try to rename again.
10288                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10289                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10290                            + " inspite of cleaning it up.");
10291                    return false;
10292                }
10293            }
10294            if (!PackageHelper.isContainerMounted(newCacheId)) {
10295                Slog.w(TAG, "Mounting container " + newCacheId);
10296                newMountPath = PackageHelper.mountSdDir(newCacheId,
10297                        getEncryptKey(), Process.SYSTEM_UID);
10298            } else {
10299                newMountPath = PackageHelper.getSdDir(newCacheId);
10300            }
10301            if (newMountPath == null) {
10302                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10303                return false;
10304            }
10305            Log.i(TAG, "Succesfully renamed " + cid +
10306                    " to " + newCacheId +
10307                    " at new path: " + newMountPath);
10308            cid = newCacheId;
10309
10310            final File beforeCodeFile = new File(packagePath);
10311            setMountPath(newMountPath);
10312            final File afterCodeFile = new File(packagePath);
10313
10314            // Reflect the rename in scanned details
10315            pkg.codePath = afterCodeFile.getAbsolutePath();
10316            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10317                    pkg.baseCodePath);
10318            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10319                    pkg.splitCodePaths);
10320
10321            // Reflect the rename in app info
10322            pkg.applicationInfo.setCodePath(pkg.codePath);
10323            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10324            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10325            pkg.applicationInfo.setResourcePath(pkg.codePath);
10326            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10327            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10328
10329            return true;
10330        }
10331
10332        private void setMountPath(String mountPath) {
10333            final File mountFile = new File(mountPath);
10334
10335            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10336            if (monolithicFile.exists()) {
10337                packagePath = monolithicFile.getAbsolutePath();
10338                if (isFwdLocked()) {
10339                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10340                } else {
10341                    resourcePath = packagePath;
10342                }
10343            } else {
10344                packagePath = mountFile.getAbsolutePath();
10345                resourcePath = packagePath;
10346            }
10347
10348            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
10349        }
10350
10351        int doPostInstall(int status, int uid) {
10352            if (status != PackageManager.INSTALL_SUCCEEDED) {
10353                cleanUp();
10354            } else {
10355                final int groupOwner;
10356                final String protectedFile;
10357                if (isFwdLocked()) {
10358                    groupOwner = UserHandle.getSharedAppGid(uid);
10359                    protectedFile = RES_FILE_NAME;
10360                } else {
10361                    groupOwner = -1;
10362                    protectedFile = null;
10363                }
10364
10365                if (uid < Process.FIRST_APPLICATION_UID
10366                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10367                    Slog.e(TAG, "Failed to finalize " + cid);
10368                    PackageHelper.destroySdDir(cid);
10369                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10370                }
10371
10372                boolean mounted = PackageHelper.isContainerMounted(cid);
10373                if (!mounted) {
10374                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10375                }
10376            }
10377            return status;
10378        }
10379
10380        private void cleanUp() {
10381            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10382
10383            // Destroy secure container
10384            PackageHelper.destroySdDir(cid);
10385        }
10386
10387        private List<String> getAllCodePaths() {
10388            final File codeFile = new File(getCodePath());
10389            if (codeFile != null && codeFile.exists()) {
10390                try {
10391                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10392                    return pkg.getAllCodePaths();
10393                } catch (PackageParserException e) {
10394                    // Ignored; we tried our best
10395                }
10396            }
10397            return Collections.EMPTY_LIST;
10398        }
10399
10400        void cleanUpResourcesLI() {
10401            // Enumerate all code paths before deleting
10402            cleanUpResourcesLI(getAllCodePaths());
10403        }
10404
10405        private void cleanUpResourcesLI(List<String> allCodePaths) {
10406            cleanUp();
10407            removeDexFiles(allCodePaths, instructionSets);
10408        }
10409
10410
10411
10412        String getPackageName() {
10413            return getAsecPackageName(cid);
10414        }
10415
10416        boolean doPostDeleteLI(boolean delete) {
10417            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10418            final List<String> allCodePaths = getAllCodePaths();
10419            boolean mounted = PackageHelper.isContainerMounted(cid);
10420            if (mounted) {
10421                // Unmount first
10422                if (PackageHelper.unMountSdDir(cid)) {
10423                    mounted = false;
10424                }
10425            }
10426            if (!mounted && delete) {
10427                cleanUpResourcesLI(allCodePaths);
10428            }
10429            return !mounted;
10430        }
10431
10432        @Override
10433        int doPreCopy() {
10434            if (isFwdLocked()) {
10435                if (!PackageHelper.fixSdPermissions(cid,
10436                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10437                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10438                }
10439            }
10440
10441            return PackageManager.INSTALL_SUCCEEDED;
10442        }
10443
10444        @Override
10445        int doPostCopy(int uid) {
10446            if (isFwdLocked()) {
10447                if (uid < Process.FIRST_APPLICATION_UID
10448                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10449                                RES_FILE_NAME)) {
10450                    Slog.e(TAG, "Failed to finalize " + cid);
10451                    PackageHelper.destroySdDir(cid);
10452                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10453                }
10454            }
10455
10456            return PackageManager.INSTALL_SUCCEEDED;
10457        }
10458    }
10459
10460    static String getAsecPackageName(String packageCid) {
10461        int idx = packageCid.lastIndexOf("-");
10462        if (idx == -1) {
10463            return packageCid;
10464        }
10465        return packageCid.substring(0, idx);
10466    }
10467
10468    // Utility method used to create code paths based on package name and available index.
10469    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
10470        String idxStr = "";
10471        int idx = 1;
10472        // Fall back to default value of idx=1 if prefix is not
10473        // part of oldCodePath
10474        if (oldCodePath != null) {
10475            String subStr = oldCodePath;
10476            // Drop the suffix right away
10477            if (suffix != null && subStr.endsWith(suffix)) {
10478                subStr = subStr.substring(0, subStr.length() - suffix.length());
10479            }
10480            // If oldCodePath already contains prefix find out the
10481            // ending index to either increment or decrement.
10482            int sidx = subStr.lastIndexOf(prefix);
10483            if (sidx != -1) {
10484                subStr = subStr.substring(sidx + prefix.length());
10485                if (subStr != null) {
10486                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10487                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10488                    }
10489                    try {
10490                        idx = Integer.parseInt(subStr);
10491                        if (idx <= 1) {
10492                            idx++;
10493                        } else {
10494                            idx--;
10495                        }
10496                    } catch(NumberFormatException e) {
10497                    }
10498                }
10499            }
10500        }
10501        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10502        return prefix + idxStr;
10503    }
10504
10505    private File getNextCodePath(File targetDir, String packageName) {
10506        int suffix = 1;
10507        File result;
10508        do {
10509            result = new File(targetDir, packageName + "-" + suffix);
10510            suffix++;
10511        } while (result.exists());
10512        return result;
10513    }
10514
10515    // Utility method that returns the relative package path with respect
10516    // to the installation directory. Like say for /data/data/com.test-1.apk
10517    // string com.test-1 is returned.
10518    static String deriveCodePathName(String codePath) {
10519        if (codePath == null) {
10520            return null;
10521        }
10522        final File codeFile = new File(codePath);
10523        final String name = codeFile.getName();
10524        if (codeFile.isDirectory()) {
10525            return name;
10526        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10527            final int lastDot = name.lastIndexOf('.');
10528            return name.substring(0, lastDot);
10529        } else {
10530            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10531            return null;
10532        }
10533    }
10534
10535    class PackageInstalledInfo {
10536        String name;
10537        int uid;
10538        // The set of users that originally had this package installed.
10539        int[] origUsers;
10540        // The set of users that now have this package installed.
10541        int[] newUsers;
10542        PackageParser.Package pkg;
10543        int returnCode;
10544        String returnMsg;
10545        PackageRemovedInfo removedInfo;
10546
10547        public void setError(int code, String msg) {
10548            returnCode = code;
10549            returnMsg = msg;
10550            Slog.w(TAG, msg);
10551        }
10552
10553        public void setError(String msg, PackageParserException e) {
10554            returnCode = e.error;
10555            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10556            Slog.w(TAG, msg, e);
10557        }
10558
10559        public void setError(String msg, PackageManagerException e) {
10560            returnCode = e.error;
10561            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10562            Slog.w(TAG, msg, e);
10563        }
10564
10565        // In some error cases we want to convey more info back to the observer
10566        String origPackage;
10567        String origPermission;
10568    }
10569
10570    /*
10571     * Install a non-existing package.
10572     */
10573    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
10574            UserHandle user, String installerPackageName, String volumeUuid,
10575            PackageInstalledInfo res) {
10576        // Remember this for later, in case we need to rollback this install
10577        String pkgName = pkg.packageName;
10578
10579        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10580        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
10581        synchronized(mPackages) {
10582            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10583                // A package with the same name is already installed, though
10584                // it has been renamed to an older name.  The package we
10585                // are trying to install should be installed as an update to
10586                // the existing one, but that has not been requested, so bail.
10587                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10588                        + " without first uninstalling package running as "
10589                        + mSettings.mRenamedPackages.get(pkgName));
10590                return;
10591            }
10592            if (mPackages.containsKey(pkgName)) {
10593                // Don't allow installation over an existing package with the same name.
10594                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10595                        + " without first uninstalling.");
10596                return;
10597            }
10598        }
10599
10600        try {
10601            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10602                    System.currentTimeMillis(), user);
10603
10604            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
10605            // delete the partially installed application. the data directory will have to be
10606            // restored if it was already existing
10607            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10608                // remove package from internal structures.  Note that we want deletePackageX to
10609                // delete the package data and cache directories that it created in
10610                // scanPackageLocked, unless those directories existed before we even tried to
10611                // install.
10612                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10613                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10614                                res.removedInfo, true);
10615            }
10616
10617        } catch (PackageManagerException e) {
10618            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10619        }
10620    }
10621
10622    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10623        // Upgrade keysets are being used.  Determine if new package has a superset of the
10624        // required keys.
10625        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10626        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10627        for (int i = 0; i < upgradeKeySets.length; i++) {
10628            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10629            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10630                return true;
10631            }
10632        }
10633        return false;
10634    }
10635
10636    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
10637            UserHandle user, String installerPackageName, String volumeUuid,
10638            PackageInstalledInfo res) {
10639        PackageParser.Package oldPackage;
10640        String pkgName = pkg.packageName;
10641        int[] allUsers;
10642        boolean[] perUserInstalled;
10643
10644        // First find the old package info and check signatures
10645        synchronized(mPackages) {
10646            oldPackage = mPackages.get(pkgName);
10647            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10648            PackageSetting ps = mSettings.mPackages.get(pkgName);
10649            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10650                // default to original signature matching
10651                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10652                    != PackageManager.SIGNATURE_MATCH) {
10653                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10654                            "New package has a different signature: " + pkgName);
10655                    return;
10656                }
10657            } else {
10658                if(!checkUpgradeKeySetLP(ps, pkg)) {
10659                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10660                            "New package not signed by keys specified by upgrade-keysets: "
10661                            + pkgName);
10662                    return;
10663                }
10664            }
10665
10666            // In case of rollback, remember per-user/profile install state
10667            allUsers = sUserManager.getUserIds();
10668            perUserInstalled = new boolean[allUsers.length];
10669            for (int i = 0; i < allUsers.length; i++) {
10670                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10671            }
10672        }
10673
10674        boolean sysPkg = (isSystemApp(oldPackage));
10675        if (sysPkg) {
10676            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10677                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
10678        } else {
10679            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10680                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
10681        }
10682    }
10683
10684    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10685            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10686            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
10687            String volumeUuid, PackageInstalledInfo res) {
10688        String pkgName = deletedPackage.packageName;
10689        boolean deletedPkg = true;
10690        boolean updatedSettings = false;
10691
10692        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10693                + deletedPackage);
10694        long origUpdateTime;
10695        if (pkg.mExtras != null) {
10696            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10697        } else {
10698            origUpdateTime = 0;
10699        }
10700
10701        // First delete the existing package while retaining the data directory
10702        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10703                res.removedInfo, true)) {
10704            // If the existing package wasn't successfully deleted
10705            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10706            deletedPkg = false;
10707        } else {
10708            // Successfully deleted the old package; proceed with replace.
10709
10710            // If deleted package lived in a container, give users a chance to
10711            // relinquish resources before killing.
10712            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
10713                if (DEBUG_INSTALL) {
10714                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10715                }
10716                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10717                final ArrayList<String> pkgList = new ArrayList<String>(1);
10718                pkgList.add(deletedPackage.applicationInfo.packageName);
10719                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10720            }
10721
10722            deleteCodeCacheDirsLI(pkgName);
10723            try {
10724                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10725                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10726                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
10727                        perUserInstalled, res, user);
10728                updatedSettings = true;
10729            } catch (PackageManagerException e) {
10730                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10731            }
10732        }
10733
10734        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10735            // remove package from internal structures.  Note that we want deletePackageX to
10736            // delete the package data and cache directories that it created in
10737            // scanPackageLocked, unless those directories existed before we even tried to
10738            // install.
10739            if(updatedSettings) {
10740                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10741                deletePackageLI(
10742                        pkgName, null, true, allUsers, perUserInstalled,
10743                        PackageManager.DELETE_KEEP_DATA,
10744                                res.removedInfo, true);
10745            }
10746            // Since we failed to install the new package we need to restore the old
10747            // package that we deleted.
10748            if (deletedPkg) {
10749                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10750                File restoreFile = new File(deletedPackage.codePath);
10751                // Parse old package
10752                boolean oldExternal = isExternal(deletedPackage);
10753                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10754                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10755                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
10756                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10757                try {
10758                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10759                } catch (PackageManagerException e) {
10760                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10761                            + e.getMessage());
10762                    return;
10763                }
10764                // Restore of old package succeeded. Update permissions.
10765                // writer
10766                synchronized (mPackages) {
10767                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10768                            UPDATE_PERMISSIONS_ALL);
10769                    // can downgrade to reader
10770                    mSettings.writeLPr();
10771                }
10772                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10773            }
10774        }
10775    }
10776
10777    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10778            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10779            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
10780            String volumeUuid, PackageInstalledInfo res) {
10781        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10782                + ", old=" + deletedPackage);
10783        boolean disabledSystem = false;
10784        boolean updatedSettings = false;
10785        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10786        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
10787                != 0) {
10788            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10789        }
10790        String packageName = deletedPackage.packageName;
10791        if (packageName == null) {
10792            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10793                    "Attempt to delete null packageName.");
10794            return;
10795        }
10796        PackageParser.Package oldPkg;
10797        PackageSetting oldPkgSetting;
10798        // reader
10799        synchronized (mPackages) {
10800            oldPkg = mPackages.get(packageName);
10801            oldPkgSetting = mSettings.mPackages.get(packageName);
10802            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10803                    (oldPkgSetting == null)) {
10804                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10805                        "Couldn't find package:" + packageName + " information");
10806                return;
10807            }
10808        }
10809
10810        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10811
10812        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10813        res.removedInfo.removedPackage = packageName;
10814        // Remove existing system package
10815        removePackageLI(oldPkgSetting, true);
10816        // writer
10817        synchronized (mPackages) {
10818            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10819            if (!disabledSystem && deletedPackage != null) {
10820                // We didn't need to disable the .apk as a current system package,
10821                // which means we are replacing another update that is already
10822                // installed.  We need to make sure to delete the older one's .apk.
10823                res.removedInfo.args = createInstallArgsForExisting(0,
10824                        deletedPackage.applicationInfo.getCodePath(),
10825                        deletedPackage.applicationInfo.getResourcePath(),
10826                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10827                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10828            } else {
10829                res.removedInfo.args = null;
10830            }
10831        }
10832
10833        // Successfully disabled the old package. Now proceed with re-installation
10834        deleteCodeCacheDirsLI(packageName);
10835
10836        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10837        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10838
10839        PackageParser.Package newPackage = null;
10840        try {
10841            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10842            if (newPackage.mExtras != null) {
10843                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10844                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10845                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10846
10847                // is the update attempting to change shared user? that isn't going to work...
10848                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10849                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10850                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10851                            + " to " + newPkgSetting.sharedUser);
10852                    updatedSettings = true;
10853                }
10854            }
10855
10856            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10857                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
10858                        perUserInstalled, res, user);
10859                updatedSettings = true;
10860            }
10861
10862        } catch (PackageManagerException e) {
10863            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10864        }
10865
10866        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10867            // Re installation failed. Restore old information
10868            // Remove new pkg information
10869            if (newPackage != null) {
10870                removeInstalledPackageLI(newPackage, true);
10871            }
10872            // Add back the old system package
10873            try {
10874                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10875            } catch (PackageManagerException e) {
10876                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10877            }
10878            // Restore the old system information in Settings
10879            synchronized (mPackages) {
10880                if (disabledSystem) {
10881                    mSettings.enableSystemPackageLPw(packageName);
10882                }
10883                if (updatedSettings) {
10884                    mSettings.setInstallerPackageName(packageName,
10885                            oldPkgSetting.installerPackageName);
10886                }
10887                mSettings.writeLPr();
10888            }
10889        }
10890    }
10891
10892    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10893            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
10894            UserHandle user) {
10895        String pkgName = newPackage.packageName;
10896        synchronized (mPackages) {
10897            //write settings. the installStatus will be incomplete at this stage.
10898            //note that the new package setting would have already been
10899            //added to mPackages. It hasn't been persisted yet.
10900            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10901            mSettings.writeLPr();
10902        }
10903
10904        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10905
10906        synchronized (mPackages) {
10907            updatePermissionsLPw(newPackage.packageName, newPackage,
10908                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10909                            ? UPDATE_PERMISSIONS_ALL : 0));
10910            // For system-bundled packages, we assume that installing an upgraded version
10911            // of the package implies that the user actually wants to run that new code,
10912            // so we enable the package.
10913            PackageSetting ps = mSettings.mPackages.get(pkgName);
10914            if (ps != null) {
10915                if (isSystemApp(newPackage)) {
10916                    // NB: implicit assumption that system package upgrades apply to all users
10917                    if (DEBUG_INSTALL) {
10918                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10919                    }
10920                    if (res.origUsers != null) {
10921                        for (int userHandle : res.origUsers) {
10922                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10923                                    userHandle, installerPackageName);
10924                        }
10925                    }
10926                    // Also convey the prior install/uninstall state
10927                    if (allUsers != null && perUserInstalled != null) {
10928                        for (int i = 0; i < allUsers.length; i++) {
10929                            if (DEBUG_INSTALL) {
10930                                Slog.d(TAG, "    user " + allUsers[i]
10931                                        + " => " + perUserInstalled[i]);
10932                            }
10933                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10934                        }
10935                        // these install state changes will be persisted in the
10936                        // upcoming call to mSettings.writeLPr().
10937                    }
10938                }
10939                // It's implied that when a user requests installation, they want the app to be
10940                // installed and enabled.
10941                int userId = user.getIdentifier();
10942                if (userId != UserHandle.USER_ALL) {
10943                    ps.setInstalled(true, userId);
10944                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
10945                }
10946            }
10947            res.name = pkgName;
10948            res.uid = newPackage.applicationInfo.uid;
10949            res.pkg = newPackage;
10950            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10951            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10952            mSettings.setVolumeUuid(pkgName, volumeUuid);
10953            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10954            //to update install status
10955            mSettings.writeLPr();
10956        }
10957    }
10958
10959    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10960        final int installFlags = args.installFlags;
10961        final String installerPackageName = args.installerPackageName;
10962        final String volumeUuid = args.volumeUuid;
10963        final File tmpPackageFile = new File(args.getCodePath());
10964        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10965        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
10966                || (args.volumeUuid != null));
10967        boolean replace = false;
10968        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10969        // Result object to be returned
10970        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10971
10972        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10973        // Retrieve PackageSettings and parse package
10974        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10975                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10976                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
10977        PackageParser pp = new PackageParser();
10978        pp.setSeparateProcesses(mSeparateProcesses);
10979        pp.setDisplayMetrics(mMetrics);
10980
10981        final PackageParser.Package pkg;
10982        try {
10983            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10984        } catch (PackageParserException e) {
10985            res.setError("Failed parse during installPackageLI", e);
10986            return;
10987        }
10988
10989        // Mark that we have an install time CPU ABI override.
10990        pkg.cpuAbiOverride = args.abiOverride;
10991
10992        String pkgName = res.name = pkg.packageName;
10993        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10994            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10995                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10996                return;
10997            }
10998        }
10999
11000        try {
11001            pp.collectCertificates(pkg, parseFlags);
11002            pp.collectManifestDigest(pkg);
11003        } catch (PackageParserException e) {
11004            res.setError("Failed collect during installPackageLI", e);
11005            return;
11006        }
11007
11008        /* If the installer passed in a manifest digest, compare it now. */
11009        if (args.manifestDigest != null) {
11010            if (DEBUG_INSTALL) {
11011                final String parsedManifest = pkg.manifestDigest == null ? "null"
11012                        : pkg.manifestDigest.toString();
11013                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11014                        + parsedManifest);
11015            }
11016
11017            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11018                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11019                return;
11020            }
11021        } else if (DEBUG_INSTALL) {
11022            final String parsedManifest = pkg.manifestDigest == null
11023                    ? "null" : pkg.manifestDigest.toString();
11024            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11025        }
11026
11027        // Get rid of all references to package scan path via parser.
11028        pp = null;
11029        String oldCodePath = null;
11030        boolean systemApp = false;
11031        synchronized (mPackages) {
11032            // Check if installing already existing package
11033            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11034                String oldName = mSettings.mRenamedPackages.get(pkgName);
11035                if (pkg.mOriginalPackages != null
11036                        && pkg.mOriginalPackages.contains(oldName)
11037                        && mPackages.containsKey(oldName)) {
11038                    // This package is derived from an original package,
11039                    // and this device has been updating from that original
11040                    // name.  We must continue using the original name, so
11041                    // rename the new package here.
11042                    pkg.setPackageName(oldName);
11043                    pkgName = pkg.packageName;
11044                    replace = true;
11045                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11046                            + oldName + " pkgName=" + pkgName);
11047                } else if (mPackages.containsKey(pkgName)) {
11048                    // This package, under its official name, already exists
11049                    // on the device; we should replace it.
11050                    replace = true;
11051                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11052                }
11053            }
11054
11055            PackageSetting ps = mSettings.mPackages.get(pkgName);
11056            if (ps != null) {
11057                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11058
11059                // Quick sanity check that we're signed correctly if updating;
11060                // we'll check this again later when scanning, but we want to
11061                // bail early here before tripping over redefined permissions.
11062                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11063                    try {
11064                        verifySignaturesLP(ps, pkg);
11065                    } catch (PackageManagerException e) {
11066                        res.setError(e.error, e.getMessage());
11067                        return;
11068                    }
11069                } else {
11070                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11071                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11072                                + pkg.packageName + " upgrade keys do not match the "
11073                                + "previously installed version");
11074                        return;
11075                    }
11076                }
11077
11078                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11079                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11080                    systemApp = (ps.pkg.applicationInfo.flags &
11081                            ApplicationInfo.FLAG_SYSTEM) != 0;
11082                }
11083                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11084            }
11085
11086            // Check whether the newly-scanned package wants to define an already-defined perm
11087            int N = pkg.permissions.size();
11088            for (int i = N-1; i >= 0; i--) {
11089                PackageParser.Permission perm = pkg.permissions.get(i);
11090                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11091                if (bp != null) {
11092                    // If the defining package is signed with our cert, it's okay.  This
11093                    // also includes the "updating the same package" case, of course.
11094                    // "updating same package" could also involve key-rotation.
11095                    final boolean sigsOk;
11096                    if (!bp.sourcePackage.equals(pkg.packageName)
11097                            || !(bp.packageSetting instanceof PackageSetting)
11098                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
11099                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
11100                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11101                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11102                    } else {
11103                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11104                    }
11105                    if (!sigsOk) {
11106                        // If the owning package is the system itself, we log but allow
11107                        // install to proceed; we fail the install on all other permission
11108                        // redefinitions.
11109                        if (!bp.sourcePackage.equals("android")) {
11110                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11111                                    + pkg.packageName + " attempting to redeclare permission "
11112                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11113                            res.origPermission = perm.info.name;
11114                            res.origPackage = bp.sourcePackage;
11115                            return;
11116                        } else {
11117                            Slog.w(TAG, "Package " + pkg.packageName
11118                                    + " attempting to redeclare system permission "
11119                                    + perm.info.name + "; ignoring new declaration");
11120                            pkg.permissions.remove(i);
11121                        }
11122                    }
11123                }
11124            }
11125
11126        }
11127
11128        if (systemApp && onExternal) {
11129            // Disable updates to system apps on sdcard
11130            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11131                    "Cannot install updates to system apps on sdcard");
11132            return;
11133        }
11134
11135        // Run dexopt before old package gets removed, to minimize time when app is not available
11136        int result = mPackageDexOptimizer
11137                .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */,
11138                        false /* defer */, false /* inclDependencies */);
11139        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11140            res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11141            return;
11142        }
11143
11144        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11145            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11146            return;
11147        }
11148
11149        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11150
11151        if (replace) {
11152            // Call replacePackageLI with SCAN_NO_DEX, since we already made dexopt
11153            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING | SCAN_NO_DEX, args.user,
11154                    installerPackageName, volumeUuid, res);
11155        } else {
11156            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11157                    args.user, installerPackageName, volumeUuid, res);
11158        }
11159        synchronized (mPackages) {
11160            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11161            if (ps != null) {
11162                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11163            }
11164        }
11165    }
11166
11167    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11168        if (mIntentFilterVerifierComponent == null) {
11169            Slog.d(TAG, "No IntentFilter verification will not be done as "
11170                    + "there is no IntentFilterVerifier available!");
11171            return;
11172        }
11173
11174        final int verifierUid = getPackageUid(
11175                mIntentFilterVerifierComponent.getPackageName(),
11176                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11177
11178        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11179        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11180        msg.obj = pkg;
11181        msg.arg1 = userId;
11182        msg.arg2 = verifierUid;
11183
11184        mHandler.sendMessage(msg);
11185    }
11186
11187    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11188                                             PackageParser.Package pkg) {
11189        int size = pkg.activities.size();
11190        if (size == 0) {
11191            Slog.d(TAG, "No activity, so no need to verify any IntentFilter!");
11192            return;
11193        }
11194
11195        Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size
11196                + " Activities needs verification ...");
11197
11198        final int verificationId = mIntentFilterVerificationToken++;
11199        int count = 0;
11200        synchronized (mPackages) {
11201            for (PackageParser.Activity a : pkg.activities) {
11202                for (ActivityIntentInfo filter : a.intents) {
11203                    boolean needFilterVerification = filter.needsVerification() &&
11204                            !filter.isVerified();
11205                    if (needFilterVerification && needNetworkVerificationLPr(filter)) {
11206                        Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString());
11207                        mIntentFilterVerifier.addOneIntentFilterVerification(
11208                                verifierUid, userId, verificationId, filter, pkg.packageName);
11209                        count++;
11210                    } else {
11211                        Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString());
11212                    }
11213                }
11214            }
11215        }
11216
11217        if (count > 0) {
11218            mIntentFilterVerifier.startVerifications(userId);
11219            Slog.d(TAG, "Started " + count + " IntentFilter verification"
11220                    + (count > 1 ? "s" : "") +  " for userId:" + userId + "!");
11221        } else {
11222            Slog.d(TAG, "No need to start any IntentFilter verification!");
11223        }
11224    }
11225
11226    private boolean needNetworkVerificationLPr(ActivityIntentInfo filter) {
11227        final ComponentName cn  = filter.activity.getComponentName();
11228        final String packageName = cn.getPackageName();
11229
11230        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11231                packageName);
11232        if (ivi == null) {
11233            return true;
11234        }
11235        int status = ivi.getStatus();
11236        switch (status) {
11237            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11238            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11239                return true;
11240
11241            default:
11242                // Nothing to do
11243                return false;
11244        }
11245    }
11246
11247    private static boolean isMultiArch(PackageSetting ps) {
11248        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11249    }
11250
11251    private static boolean isMultiArch(ApplicationInfo info) {
11252        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11253    }
11254
11255    private static boolean isExternal(PackageParser.Package pkg) {
11256        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11257    }
11258
11259    private static boolean isExternal(PackageSetting ps) {
11260        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11261    }
11262
11263    private static boolean isExternal(ApplicationInfo info) {
11264        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11265    }
11266
11267    private static boolean isSystemApp(PackageParser.Package pkg) {
11268        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11269    }
11270
11271    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11272        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11273    }
11274
11275    private static boolean isSystemApp(PackageSetting ps) {
11276        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11277    }
11278
11279    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11280        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11281    }
11282
11283    private int packageFlagsToInstallFlags(PackageSetting ps) {
11284        int installFlags = 0;
11285        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11286            // This existing package was an external ASEC install when we have
11287            // the external flag without a UUID
11288            installFlags |= PackageManager.INSTALL_EXTERNAL;
11289        }
11290        if (ps.isForwardLocked()) {
11291            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11292        }
11293        return installFlags;
11294    }
11295
11296    private void deleteTempPackageFiles() {
11297        final FilenameFilter filter = new FilenameFilter() {
11298            public boolean accept(File dir, String name) {
11299                return name.startsWith("vmdl") && name.endsWith(".tmp");
11300            }
11301        };
11302        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11303            file.delete();
11304        }
11305    }
11306
11307    @Override
11308    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11309            int flags) {
11310        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11311                flags);
11312    }
11313
11314    @Override
11315    public void deletePackage(final String packageName,
11316            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11317        mContext.enforceCallingOrSelfPermission(
11318                android.Manifest.permission.DELETE_PACKAGES, null);
11319        final int uid = Binder.getCallingUid();
11320        if (UserHandle.getUserId(uid) != userId) {
11321            mContext.enforceCallingPermission(
11322                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11323                    "deletePackage for user " + userId);
11324        }
11325        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11326            try {
11327                observer.onPackageDeleted(packageName,
11328                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11329            } catch (RemoteException re) {
11330            }
11331            return;
11332        }
11333
11334        boolean uninstallBlocked = false;
11335        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11336            int[] users = sUserManager.getUserIds();
11337            for (int i = 0; i < users.length; ++i) {
11338                if (getBlockUninstallForUser(packageName, users[i])) {
11339                    uninstallBlocked = true;
11340                    break;
11341                }
11342            }
11343        } else {
11344            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11345        }
11346        if (uninstallBlocked) {
11347            try {
11348                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11349                        null);
11350            } catch (RemoteException re) {
11351            }
11352            return;
11353        }
11354
11355        if (DEBUG_REMOVE) {
11356            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
11357        }
11358        // Queue up an async operation since the package deletion may take a little while.
11359        mHandler.post(new Runnable() {
11360            public void run() {
11361                mHandler.removeCallbacks(this);
11362                final int returnCode = deletePackageX(packageName, userId, flags);
11363                if (observer != null) {
11364                    try {
11365                        observer.onPackageDeleted(packageName, returnCode, null);
11366                    } catch (RemoteException e) {
11367                        Log.i(TAG, "Observer no longer exists.");
11368                    } //end catch
11369                } //end if
11370            } //end run
11371        });
11372    }
11373
11374    private boolean isPackageDeviceAdmin(String packageName, int userId) {
11375        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
11376                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
11377        try {
11378            if (dpm != null) {
11379                if (dpm.isDeviceOwner(packageName)) {
11380                    return true;
11381                }
11382                int[] users;
11383                if (userId == UserHandle.USER_ALL) {
11384                    users = sUserManager.getUserIds();
11385                } else {
11386                    users = new int[]{userId};
11387                }
11388                for (int i = 0; i < users.length; ++i) {
11389                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
11390                        return true;
11391                    }
11392                }
11393            }
11394        } catch (RemoteException e) {
11395        }
11396        return false;
11397    }
11398
11399    /**
11400     *  This method is an internal method that could be get invoked either
11401     *  to delete an installed package or to clean up a failed installation.
11402     *  After deleting an installed package, a broadcast is sent to notify any
11403     *  listeners that the package has been installed. For cleaning up a failed
11404     *  installation, the broadcast is not necessary since the package's
11405     *  installation wouldn't have sent the initial broadcast either
11406     *  The key steps in deleting a package are
11407     *  deleting the package information in internal structures like mPackages,
11408     *  deleting the packages base directories through installd
11409     *  updating mSettings to reflect current status
11410     *  persisting settings for later use
11411     *  sending a broadcast if necessary
11412     */
11413    private int deletePackageX(String packageName, int userId, int flags) {
11414        final PackageRemovedInfo info = new PackageRemovedInfo();
11415        final boolean res;
11416
11417        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
11418                ? UserHandle.ALL : new UserHandle(userId);
11419
11420        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
11421            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
11422            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
11423        }
11424
11425        boolean removedForAllUsers = false;
11426        boolean systemUpdate = false;
11427
11428        // for the uninstall-updates case and restricted profiles, remember the per-
11429        // userhandle installed state
11430        int[] allUsers;
11431        boolean[] perUserInstalled;
11432        synchronized (mPackages) {
11433            PackageSetting ps = mSettings.mPackages.get(packageName);
11434            allUsers = sUserManager.getUserIds();
11435            perUserInstalled = new boolean[allUsers.length];
11436            for (int i = 0; i < allUsers.length; i++) {
11437                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11438            }
11439        }
11440
11441        synchronized (mInstallLock) {
11442            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
11443            res = deletePackageLI(packageName, removeForUser,
11444                    true, allUsers, perUserInstalled,
11445                    flags | REMOVE_CHATTY, info, true);
11446            systemUpdate = info.isRemovedPackageSystemUpdate;
11447            if (res && !systemUpdate && mPackages.get(packageName) == null) {
11448                removedForAllUsers = true;
11449            }
11450            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
11451                    + " removedForAllUsers=" + removedForAllUsers);
11452        }
11453
11454        if (res) {
11455            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
11456
11457            // If the removed package was a system update, the old system package
11458            // was re-enabled; we need to broadcast this information
11459            if (systemUpdate) {
11460                Bundle extras = new Bundle(1);
11461                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
11462                        ? info.removedAppId : info.uid);
11463                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11464
11465                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
11466                        extras, null, null, null);
11467                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
11468                        extras, null, null, null);
11469                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
11470                        null, packageName, null, null);
11471            }
11472        }
11473        // Force a gc here.
11474        Runtime.getRuntime().gc();
11475        // Delete the resources here after sending the broadcast to let
11476        // other processes clean up before deleting resources.
11477        if (info.args != null) {
11478            synchronized (mInstallLock) {
11479                info.args.doPostDeleteLI(true);
11480            }
11481        }
11482
11483        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
11484    }
11485
11486    static class PackageRemovedInfo {
11487        String removedPackage;
11488        int uid = -1;
11489        int removedAppId = -1;
11490        int[] removedUsers = null;
11491        boolean isRemovedPackageSystemUpdate = false;
11492        // Clean up resources deleted packages.
11493        InstallArgs args = null;
11494
11495        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
11496            Bundle extras = new Bundle(1);
11497            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
11498            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
11499            if (replacing) {
11500                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11501            }
11502            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
11503            if (removedPackage != null) {
11504                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
11505                        extras, null, null, removedUsers);
11506                if (fullRemove && !replacing) {
11507                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
11508                            extras, null, null, removedUsers);
11509                }
11510            }
11511            if (removedAppId >= 0) {
11512                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
11513                        removedUsers);
11514            }
11515        }
11516    }
11517
11518    /*
11519     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
11520     * flag is not set, the data directory is removed as well.
11521     * make sure this flag is set for partially installed apps. If not its meaningless to
11522     * delete a partially installed application.
11523     */
11524    private void removePackageDataLI(PackageSetting ps,
11525            int[] allUserHandles, boolean[] perUserInstalled,
11526            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
11527        String packageName = ps.name;
11528        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
11529        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
11530        // Retrieve object to delete permissions for shared user later on
11531        final PackageSetting deletedPs;
11532        // reader
11533        synchronized (mPackages) {
11534            deletedPs = mSettings.mPackages.get(packageName);
11535            if (outInfo != null) {
11536                outInfo.removedPackage = packageName;
11537                outInfo.removedUsers = deletedPs != null
11538                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
11539                        : null;
11540            }
11541        }
11542        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11543            removeDataDirsLI(packageName);
11544            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
11545        }
11546        // writer
11547        synchronized (mPackages) {
11548            if (deletedPs != null) {
11549                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11550                    if (outInfo != null) {
11551                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
11552                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
11553                    }
11554                    updatePermissionsLPw(deletedPs.name, null, 0);
11555                    if (deletedPs.sharedUser != null) {
11556                        // Remove permissions associated with package. Since runtime
11557                        // permissions are per user we have to kill the removed package
11558                        // or packages running under the shared user of the removed
11559                        // package if revoking the permissions requested only by the removed
11560                        // package is successful and this causes a change in gids.
11561                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11562                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
11563                                    userId);
11564                            if (userIdToKill == UserHandle.USER_ALL
11565                                    || userIdToKill >= UserHandle.USER_OWNER) {
11566                                // If gids changed for this user, kill all affected packages.
11567                                mHandler.post(new Runnable() {
11568                                    @Override
11569                                    public void run() {
11570                                        // This has to happen with no lock held.
11571                                        killSettingPackagesForUser(deletedPs, userIdToKill,
11572                                                KILL_APP_REASON_GIDS_CHANGED);
11573                                    }
11574                                });
11575                            break;
11576                            }
11577                        }
11578                    }
11579                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
11580                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
11581                }
11582                // make sure to preserve per-user disabled state if this removal was just
11583                // a downgrade of a system app to the factory package
11584                if (allUserHandles != null && perUserInstalled != null) {
11585                    if (DEBUG_REMOVE) {
11586                        Slog.d(TAG, "Propagating install state across downgrade");
11587                    }
11588                    for (int i = 0; i < allUserHandles.length; i++) {
11589                        if (DEBUG_REMOVE) {
11590                            Slog.d(TAG, "    user " + allUserHandles[i]
11591                                    + " => " + perUserInstalled[i]);
11592                        }
11593                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11594                    }
11595                }
11596            }
11597            // can downgrade to reader
11598            if (writeSettings) {
11599                // Save settings now
11600                mSettings.writeLPr();
11601            }
11602        }
11603        if (outInfo != null) {
11604            // A user ID was deleted here. Go through all users and remove it
11605            // from KeyStore.
11606            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
11607        }
11608    }
11609
11610    static boolean locationIsPrivileged(File path) {
11611        try {
11612            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
11613                    .getCanonicalPath();
11614            return path.getCanonicalPath().startsWith(privilegedAppDir);
11615        } catch (IOException e) {
11616            Slog.e(TAG, "Unable to access code path " + path);
11617        }
11618        return false;
11619    }
11620
11621    /*
11622     * Tries to delete system package.
11623     */
11624    private boolean deleteSystemPackageLI(PackageSetting newPs,
11625            int[] allUserHandles, boolean[] perUserInstalled,
11626            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
11627        final boolean applyUserRestrictions
11628                = (allUserHandles != null) && (perUserInstalled != null);
11629        PackageSetting disabledPs = null;
11630        // Confirm if the system package has been updated
11631        // An updated system app can be deleted. This will also have to restore
11632        // the system pkg from system partition
11633        // reader
11634        synchronized (mPackages) {
11635            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
11636        }
11637        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
11638                + " disabledPs=" + disabledPs);
11639        if (disabledPs == null) {
11640            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
11641            return false;
11642        } else if (DEBUG_REMOVE) {
11643            Slog.d(TAG, "Deleting system pkg from data partition");
11644        }
11645        if (DEBUG_REMOVE) {
11646            if (applyUserRestrictions) {
11647                Slog.d(TAG, "Remembering install states:");
11648                for (int i = 0; i < allUserHandles.length; i++) {
11649                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
11650                }
11651            }
11652        }
11653        // Delete the updated package
11654        outInfo.isRemovedPackageSystemUpdate = true;
11655        if (disabledPs.versionCode < newPs.versionCode) {
11656            // Delete data for downgrades
11657            flags &= ~PackageManager.DELETE_KEEP_DATA;
11658        } else {
11659            // Preserve data by setting flag
11660            flags |= PackageManager.DELETE_KEEP_DATA;
11661        }
11662        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
11663                allUserHandles, perUserInstalled, outInfo, writeSettings);
11664        if (!ret) {
11665            return false;
11666        }
11667        // writer
11668        synchronized (mPackages) {
11669            // Reinstate the old system package
11670            mSettings.enableSystemPackageLPw(newPs.name);
11671            // Remove any native libraries from the upgraded package.
11672            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
11673        }
11674        // Install the system package
11675        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
11676        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
11677        if (locationIsPrivileged(disabledPs.codePath)) {
11678            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11679        }
11680
11681        final PackageParser.Package newPkg;
11682        try {
11683            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
11684        } catch (PackageManagerException e) {
11685            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
11686            return false;
11687        }
11688
11689        // writer
11690        synchronized (mPackages) {
11691            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
11692            updatePermissionsLPw(newPkg.packageName, newPkg,
11693                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
11694            if (applyUserRestrictions) {
11695                if (DEBUG_REMOVE) {
11696                    Slog.d(TAG, "Propagating install state across reinstall");
11697                }
11698                for (int i = 0; i < allUserHandles.length; i++) {
11699                    if (DEBUG_REMOVE) {
11700                        Slog.d(TAG, "    user " + allUserHandles[i]
11701                                + " => " + perUserInstalled[i]);
11702                    }
11703                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11704                }
11705                // Regardless of writeSettings we need to ensure that this restriction
11706                // state propagation is persisted
11707                mSettings.writeAllUsersPackageRestrictionsLPr();
11708            }
11709            // can downgrade to reader here
11710            if (writeSettings) {
11711                mSettings.writeLPr();
11712            }
11713        }
11714        return true;
11715    }
11716
11717    private boolean deleteInstalledPackageLI(PackageSetting ps,
11718            boolean deleteCodeAndResources, int flags,
11719            int[] allUserHandles, boolean[] perUserInstalled,
11720            PackageRemovedInfo outInfo, boolean writeSettings) {
11721        if (outInfo != null) {
11722            outInfo.uid = ps.appId;
11723        }
11724
11725        // Delete package data from internal structures and also remove data if flag is set
11726        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
11727
11728        // Delete application code and resources
11729        if (deleteCodeAndResources && (outInfo != null)) {
11730            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
11731                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
11732                    getAppDexInstructionSets(ps));
11733            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
11734        }
11735        return true;
11736    }
11737
11738    @Override
11739    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
11740            int userId) {
11741        mContext.enforceCallingOrSelfPermission(
11742                android.Manifest.permission.DELETE_PACKAGES, null);
11743        synchronized (mPackages) {
11744            PackageSetting ps = mSettings.mPackages.get(packageName);
11745            if (ps == null) {
11746                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
11747                return false;
11748            }
11749            if (!ps.getInstalled(userId)) {
11750                // Can't block uninstall for an app that is not installed or enabled.
11751                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11752                return false;
11753            }
11754            ps.setBlockUninstall(blockUninstall, userId);
11755            mSettings.writePackageRestrictionsLPr(userId);
11756        }
11757        return true;
11758    }
11759
11760    @Override
11761    public boolean getBlockUninstallForUser(String packageName, int userId) {
11762        synchronized (mPackages) {
11763            PackageSetting ps = mSettings.mPackages.get(packageName);
11764            if (ps == null) {
11765                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11766                return false;
11767            }
11768            return ps.getBlockUninstall(userId);
11769        }
11770    }
11771
11772    /*
11773     * This method handles package deletion in general
11774     */
11775    private boolean deletePackageLI(String packageName, UserHandle user,
11776            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11777            int flags, PackageRemovedInfo outInfo,
11778            boolean writeSettings) {
11779        if (packageName == null) {
11780            Slog.w(TAG, "Attempt to delete null packageName.");
11781            return false;
11782        }
11783        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11784        PackageSetting ps;
11785        boolean dataOnly = false;
11786        int removeUser = -1;
11787        int appId = -1;
11788        synchronized (mPackages) {
11789            ps = mSettings.mPackages.get(packageName);
11790            if (ps == null) {
11791                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11792                return false;
11793            }
11794            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11795                    && user.getIdentifier() != UserHandle.USER_ALL) {
11796                // The caller is asking that the package only be deleted for a single
11797                // user.  To do this, we just mark its uninstalled state and delete
11798                // its data.  If this is a system app, we only allow this to happen if
11799                // they have set the special DELETE_SYSTEM_APP which requests different
11800                // semantics than normal for uninstalling system apps.
11801                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11802                ps.setUserState(user.getIdentifier(),
11803                        COMPONENT_ENABLED_STATE_DEFAULT,
11804                        false, //installed
11805                        true,  //stopped
11806                        true,  //notLaunched
11807                        false, //hidden
11808                        null, null, null,
11809                        false, // blockUninstall
11810                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
11811                if (!isSystemApp(ps)) {
11812                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11813                        // Other user still have this package installed, so all
11814                        // we need to do is clear this user's data and save that
11815                        // it is uninstalled.
11816                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11817                        removeUser = user.getIdentifier();
11818                        appId = ps.appId;
11819                        mSettings.writePackageRestrictionsLPr(removeUser);
11820                    } else {
11821                        // We need to set it back to 'installed' so the uninstall
11822                        // broadcasts will be sent correctly.
11823                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11824                        ps.setInstalled(true, user.getIdentifier());
11825                    }
11826                } else {
11827                    // This is a system app, so we assume that the
11828                    // other users still have this package installed, so all
11829                    // we need to do is clear this user's data and save that
11830                    // it is uninstalled.
11831                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11832                    removeUser = user.getIdentifier();
11833                    appId = ps.appId;
11834                    mSettings.writePackageRestrictionsLPr(removeUser);
11835                }
11836            }
11837        }
11838
11839        if (removeUser >= 0) {
11840            // From above, we determined that we are deleting this only
11841            // for a single user.  Continue the work here.
11842            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11843            if (outInfo != null) {
11844                outInfo.removedPackage = packageName;
11845                outInfo.removedAppId = appId;
11846                outInfo.removedUsers = new int[] {removeUser};
11847            }
11848            mInstaller.clearUserData(packageName, removeUser);
11849            removeKeystoreDataIfNeeded(removeUser, appId);
11850            schedulePackageCleaning(packageName, removeUser, false);
11851            return true;
11852        }
11853
11854        if (dataOnly) {
11855            // Delete application data first
11856            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11857            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11858            return true;
11859        }
11860
11861        boolean ret = false;
11862        if (isSystemApp(ps)) {
11863            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11864            // When an updated system application is deleted we delete the existing resources as well and
11865            // fall back to existing code in system partition
11866            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11867                    flags, outInfo, writeSettings);
11868        } else {
11869            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11870            // Kill application pre-emptively especially for apps on sd.
11871            killApplication(packageName, ps.appId, "uninstall pkg");
11872            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11873                    allUserHandles, perUserInstalled,
11874                    outInfo, writeSettings);
11875        }
11876
11877        return ret;
11878    }
11879
11880    private final class ClearStorageConnection implements ServiceConnection {
11881        IMediaContainerService mContainerService;
11882
11883        @Override
11884        public void onServiceConnected(ComponentName name, IBinder service) {
11885            synchronized (this) {
11886                mContainerService = IMediaContainerService.Stub.asInterface(service);
11887                notifyAll();
11888            }
11889        }
11890
11891        @Override
11892        public void onServiceDisconnected(ComponentName name) {
11893        }
11894    }
11895
11896    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11897        final boolean mounted;
11898        if (Environment.isExternalStorageEmulated()) {
11899            mounted = true;
11900        } else {
11901            final String status = Environment.getExternalStorageState();
11902
11903            mounted = status.equals(Environment.MEDIA_MOUNTED)
11904                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11905        }
11906
11907        if (!mounted) {
11908            return;
11909        }
11910
11911        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11912        int[] users;
11913        if (userId == UserHandle.USER_ALL) {
11914            users = sUserManager.getUserIds();
11915        } else {
11916            users = new int[] { userId };
11917        }
11918        final ClearStorageConnection conn = new ClearStorageConnection();
11919        if (mContext.bindServiceAsUser(
11920                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11921            try {
11922                for (int curUser : users) {
11923                    long timeout = SystemClock.uptimeMillis() + 5000;
11924                    synchronized (conn) {
11925                        long now = SystemClock.uptimeMillis();
11926                        while (conn.mContainerService == null && now < timeout) {
11927                            try {
11928                                conn.wait(timeout - now);
11929                            } catch (InterruptedException e) {
11930                            }
11931                        }
11932                    }
11933                    if (conn.mContainerService == null) {
11934                        return;
11935                    }
11936
11937                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11938                    clearDirectory(conn.mContainerService,
11939                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11940                    if (allData) {
11941                        clearDirectory(conn.mContainerService,
11942                                userEnv.buildExternalStorageAppDataDirs(packageName));
11943                        clearDirectory(conn.mContainerService,
11944                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11945                    }
11946                }
11947            } finally {
11948                mContext.unbindService(conn);
11949            }
11950        }
11951    }
11952
11953    @Override
11954    public void clearApplicationUserData(final String packageName,
11955            final IPackageDataObserver observer, final int userId) {
11956        mContext.enforceCallingOrSelfPermission(
11957                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11958        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11959        // Queue up an async operation since the package deletion may take a little while.
11960        mHandler.post(new Runnable() {
11961            public void run() {
11962                mHandler.removeCallbacks(this);
11963                final boolean succeeded;
11964                synchronized (mInstallLock) {
11965                    succeeded = clearApplicationUserDataLI(packageName, userId);
11966                }
11967                clearExternalStorageDataSync(packageName, userId, true);
11968                if (succeeded) {
11969                    // invoke DeviceStorageMonitor's update method to clear any notifications
11970                    DeviceStorageMonitorInternal
11971                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11972                    if (dsm != null) {
11973                        dsm.checkMemory();
11974                    }
11975                }
11976                if(observer != null) {
11977                    try {
11978                        observer.onRemoveCompleted(packageName, succeeded);
11979                    } catch (RemoteException e) {
11980                        Log.i(TAG, "Observer no longer exists.");
11981                    }
11982                } //end if observer
11983            } //end run
11984        });
11985    }
11986
11987    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11988        if (packageName == null) {
11989            Slog.w(TAG, "Attempt to delete null packageName.");
11990            return false;
11991        }
11992
11993        // Try finding details about the requested package
11994        PackageParser.Package pkg;
11995        synchronized (mPackages) {
11996            pkg = mPackages.get(packageName);
11997            if (pkg == null) {
11998                final PackageSetting ps = mSettings.mPackages.get(packageName);
11999                if (ps != null) {
12000                    pkg = ps.pkg;
12001                }
12002            }
12003        }
12004
12005        if (pkg == null) {
12006            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12007        }
12008
12009        // Always delete data directories for package, even if we found no other
12010        // record of app. This helps users recover from UID mismatches without
12011        // resorting to a full data wipe.
12012        int retCode = mInstaller.clearUserData(packageName, userId);
12013        if (retCode < 0) {
12014            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12015            return false;
12016        }
12017
12018        if (pkg == null) {
12019            return false;
12020        }
12021
12022        if (pkg != null && pkg.applicationInfo != null) {
12023            final int appId = pkg.applicationInfo.uid;
12024            removeKeystoreDataIfNeeded(userId, appId);
12025        }
12026
12027        // Create a native library symlink only if we have native libraries
12028        // and if the native libraries are 32 bit libraries. We do not provide
12029        // this symlink for 64 bit libraries.
12030        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
12031                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12032            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12033            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
12034                Slog.w(TAG, "Failed linking native library dir");
12035                return false;
12036            }
12037        }
12038
12039        return true;
12040    }
12041
12042    /**
12043     * Remove entries from the keystore daemon. Will only remove it if the
12044     * {@code appId} is valid.
12045     */
12046    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12047        if (appId < 0) {
12048            return;
12049        }
12050
12051        final KeyStore keyStore = KeyStore.getInstance();
12052        if (keyStore != null) {
12053            if (userId == UserHandle.USER_ALL) {
12054                for (final int individual : sUserManager.getUserIds()) {
12055                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12056                }
12057            } else {
12058                keyStore.clearUid(UserHandle.getUid(userId, appId));
12059            }
12060        } else {
12061            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12062        }
12063    }
12064
12065    @Override
12066    public void deleteApplicationCacheFiles(final String packageName,
12067            final IPackageDataObserver observer) {
12068        mContext.enforceCallingOrSelfPermission(
12069                android.Manifest.permission.DELETE_CACHE_FILES, null);
12070        // Queue up an async operation since the package deletion may take a little while.
12071        final int userId = UserHandle.getCallingUserId();
12072        mHandler.post(new Runnable() {
12073            public void run() {
12074                mHandler.removeCallbacks(this);
12075                final boolean succeded;
12076                synchronized (mInstallLock) {
12077                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12078                }
12079                clearExternalStorageDataSync(packageName, userId, false);
12080                if(observer != null) {
12081                    try {
12082                        observer.onRemoveCompleted(packageName, succeded);
12083                    } catch (RemoteException e) {
12084                        Log.i(TAG, "Observer no longer exists.");
12085                    }
12086                } //end if observer
12087            } //end run
12088        });
12089    }
12090
12091    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12092        if (packageName == null) {
12093            Slog.w(TAG, "Attempt to delete null packageName.");
12094            return false;
12095        }
12096        PackageParser.Package p;
12097        synchronized (mPackages) {
12098            p = mPackages.get(packageName);
12099        }
12100        if (p == null) {
12101            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12102            return false;
12103        }
12104        final ApplicationInfo applicationInfo = p.applicationInfo;
12105        if (applicationInfo == null) {
12106            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12107            return false;
12108        }
12109        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
12110        if (retCode < 0) {
12111            Slog.w(TAG, "Couldn't remove cache files for package: "
12112                       + packageName + " u" + userId);
12113            return false;
12114        }
12115        return true;
12116    }
12117
12118    @Override
12119    public void getPackageSizeInfo(final String packageName, int userHandle,
12120            final IPackageStatsObserver observer) {
12121        mContext.enforceCallingOrSelfPermission(
12122                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12123        if (packageName == null) {
12124            throw new IllegalArgumentException("Attempt to get size of null packageName");
12125        }
12126
12127        PackageStats stats = new PackageStats(packageName, userHandle);
12128
12129        /*
12130         * Queue up an async operation since the package measurement may take a
12131         * little while.
12132         */
12133        Message msg = mHandler.obtainMessage(INIT_COPY);
12134        msg.obj = new MeasureParams(stats, observer);
12135        mHandler.sendMessage(msg);
12136    }
12137
12138    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12139            PackageStats pStats) {
12140        if (packageName == null) {
12141            Slog.w(TAG, "Attempt to get size of null packageName.");
12142            return false;
12143        }
12144        PackageParser.Package p;
12145        boolean dataOnly = false;
12146        String libDirRoot = null;
12147        String asecPath = null;
12148        PackageSetting ps = null;
12149        synchronized (mPackages) {
12150            p = mPackages.get(packageName);
12151            ps = mSettings.mPackages.get(packageName);
12152            if(p == null) {
12153                dataOnly = true;
12154                if((ps == null) || (ps.pkg == null)) {
12155                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12156                    return false;
12157                }
12158                p = ps.pkg;
12159            }
12160            if (ps != null) {
12161                libDirRoot = ps.legacyNativeLibraryPathString;
12162            }
12163            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12164                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12165                if (secureContainerId != null) {
12166                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12167                }
12168            }
12169        }
12170        String publicSrcDir = null;
12171        if(!dataOnly) {
12172            final ApplicationInfo applicationInfo = p.applicationInfo;
12173            if (applicationInfo == null) {
12174                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12175                return false;
12176            }
12177            if (p.isForwardLocked()) {
12178                publicSrcDir = applicationInfo.getBaseResourcePath();
12179            }
12180        }
12181        // TODO: extend to measure size of split APKs
12182        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12183        // not just the first level.
12184        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12185        // just the primary.
12186        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12187        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
12188                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12189        if (res < 0) {
12190            return false;
12191        }
12192
12193        // Fix-up for forward-locked applications in ASEC containers.
12194        if (!isExternal(p)) {
12195            pStats.codeSize += pStats.externalCodeSize;
12196            pStats.externalCodeSize = 0L;
12197        }
12198
12199        return true;
12200    }
12201
12202
12203    @Override
12204    public void addPackageToPreferred(String packageName) {
12205        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12206    }
12207
12208    @Override
12209    public void removePackageFromPreferred(String packageName) {
12210        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12211    }
12212
12213    @Override
12214    public List<PackageInfo> getPreferredPackages(int flags) {
12215        return new ArrayList<PackageInfo>();
12216    }
12217
12218    private int getUidTargetSdkVersionLockedLPr(int uid) {
12219        Object obj = mSettings.getUserIdLPr(uid);
12220        if (obj instanceof SharedUserSetting) {
12221            final SharedUserSetting sus = (SharedUserSetting) obj;
12222            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12223            final Iterator<PackageSetting> it = sus.packages.iterator();
12224            while (it.hasNext()) {
12225                final PackageSetting ps = it.next();
12226                if (ps.pkg != null) {
12227                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12228                    if (v < vers) vers = v;
12229                }
12230            }
12231            return vers;
12232        } else if (obj instanceof PackageSetting) {
12233            final PackageSetting ps = (PackageSetting) obj;
12234            if (ps.pkg != null) {
12235                return ps.pkg.applicationInfo.targetSdkVersion;
12236            }
12237        }
12238        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12239    }
12240
12241    @Override
12242    public void addPreferredActivity(IntentFilter filter, int match,
12243            ComponentName[] set, ComponentName activity, int userId) {
12244        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12245                "Adding preferred");
12246    }
12247
12248    private void addPreferredActivityInternal(IntentFilter filter, int match,
12249            ComponentName[] set, ComponentName activity, boolean always, int userId,
12250            String opname) {
12251        // writer
12252        int callingUid = Binder.getCallingUid();
12253        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12254        if (filter.countActions() == 0) {
12255            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12256            return;
12257        }
12258        synchronized (mPackages) {
12259            if (mContext.checkCallingOrSelfPermission(
12260                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12261                    != PackageManager.PERMISSION_GRANTED) {
12262                if (getUidTargetSdkVersionLockedLPr(callingUid)
12263                        < Build.VERSION_CODES.FROYO) {
12264                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12265                            + callingUid);
12266                    return;
12267                }
12268                mContext.enforceCallingOrSelfPermission(
12269                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12270            }
12271
12272            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12273            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12274                    + userId + ":");
12275            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12276            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12277            scheduleWritePackageRestrictionsLocked(userId);
12278        }
12279    }
12280
12281    @Override
12282    public void replacePreferredActivity(IntentFilter filter, int match,
12283            ComponentName[] set, ComponentName activity, int userId) {
12284        if (filter.countActions() != 1) {
12285            throw new IllegalArgumentException(
12286                    "replacePreferredActivity expects filter to have only 1 action.");
12287        }
12288        if (filter.countDataAuthorities() != 0
12289                || filter.countDataPaths() != 0
12290                || filter.countDataSchemes() > 1
12291                || filter.countDataTypes() != 0) {
12292            throw new IllegalArgumentException(
12293                    "replacePreferredActivity expects filter to have no data authorities, " +
12294                    "paths, or types; and at most one scheme.");
12295        }
12296
12297        final int callingUid = Binder.getCallingUid();
12298        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12299        synchronized (mPackages) {
12300            if (mContext.checkCallingOrSelfPermission(
12301                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12302                    != PackageManager.PERMISSION_GRANTED) {
12303                if (getUidTargetSdkVersionLockedLPr(callingUid)
12304                        < Build.VERSION_CODES.FROYO) {
12305                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12306                            + Binder.getCallingUid());
12307                    return;
12308                }
12309                mContext.enforceCallingOrSelfPermission(
12310                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12311            }
12312
12313            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12314            if (pir != null) {
12315                // Get all of the existing entries that exactly match this filter.
12316                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
12317                if (existing != null && existing.size() == 1) {
12318                    PreferredActivity cur = existing.get(0);
12319                    if (DEBUG_PREFERRED) {
12320                        Slog.i(TAG, "Checking replace of preferred:");
12321                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12322                        if (!cur.mPref.mAlways) {
12323                            Slog.i(TAG, "  -- CUR; not mAlways!");
12324                        } else {
12325                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
12326                            Slog.i(TAG, "  -- CUR: mSet="
12327                                    + Arrays.toString(cur.mPref.mSetComponents));
12328                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
12329                            Slog.i(TAG, "  -- NEW: mMatch="
12330                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
12331                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
12332                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
12333                        }
12334                    }
12335                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
12336                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
12337                            && cur.mPref.sameSet(set)) {
12338                        // Setting the preferred activity to what it happens to be already
12339                        if (DEBUG_PREFERRED) {
12340                            Slog.i(TAG, "Replacing with same preferred activity "
12341                                    + cur.mPref.mShortComponent + " for user "
12342                                    + userId + ":");
12343                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12344                        }
12345                        return;
12346                    }
12347                }
12348
12349                if (existing != null) {
12350                    if (DEBUG_PREFERRED) {
12351                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
12352                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12353                    }
12354                    for (int i = 0; i < existing.size(); i++) {
12355                        PreferredActivity pa = existing.get(i);
12356                        if (DEBUG_PREFERRED) {
12357                            Slog.i(TAG, "Removing existing preferred activity "
12358                                    + pa.mPref.mComponent + ":");
12359                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
12360                        }
12361                        pir.removeFilter(pa);
12362                    }
12363                }
12364            }
12365            addPreferredActivityInternal(filter, match, set, activity, true, userId,
12366                    "Replacing preferred");
12367        }
12368    }
12369
12370    @Override
12371    public void clearPackagePreferredActivities(String packageName) {
12372        final int uid = Binder.getCallingUid();
12373        // writer
12374        synchronized (mPackages) {
12375            PackageParser.Package pkg = mPackages.get(packageName);
12376            if (pkg == null || pkg.applicationInfo.uid != uid) {
12377                if (mContext.checkCallingOrSelfPermission(
12378                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12379                        != PackageManager.PERMISSION_GRANTED) {
12380                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
12381                            < Build.VERSION_CODES.FROYO) {
12382                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
12383                                + Binder.getCallingUid());
12384                        return;
12385                    }
12386                    mContext.enforceCallingOrSelfPermission(
12387                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12388                }
12389            }
12390
12391            int user = UserHandle.getCallingUserId();
12392            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
12393                scheduleWritePackageRestrictionsLocked(user);
12394            }
12395        }
12396    }
12397
12398    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12399    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
12400        ArrayList<PreferredActivity> removed = null;
12401        boolean changed = false;
12402        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12403            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
12404            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12405            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
12406                continue;
12407            }
12408            Iterator<PreferredActivity> it = pir.filterIterator();
12409            while (it.hasNext()) {
12410                PreferredActivity pa = it.next();
12411                // Mark entry for removal only if it matches the package name
12412                // and the entry is of type "always".
12413                if (packageName == null ||
12414                        (pa.mPref.mComponent.getPackageName().equals(packageName)
12415                                && pa.mPref.mAlways)) {
12416                    if (removed == null) {
12417                        removed = new ArrayList<PreferredActivity>();
12418                    }
12419                    removed.add(pa);
12420                }
12421            }
12422            if (removed != null) {
12423                for (int j=0; j<removed.size(); j++) {
12424                    PreferredActivity pa = removed.get(j);
12425                    pir.removeFilter(pa);
12426                }
12427                changed = true;
12428            }
12429        }
12430        return changed;
12431    }
12432
12433    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12434    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
12435        if (userId == UserHandle.USER_ALL) {
12436            mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds());
12437            for (int oneUserId : sUserManager.getUserIds()) {
12438                scheduleWritePackageRestrictionsLocked(oneUserId);
12439            }
12440        } else {
12441            mSettings.removeIntentFilterVerificationLPw(packageName, userId);
12442            scheduleWritePackageRestrictionsLocked(userId);
12443        }
12444    }
12445
12446    @Override
12447    public void resetPreferredActivities(int userId) {
12448        /* TODO: Actually use userId. Why is it being passed in? */
12449        mContext.enforceCallingOrSelfPermission(
12450                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12451        // writer
12452        synchronized (mPackages) {
12453            int user = UserHandle.getCallingUserId();
12454            clearPackagePreferredActivitiesLPw(null, user);
12455            mSettings.readDefaultPreferredAppsLPw(this, user);
12456            scheduleWritePackageRestrictionsLocked(user);
12457        }
12458    }
12459
12460    @Override
12461    public int getPreferredActivities(List<IntentFilter> outFilters,
12462            List<ComponentName> outActivities, String packageName) {
12463
12464        int num = 0;
12465        final int userId = UserHandle.getCallingUserId();
12466        // reader
12467        synchronized (mPackages) {
12468            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12469            if (pir != null) {
12470                final Iterator<PreferredActivity> it = pir.filterIterator();
12471                while (it.hasNext()) {
12472                    final PreferredActivity pa = it.next();
12473                    if (packageName == null
12474                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
12475                                    && pa.mPref.mAlways)) {
12476                        if (outFilters != null) {
12477                            outFilters.add(new IntentFilter(pa));
12478                        }
12479                        if (outActivities != null) {
12480                            outActivities.add(pa.mPref.mComponent);
12481                        }
12482                    }
12483                }
12484            }
12485        }
12486
12487        return num;
12488    }
12489
12490    @Override
12491    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
12492            int userId) {
12493        int callingUid = Binder.getCallingUid();
12494        if (callingUid != Process.SYSTEM_UID) {
12495            throw new SecurityException(
12496                    "addPersistentPreferredActivity can only be run by the system");
12497        }
12498        if (filter.countActions() == 0) {
12499            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12500            return;
12501        }
12502        synchronized (mPackages) {
12503            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
12504                    " :");
12505            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12506            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
12507                    new PersistentPreferredActivity(filter, activity));
12508            scheduleWritePackageRestrictionsLocked(userId);
12509        }
12510    }
12511
12512    @Override
12513    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
12514        int callingUid = Binder.getCallingUid();
12515        if (callingUid != Process.SYSTEM_UID) {
12516            throw new SecurityException(
12517                    "clearPackagePersistentPreferredActivities can only be run by the system");
12518        }
12519        ArrayList<PersistentPreferredActivity> removed = null;
12520        boolean changed = false;
12521        synchronized (mPackages) {
12522            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
12523                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
12524                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
12525                        .valueAt(i);
12526                if (userId != thisUserId) {
12527                    continue;
12528                }
12529                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
12530                while (it.hasNext()) {
12531                    PersistentPreferredActivity ppa = it.next();
12532                    // Mark entry for removal only if it matches the package name.
12533                    if (ppa.mComponent.getPackageName().equals(packageName)) {
12534                        if (removed == null) {
12535                            removed = new ArrayList<PersistentPreferredActivity>();
12536                        }
12537                        removed.add(ppa);
12538                    }
12539                }
12540                if (removed != null) {
12541                    for (int j=0; j<removed.size(); j++) {
12542                        PersistentPreferredActivity ppa = removed.get(j);
12543                        ppir.removeFilter(ppa);
12544                    }
12545                    changed = true;
12546                }
12547            }
12548
12549            if (changed) {
12550                scheduleWritePackageRestrictionsLocked(userId);
12551            }
12552        }
12553    }
12554
12555    /**
12556     * Non-Binder method, support for the backup/restore mechanism: write the
12557     * full set of preferred activities in its canonical XML format.  Returns true
12558     * on success; false otherwise.
12559     */
12560    @Override
12561    public byte[] getPreferredActivityBackup(int userId) {
12562        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
12563            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
12564        }
12565
12566        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
12567        try {
12568            final XmlSerializer serializer = new FastXmlSerializer();
12569            serializer.setOutput(dataStream, "utf-8");
12570            serializer.startDocument(null, true);
12571            serializer.startTag(null, TAG_PREFERRED_BACKUP);
12572
12573            synchronized (mPackages) {
12574                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
12575            }
12576
12577            serializer.endTag(null, TAG_PREFERRED_BACKUP);
12578            serializer.endDocument();
12579            serializer.flush();
12580        } catch (Exception e) {
12581            if (DEBUG_BACKUP) {
12582                Slog.e(TAG, "Unable to write preferred activities for backup", e);
12583            }
12584            return null;
12585        }
12586
12587        return dataStream.toByteArray();
12588    }
12589
12590    @Override
12591    public void restorePreferredActivities(byte[] backup, int userId) {
12592        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
12593            throw new SecurityException("Only the system may call restorePreferredActivities()");
12594        }
12595
12596        try {
12597            final XmlPullParser parser = Xml.newPullParser();
12598            parser.setInput(new ByteArrayInputStream(backup), null);
12599
12600            int type;
12601            while ((type = parser.next()) != XmlPullParser.START_TAG
12602                    && type != XmlPullParser.END_DOCUMENT) {
12603            }
12604            if (type != XmlPullParser.START_TAG) {
12605                // oops didn't find a start tag?!
12606                if (DEBUG_BACKUP) {
12607                    Slog.e(TAG, "Didn't find start tag during restore");
12608                }
12609                return;
12610            }
12611
12612            // this is supposed to be TAG_PREFERRED_BACKUP
12613            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
12614                if (DEBUG_BACKUP) {
12615                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
12616                }
12617                return;
12618            }
12619
12620            // skip interfering stuff, then we're aligned with the backing implementation
12621            while ((type = parser.next()) == XmlPullParser.TEXT) { }
12622            synchronized (mPackages) {
12623                mSettings.readPreferredActivitiesLPw(parser, userId);
12624            }
12625        } catch (Exception e) {
12626            if (DEBUG_BACKUP) {
12627                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
12628            }
12629        }
12630    }
12631
12632    @Override
12633    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
12634            int sourceUserId, int targetUserId, int flags) {
12635        mContext.enforceCallingOrSelfPermission(
12636                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12637        int callingUid = Binder.getCallingUid();
12638        enforceOwnerRights(ownerPackage, callingUid);
12639        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12640        if (intentFilter.countActions() == 0) {
12641            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
12642            return;
12643        }
12644        synchronized (mPackages) {
12645            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
12646                    ownerPackage, targetUserId, flags);
12647            CrossProfileIntentResolver resolver =
12648                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12649            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
12650            // We have all those whose filter is equal. Now checking if the rest is equal as well.
12651            if (existing != null) {
12652                int size = existing.size();
12653                for (int i = 0; i < size; i++) {
12654                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
12655                        return;
12656                    }
12657                }
12658            }
12659            resolver.addFilter(newFilter);
12660            scheduleWritePackageRestrictionsLocked(sourceUserId);
12661        }
12662    }
12663
12664    @Override
12665    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
12666        mContext.enforceCallingOrSelfPermission(
12667                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12668        int callingUid = Binder.getCallingUid();
12669        enforceOwnerRights(ownerPackage, callingUid);
12670        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12671        synchronized (mPackages) {
12672            CrossProfileIntentResolver resolver =
12673                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12674            ArraySet<CrossProfileIntentFilter> set =
12675                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
12676            for (CrossProfileIntentFilter filter : set) {
12677                if (filter.getOwnerPackage().equals(ownerPackage)) {
12678                    resolver.removeFilter(filter);
12679                }
12680            }
12681            scheduleWritePackageRestrictionsLocked(sourceUserId);
12682        }
12683    }
12684
12685    // Enforcing that callingUid is owning pkg on userId
12686    private void enforceOwnerRights(String pkg, int callingUid) {
12687        // The system owns everything.
12688        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
12689            return;
12690        }
12691        int callingUserId = UserHandle.getUserId(callingUid);
12692        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
12693        if (pi == null) {
12694            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
12695                    + callingUserId);
12696        }
12697        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
12698            throw new SecurityException("Calling uid " + callingUid
12699                    + " does not own package " + pkg);
12700        }
12701    }
12702
12703    @Override
12704    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
12705        Intent intent = new Intent(Intent.ACTION_MAIN);
12706        intent.addCategory(Intent.CATEGORY_HOME);
12707
12708        final int callingUserId = UserHandle.getCallingUserId();
12709        List<ResolveInfo> list = queryIntentActivities(intent, null,
12710                PackageManager.GET_META_DATA, callingUserId);
12711        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
12712                true, false, false, callingUserId);
12713
12714        allHomeCandidates.clear();
12715        if (list != null) {
12716            for (ResolveInfo ri : list) {
12717                allHomeCandidates.add(ri);
12718            }
12719        }
12720        return (preferred == null || preferred.activityInfo == null)
12721                ? null
12722                : new ComponentName(preferred.activityInfo.packageName,
12723                        preferred.activityInfo.name);
12724    }
12725
12726    @Override
12727    public void setApplicationEnabledSetting(String appPackageName,
12728            int newState, int flags, int userId, String callingPackage) {
12729        if (!sUserManager.exists(userId)) return;
12730        if (callingPackage == null) {
12731            callingPackage = Integer.toString(Binder.getCallingUid());
12732        }
12733        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
12734    }
12735
12736    @Override
12737    public void setComponentEnabledSetting(ComponentName componentName,
12738            int newState, int flags, int userId) {
12739        if (!sUserManager.exists(userId)) return;
12740        setEnabledSetting(componentName.getPackageName(),
12741                componentName.getClassName(), newState, flags, userId, null);
12742    }
12743
12744    private void setEnabledSetting(final String packageName, String className, int newState,
12745            final int flags, int userId, String callingPackage) {
12746        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
12747              || newState == COMPONENT_ENABLED_STATE_ENABLED
12748              || newState == COMPONENT_ENABLED_STATE_DISABLED
12749              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
12750              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
12751            throw new IllegalArgumentException("Invalid new component state: "
12752                    + newState);
12753        }
12754        PackageSetting pkgSetting;
12755        final int uid = Binder.getCallingUid();
12756        final int permission = mContext.checkCallingOrSelfPermission(
12757                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12758        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
12759        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12760        boolean sendNow = false;
12761        boolean isApp = (className == null);
12762        String componentName = isApp ? packageName : className;
12763        int packageUid = -1;
12764        ArrayList<String> components;
12765
12766        // writer
12767        synchronized (mPackages) {
12768            pkgSetting = mSettings.mPackages.get(packageName);
12769            if (pkgSetting == null) {
12770                if (className == null) {
12771                    throw new IllegalArgumentException(
12772                            "Unknown package: " + packageName);
12773                }
12774                throw new IllegalArgumentException(
12775                        "Unknown component: " + packageName
12776                        + "/" + className);
12777            }
12778            // Allow root and verify that userId is not being specified by a different user
12779            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
12780                throw new SecurityException(
12781                        "Permission Denial: attempt to change component state from pid="
12782                        + Binder.getCallingPid()
12783                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
12784            }
12785            if (className == null) {
12786                // We're dealing with an application/package level state change
12787                if (pkgSetting.getEnabled(userId) == newState) {
12788                    // Nothing to do
12789                    return;
12790                }
12791                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
12792                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
12793                    // Don't care about who enables an app.
12794                    callingPackage = null;
12795                }
12796                pkgSetting.setEnabled(newState, userId, callingPackage);
12797                // pkgSetting.pkg.mSetEnabled = newState;
12798            } else {
12799                // We're dealing with a component level state change
12800                // First, verify that this is a valid class name.
12801                PackageParser.Package pkg = pkgSetting.pkg;
12802                if (pkg == null || !pkg.hasComponentClassName(className)) {
12803                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
12804                        throw new IllegalArgumentException("Component class " + className
12805                                + " does not exist in " + packageName);
12806                    } else {
12807                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
12808                                + className + " does not exist in " + packageName);
12809                    }
12810                }
12811                switch (newState) {
12812                case COMPONENT_ENABLED_STATE_ENABLED:
12813                    if (!pkgSetting.enableComponentLPw(className, userId)) {
12814                        return;
12815                    }
12816                    break;
12817                case COMPONENT_ENABLED_STATE_DISABLED:
12818                    if (!pkgSetting.disableComponentLPw(className, userId)) {
12819                        return;
12820                    }
12821                    break;
12822                case COMPONENT_ENABLED_STATE_DEFAULT:
12823                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
12824                        return;
12825                    }
12826                    break;
12827                default:
12828                    Slog.e(TAG, "Invalid new component state: " + newState);
12829                    return;
12830                }
12831            }
12832            scheduleWritePackageRestrictionsLocked(userId);
12833            components = mPendingBroadcasts.get(userId, packageName);
12834            final boolean newPackage = components == null;
12835            if (newPackage) {
12836                components = new ArrayList<String>();
12837            }
12838            if (!components.contains(componentName)) {
12839                components.add(componentName);
12840            }
12841            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12842                sendNow = true;
12843                // Purge entry from pending broadcast list if another one exists already
12844                // since we are sending one right away.
12845                mPendingBroadcasts.remove(userId, packageName);
12846            } else {
12847                if (newPackage) {
12848                    mPendingBroadcasts.put(userId, packageName, components);
12849                }
12850                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12851                    // Schedule a message
12852                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12853                }
12854            }
12855        }
12856
12857        long callingId = Binder.clearCallingIdentity();
12858        try {
12859            if (sendNow) {
12860                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12861                sendPackageChangedBroadcast(packageName,
12862                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12863            }
12864        } finally {
12865            Binder.restoreCallingIdentity(callingId);
12866        }
12867    }
12868
12869    private void sendPackageChangedBroadcast(String packageName,
12870            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12871        if (DEBUG_INSTALL)
12872            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12873                    + componentNames);
12874        Bundle extras = new Bundle(4);
12875        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12876        String nameList[] = new String[componentNames.size()];
12877        componentNames.toArray(nameList);
12878        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12879        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12880        extras.putInt(Intent.EXTRA_UID, packageUid);
12881        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12882                new int[] {UserHandle.getUserId(packageUid)});
12883    }
12884
12885    @Override
12886    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12887        if (!sUserManager.exists(userId)) return;
12888        final int uid = Binder.getCallingUid();
12889        final int permission = mContext.checkCallingOrSelfPermission(
12890                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12891        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12892        enforceCrossUserPermission(uid, userId, true, true, "stop package");
12893        // writer
12894        synchronized (mPackages) {
12895            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12896                    uid, userId)) {
12897                scheduleWritePackageRestrictionsLocked(userId);
12898            }
12899        }
12900    }
12901
12902    @Override
12903    public String getInstallerPackageName(String packageName) {
12904        // reader
12905        synchronized (mPackages) {
12906            return mSettings.getInstallerPackageNameLPr(packageName);
12907        }
12908    }
12909
12910    @Override
12911    public int getApplicationEnabledSetting(String packageName, int userId) {
12912        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12913        int uid = Binder.getCallingUid();
12914        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
12915        // reader
12916        synchronized (mPackages) {
12917            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12918        }
12919    }
12920
12921    @Override
12922    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12923        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12924        int uid = Binder.getCallingUid();
12925        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
12926        // reader
12927        synchronized (mPackages) {
12928            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12929        }
12930    }
12931
12932    @Override
12933    public void enterSafeMode() {
12934        enforceSystemOrRoot("Only the system can request entering safe mode");
12935
12936        if (!mSystemReady) {
12937            mSafeMode = true;
12938        }
12939    }
12940
12941    @Override
12942    public void systemReady() {
12943        mSystemReady = true;
12944
12945        // Read the compatibilty setting when the system is ready.
12946        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12947                mContext.getContentResolver(),
12948                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12949        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12950        if (DEBUG_SETTINGS) {
12951            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12952        }
12953
12954        synchronized (mPackages) {
12955            // Verify that all of the preferred activity components actually
12956            // exist.  It is possible for applications to be updated and at
12957            // that point remove a previously declared activity component that
12958            // had been set as a preferred activity.  We try to clean this up
12959            // the next time we encounter that preferred activity, but it is
12960            // possible for the user flow to never be able to return to that
12961            // situation so here we do a sanity check to make sure we haven't
12962            // left any junk around.
12963            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12964            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12965                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12966                removed.clear();
12967                for (PreferredActivity pa : pir.filterSet()) {
12968                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12969                        removed.add(pa);
12970                    }
12971                }
12972                if (removed.size() > 0) {
12973                    for (int r=0; r<removed.size(); r++) {
12974                        PreferredActivity pa = removed.get(r);
12975                        Slog.w(TAG, "Removing dangling preferred activity: "
12976                                + pa.mPref.mComponent);
12977                        pir.removeFilter(pa);
12978                    }
12979                    mSettings.writePackageRestrictionsLPr(
12980                            mSettings.mPreferredActivities.keyAt(i));
12981                }
12982            }
12983        }
12984        sUserManager.systemReady();
12985
12986        // Kick off any messages waiting for system ready
12987        if (mPostSystemReadyMessages != null) {
12988            for (Message msg : mPostSystemReadyMessages) {
12989                msg.sendToTarget();
12990            }
12991            mPostSystemReadyMessages = null;
12992        }
12993
12994        // Watch for external volumes that come and go over time
12995        final StorageManager storage = mContext.getSystemService(StorageManager.class);
12996        storage.registerListener(mStorageListener);
12997
12998        mInstallerService.systemReady();
12999    }
13000
13001    @Override
13002    public boolean isSafeMode() {
13003        return mSafeMode;
13004    }
13005
13006    @Override
13007    public boolean hasSystemUidErrors() {
13008        return mHasSystemUidErrors;
13009    }
13010
13011    static String arrayToString(int[] array) {
13012        StringBuffer buf = new StringBuffer(128);
13013        buf.append('[');
13014        if (array != null) {
13015            for (int i=0; i<array.length; i++) {
13016                if (i > 0) buf.append(", ");
13017                buf.append(array[i]);
13018            }
13019        }
13020        buf.append(']');
13021        return buf.toString();
13022    }
13023
13024    static class DumpState {
13025        public static final int DUMP_LIBS = 1 << 0;
13026        public static final int DUMP_FEATURES = 1 << 1;
13027        public static final int DUMP_RESOLVERS = 1 << 2;
13028        public static final int DUMP_PERMISSIONS = 1 << 3;
13029        public static final int DUMP_PACKAGES = 1 << 4;
13030        public static final int DUMP_SHARED_USERS = 1 << 5;
13031        public static final int DUMP_MESSAGES = 1 << 6;
13032        public static final int DUMP_PROVIDERS = 1 << 7;
13033        public static final int DUMP_VERIFIERS = 1 << 8;
13034        public static final int DUMP_PREFERRED = 1 << 9;
13035        public static final int DUMP_PREFERRED_XML = 1 << 10;
13036        public static final int DUMP_KEYSETS = 1 << 11;
13037        public static final int DUMP_VERSION = 1 << 12;
13038        public static final int DUMP_INSTALLS = 1 << 13;
13039        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13040        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13041
13042        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13043
13044        private int mTypes;
13045
13046        private int mOptions;
13047
13048        private boolean mTitlePrinted;
13049
13050        private SharedUserSetting mSharedUser;
13051
13052        public boolean isDumping(int type) {
13053            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13054                return true;
13055            }
13056
13057            return (mTypes & type) != 0;
13058        }
13059
13060        public void setDump(int type) {
13061            mTypes |= type;
13062        }
13063
13064        public boolean isOptionEnabled(int option) {
13065            return (mOptions & option) != 0;
13066        }
13067
13068        public void setOptionEnabled(int option) {
13069            mOptions |= option;
13070        }
13071
13072        public boolean onTitlePrinted() {
13073            final boolean printed = mTitlePrinted;
13074            mTitlePrinted = true;
13075            return printed;
13076        }
13077
13078        public boolean getTitlePrinted() {
13079            return mTitlePrinted;
13080        }
13081
13082        public void setTitlePrinted(boolean enabled) {
13083            mTitlePrinted = enabled;
13084        }
13085
13086        public SharedUserSetting getSharedUser() {
13087            return mSharedUser;
13088        }
13089
13090        public void setSharedUser(SharedUserSetting user) {
13091            mSharedUser = user;
13092        }
13093    }
13094
13095    @Override
13096    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13097        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13098                != PackageManager.PERMISSION_GRANTED) {
13099            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13100                    + Binder.getCallingPid()
13101                    + ", uid=" + Binder.getCallingUid()
13102                    + " without permission "
13103                    + android.Manifest.permission.DUMP);
13104            return;
13105        }
13106
13107        DumpState dumpState = new DumpState();
13108        boolean fullPreferred = false;
13109        boolean checkin = false;
13110
13111        String packageName = null;
13112
13113        int opti = 0;
13114        while (opti < args.length) {
13115            String opt = args[opti];
13116            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13117                break;
13118            }
13119            opti++;
13120
13121            if ("-a".equals(opt)) {
13122                // Right now we only know how to print all.
13123            } else if ("-h".equals(opt)) {
13124                pw.println("Package manager dump options:");
13125                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13126                pw.println("    --checkin: dump for a checkin");
13127                pw.println("    -f: print details of intent filters");
13128                pw.println("    -h: print this help");
13129                pw.println("  cmd may be one of:");
13130                pw.println("    l[ibraries]: list known shared libraries");
13131                pw.println("    f[ibraries]: list device features");
13132                pw.println("    k[eysets]: print known keysets");
13133                pw.println("    r[esolvers]: dump intent resolvers");
13134                pw.println("    perm[issions]: dump permissions");
13135                pw.println("    pref[erred]: print preferred package settings");
13136                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13137                pw.println("    prov[iders]: dump content providers");
13138                pw.println("    p[ackages]: dump installed packages");
13139                pw.println("    s[hared-users]: dump shared user IDs");
13140                pw.println("    m[essages]: print collected runtime messages");
13141                pw.println("    v[erifiers]: print package verifier info");
13142                pw.println("    version: print database version info");
13143                pw.println("    write: write current settings now");
13144                pw.println("    <package.name>: info about given package");
13145                pw.println("    installs: details about install sessions");
13146                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13147                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13148                return;
13149            } else if ("--checkin".equals(opt)) {
13150                checkin = true;
13151            } else if ("-f".equals(opt)) {
13152                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13153            } else {
13154                pw.println("Unknown argument: " + opt + "; use -h for help");
13155            }
13156        }
13157
13158        // Is the caller requesting to dump a particular piece of data?
13159        if (opti < args.length) {
13160            String cmd = args[opti];
13161            opti++;
13162            // Is this a package name?
13163            if ("android".equals(cmd) || cmd.contains(".")) {
13164                packageName = cmd;
13165                // When dumping a single package, we always dump all of its
13166                // filter information since the amount of data will be reasonable.
13167                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13168            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13169                dumpState.setDump(DumpState.DUMP_LIBS);
13170            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13171                dumpState.setDump(DumpState.DUMP_FEATURES);
13172            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13173                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13174            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13175                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13176            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13177                dumpState.setDump(DumpState.DUMP_PREFERRED);
13178            } else if ("preferred-xml".equals(cmd)) {
13179                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13180                if (opti < args.length && "--full".equals(args[opti])) {
13181                    fullPreferred = true;
13182                    opti++;
13183                }
13184            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13185                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13186            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13187                dumpState.setDump(DumpState.DUMP_PACKAGES);
13188            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13189                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13190            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13191                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13192            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13193                dumpState.setDump(DumpState.DUMP_MESSAGES);
13194            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13195                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13196            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13197                    || "intent-filter-verifiers".equals(cmd)) {
13198                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13199            } else if ("version".equals(cmd)) {
13200                dumpState.setDump(DumpState.DUMP_VERSION);
13201            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13202                dumpState.setDump(DumpState.DUMP_KEYSETS);
13203            } else if ("installs".equals(cmd)) {
13204                dumpState.setDump(DumpState.DUMP_INSTALLS);
13205            } else if ("write".equals(cmd)) {
13206                synchronized (mPackages) {
13207                    mSettings.writeLPr();
13208                    pw.println("Settings written.");
13209                    return;
13210                }
13211            }
13212        }
13213
13214        if (checkin) {
13215            pw.println("vers,1");
13216        }
13217
13218        // reader
13219        synchronized (mPackages) {
13220            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13221                if (!checkin) {
13222                    if (dumpState.onTitlePrinted())
13223                        pw.println();
13224                    pw.println("Database versions:");
13225                    pw.print("  SDK Version:");
13226                    pw.print(" internal=");
13227                    pw.print(mSettings.mInternalSdkPlatform);
13228                    pw.print(" external=");
13229                    pw.println(mSettings.mExternalSdkPlatform);
13230                    pw.print("  DB Version:");
13231                    pw.print(" internal=");
13232                    pw.print(mSettings.mInternalDatabaseVersion);
13233                    pw.print(" external=");
13234                    pw.println(mSettings.mExternalDatabaseVersion);
13235                }
13236            }
13237
13238            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13239                if (!checkin) {
13240                    if (dumpState.onTitlePrinted())
13241                        pw.println();
13242                    pw.println("Verifiers:");
13243                    pw.print("  Required: ");
13244                    pw.print(mRequiredVerifierPackage);
13245                    pw.print(" (uid=");
13246                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13247                    pw.println(")");
13248                } else if (mRequiredVerifierPackage != null) {
13249                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13250                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13251                }
13252            }
13253
13254            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13255                    packageName == null) {
13256                if (mIntentFilterVerifierComponent != null) {
13257                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13258                    if (!checkin) {
13259                        if (dumpState.onTitlePrinted())
13260                            pw.println();
13261                        pw.println("Intent Filter Verifier:");
13262                        pw.print("  Using: ");
13263                        pw.print(verifierPackageName);
13264                        pw.print(" (uid=");
13265                        pw.print(getPackageUid(verifierPackageName, 0));
13266                        pw.println(")");
13267                    } else if (verifierPackageName != null) {
13268                        pw.print("ifv,"); pw.print(verifierPackageName);
13269                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13270                    }
13271                } else {
13272                    pw.println();
13273                    pw.println("No Intent Filter Verifier available!");
13274                }
13275            }
13276
13277            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13278                boolean printedHeader = false;
13279                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13280                while (it.hasNext()) {
13281                    String name = it.next();
13282                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13283                    if (!checkin) {
13284                        if (!printedHeader) {
13285                            if (dumpState.onTitlePrinted())
13286                                pw.println();
13287                            pw.println("Libraries:");
13288                            printedHeader = true;
13289                        }
13290                        pw.print("  ");
13291                    } else {
13292                        pw.print("lib,");
13293                    }
13294                    pw.print(name);
13295                    if (!checkin) {
13296                        pw.print(" -> ");
13297                    }
13298                    if (ent.path != null) {
13299                        if (!checkin) {
13300                            pw.print("(jar) ");
13301                            pw.print(ent.path);
13302                        } else {
13303                            pw.print(",jar,");
13304                            pw.print(ent.path);
13305                        }
13306                    } else {
13307                        if (!checkin) {
13308                            pw.print("(apk) ");
13309                            pw.print(ent.apk);
13310                        } else {
13311                            pw.print(",apk,");
13312                            pw.print(ent.apk);
13313                        }
13314                    }
13315                    pw.println();
13316                }
13317            }
13318
13319            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
13320                if (dumpState.onTitlePrinted())
13321                    pw.println();
13322                if (!checkin) {
13323                    pw.println("Features:");
13324                }
13325                Iterator<String> it = mAvailableFeatures.keySet().iterator();
13326                while (it.hasNext()) {
13327                    String name = it.next();
13328                    if (!checkin) {
13329                        pw.print("  ");
13330                    } else {
13331                        pw.print("feat,");
13332                    }
13333                    pw.println(name);
13334                }
13335            }
13336
13337            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
13338                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
13339                        : "Activity Resolver Table:", "  ", packageName,
13340                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13341                    dumpState.setTitlePrinted(true);
13342                }
13343                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
13344                        : "Receiver Resolver Table:", "  ", packageName,
13345                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13346                    dumpState.setTitlePrinted(true);
13347                }
13348                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
13349                        : "Service Resolver Table:", "  ", packageName,
13350                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13351                    dumpState.setTitlePrinted(true);
13352                }
13353                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
13354                        : "Provider Resolver Table:", "  ", packageName,
13355                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13356                    dumpState.setTitlePrinted(true);
13357                }
13358            }
13359
13360            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
13361                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13362                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13363                    int user = mSettings.mPreferredActivities.keyAt(i);
13364                    if (pir.dump(pw,
13365                            dumpState.getTitlePrinted()
13366                                ? "\nPreferred Activities User " + user + ":"
13367                                : "Preferred Activities User " + user + ":", "  ",
13368                            packageName, true, false)) {
13369                        dumpState.setTitlePrinted(true);
13370                    }
13371                }
13372            }
13373
13374            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
13375                pw.flush();
13376                FileOutputStream fout = new FileOutputStream(fd);
13377                BufferedOutputStream str = new BufferedOutputStream(fout);
13378                XmlSerializer serializer = new FastXmlSerializer();
13379                try {
13380                    serializer.setOutput(str, "utf-8");
13381                    serializer.startDocument(null, true);
13382                    serializer.setFeature(
13383                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
13384                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
13385                    serializer.endDocument();
13386                    serializer.flush();
13387                } catch (IllegalArgumentException e) {
13388                    pw.println("Failed writing: " + e);
13389                } catch (IllegalStateException e) {
13390                    pw.println("Failed writing: " + e);
13391                } catch (IOException e) {
13392                    pw.println("Failed writing: " + e);
13393                }
13394            }
13395
13396            if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) {
13397                pw.println();
13398                int count = mSettings.mPackages.size();
13399                if (count == 0) {
13400                    pw.println("No domain preferred apps!");
13401                    pw.println();
13402                } else {
13403                    final String prefix = "  ";
13404                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
13405                    if (allPackageSettings.size() == 0) {
13406                        pw.println("No domain preferred apps!");
13407                        pw.println();
13408                    } else {
13409                        pw.println("Domain preferred apps status:");
13410                        pw.println();
13411                        count = 0;
13412                        for (PackageSetting ps : allPackageSettings) {
13413                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13414                            if (ivi == null || ivi.getPackageName() == null) continue;
13415                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
13416                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
13417                            pw.println(prefix + "Status: " + ivi.getStatusString());
13418                            pw.println();
13419                            count++;
13420                        }
13421                        if (count == 0) {
13422                            pw.println(prefix + "No domain preferred app status!");
13423                            pw.println();
13424                        }
13425                        for (int userId : sUserManager.getUserIds()) {
13426                            pw.println("Domain preferred apps for User " + userId + ":");
13427                            pw.println();
13428                            count = 0;
13429                            for (PackageSetting ps : allPackageSettings) {
13430                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13431                                if (ivi == null || ivi.getPackageName() == null) {
13432                                    continue;
13433                                }
13434                                final int status = ps.getDomainVerificationStatusForUser(userId);
13435                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
13436                                    continue;
13437                                }
13438                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
13439                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
13440                                String statusStr = IntentFilterVerificationInfo.
13441                                        getStatusStringFromValue(status);
13442                                pw.println(prefix + "Status: " + statusStr);
13443                                pw.println();
13444                                count++;
13445                            }
13446                            if (count == 0) {
13447                                pw.println(prefix + "No domain preferred apps!");
13448                                pw.println();
13449                            }
13450                        }
13451                    }
13452                }
13453            }
13454
13455            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
13456                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
13457                if (packageName == null) {
13458                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
13459                        if (iperm == 0) {
13460                            if (dumpState.onTitlePrinted())
13461                                pw.println();
13462                            pw.println("AppOp Permissions:");
13463                        }
13464                        pw.print("  AppOp Permission ");
13465                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
13466                        pw.println(":");
13467                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
13468                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
13469                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
13470                        }
13471                    }
13472                }
13473            }
13474
13475            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
13476                boolean printedSomething = false;
13477                for (PackageParser.Provider p : mProviders.mProviders.values()) {
13478                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13479                        continue;
13480                    }
13481                    if (!printedSomething) {
13482                        if (dumpState.onTitlePrinted())
13483                            pw.println();
13484                        pw.println("Registered ContentProviders:");
13485                        printedSomething = true;
13486                    }
13487                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
13488                    pw.print("    "); pw.println(p.toString());
13489                }
13490                printedSomething = false;
13491                for (Map.Entry<String, PackageParser.Provider> entry :
13492                        mProvidersByAuthority.entrySet()) {
13493                    PackageParser.Provider p = entry.getValue();
13494                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13495                        continue;
13496                    }
13497                    if (!printedSomething) {
13498                        if (dumpState.onTitlePrinted())
13499                            pw.println();
13500                        pw.println("ContentProvider Authorities:");
13501                        printedSomething = true;
13502                    }
13503                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
13504                    pw.print("    "); pw.println(p.toString());
13505                    if (p.info != null && p.info.applicationInfo != null) {
13506                        final String appInfo = p.info.applicationInfo.toString();
13507                        pw.print("      applicationInfo="); pw.println(appInfo);
13508                    }
13509                }
13510            }
13511
13512            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
13513                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
13514            }
13515
13516            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
13517                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
13518            }
13519
13520            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
13521                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
13522            }
13523
13524            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
13525                // XXX should handle packageName != null by dumping only install data that
13526                // the given package is involved with.
13527                if (dumpState.onTitlePrinted()) pw.println();
13528                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
13529            }
13530
13531            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
13532                if (dumpState.onTitlePrinted()) pw.println();
13533                mSettings.dumpReadMessagesLPr(pw, dumpState);
13534
13535                pw.println();
13536                pw.println("Package warning messages:");
13537                BufferedReader in = null;
13538                String line = null;
13539                try {
13540                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
13541                    while ((line = in.readLine()) != null) {
13542                        if (line.contains("ignored: updated version")) continue;
13543                        pw.println(line);
13544                    }
13545                } catch (IOException ignored) {
13546                } finally {
13547                    IoUtils.closeQuietly(in);
13548                }
13549            }
13550
13551            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
13552                BufferedReader in = null;
13553                String line = null;
13554                try {
13555                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
13556                    while ((line = in.readLine()) != null) {
13557                        if (line.contains("ignored: updated version")) continue;
13558                        pw.print("msg,");
13559                        pw.println(line);
13560                    }
13561                } catch (IOException ignored) {
13562                } finally {
13563                    IoUtils.closeQuietly(in);
13564                }
13565            }
13566        }
13567    }
13568
13569    // ------- apps on sdcard specific code -------
13570    static final boolean DEBUG_SD_INSTALL = false;
13571
13572    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
13573
13574    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
13575
13576    private boolean mMediaMounted = false;
13577
13578    static String getEncryptKey() {
13579        try {
13580            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
13581                    SD_ENCRYPTION_KEYSTORE_NAME);
13582            if (sdEncKey == null) {
13583                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
13584                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
13585                if (sdEncKey == null) {
13586                    Slog.e(TAG, "Failed to create encryption keys");
13587                    return null;
13588                }
13589            }
13590            return sdEncKey;
13591        } catch (NoSuchAlgorithmException nsae) {
13592            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
13593            return null;
13594        } catch (IOException ioe) {
13595            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
13596            return null;
13597        }
13598    }
13599
13600    /*
13601     * Update media status on PackageManager.
13602     */
13603    @Override
13604    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
13605        int callingUid = Binder.getCallingUid();
13606        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
13607            throw new SecurityException("Media status can only be updated by the system");
13608        }
13609        // reader; this apparently protects mMediaMounted, but should probably
13610        // be a different lock in that case.
13611        synchronized (mPackages) {
13612            Log.i(TAG, "Updating external media status from "
13613                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
13614                    + (mediaStatus ? "mounted" : "unmounted"));
13615            if (DEBUG_SD_INSTALL)
13616                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
13617                        + ", mMediaMounted=" + mMediaMounted);
13618            if (mediaStatus == mMediaMounted) {
13619                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
13620                        : 0, -1);
13621                mHandler.sendMessage(msg);
13622                return;
13623            }
13624            mMediaMounted = mediaStatus;
13625        }
13626        // Queue up an async operation since the package installation may take a
13627        // little while.
13628        mHandler.post(new Runnable() {
13629            public void run() {
13630                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
13631            }
13632        });
13633    }
13634
13635    /**
13636     * Called by MountService when the initial ASECs to scan are available.
13637     * Should block until all the ASEC containers are finished being scanned.
13638     */
13639    public void scanAvailableAsecs() {
13640        updateExternalMediaStatusInner(true, false, false);
13641        if (mShouldRestoreconData) {
13642            SELinuxMMAC.setRestoreconDone();
13643            mShouldRestoreconData = false;
13644        }
13645    }
13646
13647    /*
13648     * Collect information of applications on external media, map them against
13649     * existing containers and update information based on current mount status.
13650     * Please note that we always have to report status if reportStatus has been
13651     * set to true especially when unloading packages.
13652     */
13653    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
13654            boolean externalStorage) {
13655        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
13656        int[] uidArr = EmptyArray.INT;
13657
13658        final String[] list = PackageHelper.getSecureContainerList();
13659        if (ArrayUtils.isEmpty(list)) {
13660            Log.i(TAG, "No secure containers found");
13661        } else {
13662            // Process list of secure containers and categorize them
13663            // as active or stale based on their package internal state.
13664
13665            // reader
13666            synchronized (mPackages) {
13667                for (String cid : list) {
13668                    // Leave stages untouched for now; installer service owns them
13669                    if (PackageInstallerService.isStageName(cid)) continue;
13670
13671                    if (DEBUG_SD_INSTALL)
13672                        Log.i(TAG, "Processing container " + cid);
13673                    String pkgName = getAsecPackageName(cid);
13674                    if (pkgName == null) {
13675                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
13676                        continue;
13677                    }
13678                    if (DEBUG_SD_INSTALL)
13679                        Log.i(TAG, "Looking for pkg : " + pkgName);
13680
13681                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
13682                    if (ps == null) {
13683                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
13684                        continue;
13685                    }
13686
13687                    /*
13688                     * Skip packages that are not external if we're unmounting
13689                     * external storage.
13690                     */
13691                    if (externalStorage && !isMounted && !isExternal(ps)) {
13692                        continue;
13693                    }
13694
13695                    final AsecInstallArgs args = new AsecInstallArgs(cid,
13696                            getAppDexInstructionSets(ps), ps.isForwardLocked());
13697                    // The package status is changed only if the code path
13698                    // matches between settings and the container id.
13699                    if (ps.codePathString != null
13700                            && ps.codePathString.startsWith(args.getCodePath())) {
13701                        if (DEBUG_SD_INSTALL) {
13702                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
13703                                    + " at code path: " + ps.codePathString);
13704                        }
13705
13706                        // We do have a valid package installed on sdcard
13707                        processCids.put(args, ps.codePathString);
13708                        final int uid = ps.appId;
13709                        if (uid != -1) {
13710                            uidArr = ArrayUtils.appendInt(uidArr, uid);
13711                        }
13712                    } else {
13713                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
13714                                + ps.codePathString);
13715                    }
13716                }
13717            }
13718
13719            Arrays.sort(uidArr);
13720        }
13721
13722        // Process packages with valid entries.
13723        if (isMounted) {
13724            if (DEBUG_SD_INSTALL)
13725                Log.i(TAG, "Loading packages");
13726            loadMediaPackages(processCids, uidArr);
13727            startCleaningPackages();
13728            mInstallerService.onSecureContainersAvailable();
13729        } else {
13730            if (DEBUG_SD_INSTALL)
13731                Log.i(TAG, "Unloading packages");
13732            unloadMediaPackages(processCids, uidArr, reportStatus);
13733        }
13734    }
13735
13736    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13737            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
13738        final int size = infos.size();
13739        final String[] packageNames = new String[size];
13740        final int[] packageUids = new int[size];
13741        for (int i = 0; i < size; i++) {
13742            final ApplicationInfo info = infos.get(i);
13743            packageNames[i] = info.packageName;
13744            packageUids[i] = info.uid;
13745        }
13746        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
13747                finishedReceiver);
13748    }
13749
13750    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13751            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
13752        sendResourcesChangedBroadcast(mediaStatus, replacing,
13753                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
13754    }
13755
13756    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13757            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
13758        int size = pkgList.length;
13759        if (size > 0) {
13760            // Send broadcasts here
13761            Bundle extras = new Bundle();
13762            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13763            if (uidArr != null) {
13764                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
13765            }
13766            if (replacing) {
13767                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
13768            }
13769            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
13770                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
13771            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
13772        }
13773    }
13774
13775   /*
13776     * Look at potentially valid container ids from processCids If package
13777     * information doesn't match the one on record or package scanning fails,
13778     * the cid is added to list of removeCids. We currently don't delete stale
13779     * containers.
13780     */
13781    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
13782        ArrayList<String> pkgList = new ArrayList<String>();
13783        Set<AsecInstallArgs> keys = processCids.keySet();
13784
13785        for (AsecInstallArgs args : keys) {
13786            String codePath = processCids.get(args);
13787            if (DEBUG_SD_INSTALL)
13788                Log.i(TAG, "Loading container : " + args.cid);
13789            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13790            try {
13791                // Make sure there are no container errors first.
13792                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
13793                    Slog.e(TAG, "Failed to mount cid : " + args.cid
13794                            + " when installing from sdcard");
13795                    continue;
13796                }
13797                // Check code path here.
13798                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
13799                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
13800                            + " does not match one in settings " + codePath);
13801                    continue;
13802                }
13803                // Parse package
13804                int parseFlags = mDefParseFlags;
13805                if (args.isExternalAsec()) {
13806                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
13807                }
13808                if (args.isFwdLocked()) {
13809                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
13810                }
13811
13812                synchronized (mInstallLock) {
13813                    PackageParser.Package pkg = null;
13814                    try {
13815                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
13816                    } catch (PackageManagerException e) {
13817                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
13818                    }
13819                    // Scan the package
13820                    if (pkg != null) {
13821                        /*
13822                         * TODO why is the lock being held? doPostInstall is
13823                         * called in other places without the lock. This needs
13824                         * to be straightened out.
13825                         */
13826                        // writer
13827                        synchronized (mPackages) {
13828                            retCode = PackageManager.INSTALL_SUCCEEDED;
13829                            pkgList.add(pkg.packageName);
13830                            // Post process args
13831                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
13832                                    pkg.applicationInfo.uid);
13833                        }
13834                    } else {
13835                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
13836                    }
13837                }
13838
13839            } finally {
13840                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
13841                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
13842                }
13843            }
13844        }
13845        // writer
13846        synchronized (mPackages) {
13847            // If the platform SDK has changed since the last time we booted,
13848            // we need to re-grant app permission to catch any new ones that
13849            // appear. This is really a hack, and means that apps can in some
13850            // cases get permissions that the user didn't initially explicitly
13851            // allow... it would be nice to have some better way to handle
13852            // this situation.
13853            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
13854            if (regrantPermissions)
13855                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
13856                        + mSdkVersion + "; regranting permissions for external storage");
13857            mSettings.mExternalSdkPlatform = mSdkVersion;
13858
13859            // Make sure group IDs have been assigned, and any permission
13860            // changes in other apps are accounted for
13861            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
13862                    | (regrantPermissions
13863                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
13864                            : 0));
13865
13866            mSettings.updateExternalDatabaseVersion();
13867
13868            // can downgrade to reader
13869            // Persist settings
13870            mSettings.writeLPr();
13871        }
13872        // Send a broadcast to let everyone know we are done processing
13873        if (pkgList.size() > 0) {
13874            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13875        }
13876    }
13877
13878   /*
13879     * Utility method to unload a list of specified containers
13880     */
13881    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
13882        // Just unmount all valid containers.
13883        for (AsecInstallArgs arg : cidArgs) {
13884            synchronized (mInstallLock) {
13885                arg.doPostDeleteLI(false);
13886           }
13887       }
13888   }
13889
13890    /*
13891     * Unload packages mounted on external media. This involves deleting package
13892     * data from internal structures, sending broadcasts about diabled packages,
13893     * gc'ing to free up references, unmounting all secure containers
13894     * corresponding to packages on external media, and posting a
13895     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
13896     * that we always have to post this message if status has been requested no
13897     * matter what.
13898     */
13899    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
13900            final boolean reportStatus) {
13901        if (DEBUG_SD_INSTALL)
13902            Log.i(TAG, "unloading media packages");
13903        ArrayList<String> pkgList = new ArrayList<String>();
13904        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
13905        final Set<AsecInstallArgs> keys = processCids.keySet();
13906        for (AsecInstallArgs args : keys) {
13907            String pkgName = args.getPackageName();
13908            if (DEBUG_SD_INSTALL)
13909                Log.i(TAG, "Trying to unload pkg : " + pkgName);
13910            // Delete package internally
13911            PackageRemovedInfo outInfo = new PackageRemovedInfo();
13912            synchronized (mInstallLock) {
13913                boolean res = deletePackageLI(pkgName, null, false, null, null,
13914                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
13915                if (res) {
13916                    pkgList.add(pkgName);
13917                } else {
13918                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
13919                    failedList.add(args);
13920                }
13921            }
13922        }
13923
13924        // reader
13925        synchronized (mPackages) {
13926            // We didn't update the settings after removing each package;
13927            // write them now for all packages.
13928            mSettings.writeLPr();
13929        }
13930
13931        // We have to absolutely send UPDATED_MEDIA_STATUS only
13932        // after confirming that all the receivers processed the ordered
13933        // broadcast when packages get disabled, force a gc to clean things up.
13934        // and unload all the containers.
13935        if (pkgList.size() > 0) {
13936            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
13937                    new IIntentReceiver.Stub() {
13938                public void performReceive(Intent intent, int resultCode, String data,
13939                        Bundle extras, boolean ordered, boolean sticky,
13940                        int sendingUser) throws RemoteException {
13941                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
13942                            reportStatus ? 1 : 0, 1, keys);
13943                    mHandler.sendMessage(msg);
13944                }
13945            });
13946        } else {
13947            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
13948                    keys);
13949            mHandler.sendMessage(msg);
13950        }
13951    }
13952
13953    private void loadPrivatePackages(VolumeInfo vol) {
13954        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
13955        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
13956        synchronized (mPackages) {
13957            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
13958            for (PackageSetting ps : packages) {
13959                synchronized (mInstallLock) {
13960                    final PackageParser.Package pkg;
13961                    try {
13962                        pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
13963                        loaded.add(pkg.applicationInfo);
13964                    } catch (PackageManagerException e) {
13965                        Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
13966                    }
13967                }
13968            }
13969
13970            // TODO: regrant any permissions that changed based since original install
13971
13972            mSettings.writeLPr();
13973        }
13974
13975        Slog.d(TAG, "Loaded packages " + loaded);
13976        sendResourcesChangedBroadcast(true, false, loaded, null);
13977    }
13978
13979    private void unloadPrivatePackages(VolumeInfo vol) {
13980        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
13981        synchronized (mPackages) {
13982            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
13983            for (PackageSetting ps : packages) {
13984                if (ps.pkg == null) continue;
13985                synchronized (mInstallLock) {
13986                    final ApplicationInfo info = ps.pkg.applicationInfo;
13987                    final PackageRemovedInfo outInfo = new PackageRemovedInfo();
13988                    if (deletePackageLI(ps.name, null, false, null, null,
13989                            PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
13990                        unloaded.add(info);
13991                    } else {
13992                        Slog.w(TAG, "Failed to unload " + ps.codePath);
13993                    }
13994                }
13995            }
13996
13997            mSettings.writeLPr();
13998        }
13999
14000        Slog.d(TAG, "Unloaded packages " + unloaded);
14001        sendResourcesChangedBroadcast(false, false, unloaded, null);
14002    }
14003
14004    @Override
14005    public void movePackage(final String packageName, final IPackageMoveObserver observer,
14006            final int flags) {
14007        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14008
14009        final int installFlags;
14010        if ((flags & MOVE_INTERNAL) != 0) {
14011            installFlags = INSTALL_INTERNAL;
14012        } else if ((flags & MOVE_EXTERNAL_MEDIA) != 0) {
14013            installFlags = INSTALL_EXTERNAL;
14014        } else {
14015            throw new IllegalArgumentException("Unsupported move flags " + flags);
14016        }
14017
14018        try {
14019            movePackageInternal(packageName, null, installFlags, false, observer);
14020        } catch (PackageManagerException e) {
14021            Slog.d(TAG, "Failed to move " + packageName, e);
14022            try {
14023                observer.packageMoved(packageName, e.error);
14024            } catch (RemoteException ignored) {
14025            }
14026        }
14027    }
14028
14029    @Override
14030    public void movePackageAndData(final String packageName, final String volumeUuid,
14031            final IPackageMoveObserver observer) {
14032        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14033        try {
14034            movePackageInternal(packageName, volumeUuid, INSTALL_INTERNAL, true, observer);
14035        } catch (PackageManagerException e) {
14036            Slog.d(TAG, "Failed to move " + packageName, e);
14037            try {
14038                observer.packageMoved(packageName, e.error);
14039            } catch (RemoteException ignored) {
14040            }
14041        }
14042    }
14043
14044    private void movePackageInternal(final String packageName, String volumeUuid, int installFlags,
14045            boolean andData, final IPackageMoveObserver observer) throws PackageManagerException {
14046        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14047
14048        File codeFile = null;
14049        String installerPackageName = null;
14050        String packageAbiOverride = null;
14051
14052        // TOOD: move app private data before installing
14053
14054        // reader
14055        synchronized (mPackages) {
14056            final PackageParser.Package pkg = mPackages.get(packageName);
14057            final PackageSetting ps = mSettings.mPackages.get(packageName);
14058            if (pkg == null || ps == null) {
14059                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14060            }
14061
14062            if (pkg.applicationInfo.isSystemApp()) {
14063                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14064                        "Cannot move system application");
14065            } else if (pkg.mOperationPending) {
14066                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14067                        "Attempt to move package which has pending operations");
14068            }
14069
14070            // TODO: yell if already in desired location
14071
14072            pkg.mOperationPending = true;
14073
14074            codeFile = new File(pkg.codePath);
14075            installerPackageName = ps.installerPackageName;
14076            packageAbiOverride = ps.cpuAbiOverrideString;
14077        }
14078
14079        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14080            @Override
14081            public void onUserActionRequired(Intent intent) throws RemoteException {
14082                throw new IllegalStateException();
14083            }
14084
14085            @Override
14086            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14087                    Bundle extras) throws RemoteException {
14088                Slog.d(TAG, "Install result for move: "
14089                        + PackageManager.installStatusToString(returnCode, msg));
14090
14091                // We usually have a new package now after the install, but if
14092                // we failed we need to clear the pending flag on the original
14093                // package object.
14094                synchronized (mPackages) {
14095                    final PackageParser.Package pkg = mPackages.get(packageName);
14096                    if (pkg != null) {
14097                        pkg.mOperationPending = false;
14098                    }
14099                }
14100
14101                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14102                switch (status) {
14103                    case PackageInstaller.STATUS_SUCCESS:
14104                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
14105                        break;
14106                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14107                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14108                        break;
14109                    default:
14110                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14111                        break;
14112                }
14113            }
14114        };
14115
14116        // Treat a move like reinstalling an existing app, which ensures that we
14117        // process everythign uniformly, like unpacking native libraries.
14118        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14119
14120        final Message msg = mHandler.obtainMessage(INIT_COPY);
14121        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14122        msg.obj = new InstallParams(origin, installObserver, installFlags,
14123                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14124        mHandler.sendMessage(msg);
14125    }
14126
14127    @Override
14128    public boolean setInstallLocation(int loc) {
14129        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14130                null);
14131        if (getInstallLocation() == loc) {
14132            return true;
14133        }
14134        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14135                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14136            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14137                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14138            return true;
14139        }
14140        return false;
14141   }
14142
14143    @Override
14144    public int getInstallLocation() {
14145        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14146                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14147                PackageHelper.APP_INSTALL_AUTO);
14148    }
14149
14150    /** Called by UserManagerService */
14151    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14152        mDirtyUsers.remove(userHandle);
14153        mSettings.removeUserLPw(userHandle);
14154        mPendingBroadcasts.remove(userHandle);
14155        if (mInstaller != null) {
14156            // Technically, we shouldn't be doing this with the package lock
14157            // held.  However, this is very rare, and there is already so much
14158            // other disk I/O going on, that we'll let it slide for now.
14159            mInstaller.removeUserDataDirs(userHandle);
14160        }
14161        mUserNeedsBadging.delete(userHandle);
14162        removeUnusedPackagesLILPw(userManager, userHandle);
14163    }
14164
14165    /**
14166     * We're removing userHandle and would like to remove any downloaded packages
14167     * that are no longer in use by any other user.
14168     * @param userHandle the user being removed
14169     */
14170    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
14171        final boolean DEBUG_CLEAN_APKS = false;
14172        int [] users = userManager.getUserIdsLPr();
14173        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
14174        while (psit.hasNext()) {
14175            PackageSetting ps = psit.next();
14176            if (ps.pkg == null) {
14177                continue;
14178            }
14179            final String packageName = ps.pkg.packageName;
14180            // Skip over if system app
14181            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14182                continue;
14183            }
14184            if (DEBUG_CLEAN_APKS) {
14185                Slog.i(TAG, "Checking package " + packageName);
14186            }
14187            boolean keep = false;
14188            for (int i = 0; i < users.length; i++) {
14189                if (users[i] != userHandle && ps.getInstalled(users[i])) {
14190                    keep = true;
14191                    if (DEBUG_CLEAN_APKS) {
14192                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
14193                                + users[i]);
14194                    }
14195                    break;
14196                }
14197            }
14198            if (!keep) {
14199                if (DEBUG_CLEAN_APKS) {
14200                    Slog.i(TAG, "  Removing package " + packageName);
14201                }
14202                mHandler.post(new Runnable() {
14203                    public void run() {
14204                        deletePackageX(packageName, userHandle, 0);
14205                    } //end run
14206                });
14207            }
14208        }
14209    }
14210
14211    /** Called by UserManagerService */
14212    void createNewUserLILPw(int userHandle, File path) {
14213        if (mInstaller != null) {
14214            mInstaller.createUserConfig(userHandle);
14215            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
14216        }
14217    }
14218
14219    void newUserCreatedLILPw(int userHandle) {
14220        // Adding a user requires updating runtime permissions for system apps.
14221        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
14222    }
14223
14224    @Override
14225    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
14226        mContext.enforceCallingOrSelfPermission(
14227                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14228                "Only package verification agents can read the verifier device identity");
14229
14230        synchronized (mPackages) {
14231            return mSettings.getVerifierDeviceIdentityLPw();
14232        }
14233    }
14234
14235    @Override
14236    public void setPermissionEnforced(String permission, boolean enforced) {
14237        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
14238        if (READ_EXTERNAL_STORAGE.equals(permission)) {
14239            synchronized (mPackages) {
14240                if (mSettings.mReadExternalStorageEnforced == null
14241                        || mSettings.mReadExternalStorageEnforced != enforced) {
14242                    mSettings.mReadExternalStorageEnforced = enforced;
14243                    mSettings.writeLPr();
14244                }
14245            }
14246            // kill any non-foreground processes so we restart them and
14247            // grant/revoke the GID.
14248            final IActivityManager am = ActivityManagerNative.getDefault();
14249            if (am != null) {
14250                final long token = Binder.clearCallingIdentity();
14251                try {
14252                    am.killProcessesBelowForeground("setPermissionEnforcement");
14253                } catch (RemoteException e) {
14254                } finally {
14255                    Binder.restoreCallingIdentity(token);
14256                }
14257            }
14258        } else {
14259            throw new IllegalArgumentException("No selective enforcement for " + permission);
14260        }
14261    }
14262
14263    @Override
14264    @Deprecated
14265    public boolean isPermissionEnforced(String permission) {
14266        return true;
14267    }
14268
14269    @Override
14270    public boolean isStorageLow() {
14271        final long token = Binder.clearCallingIdentity();
14272        try {
14273            final DeviceStorageMonitorInternal
14274                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14275            if (dsm != null) {
14276                return dsm.isMemoryLow();
14277            } else {
14278                return false;
14279            }
14280        } finally {
14281            Binder.restoreCallingIdentity(token);
14282        }
14283    }
14284
14285    @Override
14286    public IPackageInstaller getPackageInstaller() {
14287        return mInstallerService;
14288    }
14289
14290    private boolean userNeedsBadging(int userId) {
14291        int index = mUserNeedsBadging.indexOfKey(userId);
14292        if (index < 0) {
14293            final UserInfo userInfo;
14294            final long token = Binder.clearCallingIdentity();
14295            try {
14296                userInfo = sUserManager.getUserInfo(userId);
14297            } finally {
14298                Binder.restoreCallingIdentity(token);
14299            }
14300            final boolean b;
14301            if (userInfo != null && userInfo.isManagedProfile()) {
14302                b = true;
14303            } else {
14304                b = false;
14305            }
14306            mUserNeedsBadging.put(userId, b);
14307            return b;
14308        }
14309        return mUserNeedsBadging.valueAt(index);
14310    }
14311
14312    @Override
14313    public KeySet getKeySetByAlias(String packageName, String alias) {
14314        if (packageName == null || alias == null) {
14315            return null;
14316        }
14317        synchronized(mPackages) {
14318            final PackageParser.Package pkg = mPackages.get(packageName);
14319            if (pkg == null) {
14320                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14321                throw new IllegalArgumentException("Unknown package: " + packageName);
14322            }
14323            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14324            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
14325        }
14326    }
14327
14328    @Override
14329    public KeySet getSigningKeySet(String packageName) {
14330        if (packageName == null) {
14331            return null;
14332        }
14333        synchronized(mPackages) {
14334            final PackageParser.Package pkg = mPackages.get(packageName);
14335            if (pkg == null) {
14336                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14337                throw new IllegalArgumentException("Unknown package: " + packageName);
14338            }
14339            if (pkg.applicationInfo.uid != Binder.getCallingUid()
14340                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
14341                throw new SecurityException("May not access signing KeySet of other apps.");
14342            }
14343            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14344            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
14345        }
14346    }
14347
14348    @Override
14349    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
14350        if (packageName == null || ks == null) {
14351            return false;
14352        }
14353        synchronized(mPackages) {
14354            final PackageParser.Package pkg = mPackages.get(packageName);
14355            if (pkg == null) {
14356                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14357                throw new IllegalArgumentException("Unknown package: " + packageName);
14358            }
14359            IBinder ksh = ks.getToken();
14360            if (ksh instanceof KeySetHandle) {
14361                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14362                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
14363            }
14364            return false;
14365        }
14366    }
14367
14368    @Override
14369    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
14370        if (packageName == null || ks == null) {
14371            return false;
14372        }
14373        synchronized(mPackages) {
14374            final PackageParser.Package pkg = mPackages.get(packageName);
14375            if (pkg == null) {
14376                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14377                throw new IllegalArgumentException("Unknown package: " + packageName);
14378            }
14379            IBinder ksh = ks.getToken();
14380            if (ksh instanceof KeySetHandle) {
14381                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14382                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
14383            }
14384            return false;
14385        }
14386    }
14387
14388    public void getUsageStatsIfNoPackageUsageInfo() {
14389        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
14390            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
14391            if (usm == null) {
14392                throw new IllegalStateException("UsageStatsManager must be initialized");
14393            }
14394            long now = System.currentTimeMillis();
14395            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
14396            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
14397                String packageName = entry.getKey();
14398                PackageParser.Package pkg = mPackages.get(packageName);
14399                if (pkg == null) {
14400                    continue;
14401                }
14402                UsageStats usage = entry.getValue();
14403                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
14404                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
14405            }
14406        }
14407    }
14408
14409    /**
14410     * Check and throw if the given before/after packages would be considered a
14411     * downgrade.
14412     */
14413    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
14414            throws PackageManagerException {
14415        if (after.versionCode < before.mVersionCode) {
14416            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14417                    "Update version code " + after.versionCode + " is older than current "
14418                    + before.mVersionCode);
14419        } else if (after.versionCode == before.mVersionCode) {
14420            if (after.baseRevisionCode < before.baseRevisionCode) {
14421                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14422                        "Update base revision code " + after.baseRevisionCode
14423                        + " is older than current " + before.baseRevisionCode);
14424            }
14425
14426            if (!ArrayUtils.isEmpty(after.splitNames)) {
14427                for (int i = 0; i < after.splitNames.length; i++) {
14428                    final String splitName = after.splitNames[i];
14429                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
14430                    if (j != -1) {
14431                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
14432                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14433                                    "Update split " + splitName + " revision code "
14434                                    + after.splitRevisionCodes[i] + " is older than current "
14435                                    + before.splitRevisionCodes[j]);
14436                        }
14437                    }
14438                }
14439            }
14440        }
14441    }
14442}
14443