PackageManagerService.java revision 30ca50a3ddf35e6426e7b561b95e0864885de6d5
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
46import static android.content.pm.PackageManager.INSTALL_INTERNAL;
47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
52import static android.content.pm.PackageManager.MOVE_EXTERNAL_MEDIA;
53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
54import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
55import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
56import static android.content.pm.PackageManager.MOVE_INTERNAL;
57import static android.content.pm.PackageParser.isApkFile;
58import static android.os.Process.PACKAGE_INFO_GID;
59import static android.os.Process.SYSTEM_UID;
60import static android.system.OsConstants.O_CREAT;
61import static android.system.OsConstants.O_RDWR;
62import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
64import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
65import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
66import static com.android.internal.util.ArrayUtils.appendInt;
67import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
68import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
70import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
71import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
72
73import android.Manifest;
74import org.xmlpull.v1.XmlPullParser;
75import android.app.ActivityManager;
76import android.app.ActivityManagerNative;
77import android.app.AppGlobals;
78import android.app.IActivityManager;
79import android.app.admin.IDevicePolicyManager;
80import android.app.backup.IBackupManager;
81import android.app.usage.UsageStats;
82import android.app.usage.UsageStatsManager;
83import android.content.BroadcastReceiver;
84import android.content.ComponentName;
85import android.content.Context;
86import android.content.IIntentReceiver;
87import android.content.Intent;
88import android.content.IntentFilter;
89import android.content.IntentSender;
90import android.content.IntentSender.SendIntentException;
91import android.content.ServiceConnection;
92import android.content.pm.ActivityInfo;
93import android.content.pm.ApplicationInfo;
94import android.content.pm.FeatureInfo;
95import android.content.pm.IPackageDataObserver;
96import android.content.pm.IPackageDeleteObserver;
97import android.content.pm.IPackageDeleteObserver2;
98import android.content.pm.IPackageInstallObserver2;
99import android.content.pm.IPackageInstaller;
100import android.content.pm.IPackageManager;
101import android.content.pm.IPackageMoveObserver;
102import android.content.pm.IPackageStatsObserver;
103import android.content.pm.InstrumentationInfo;
104import android.content.pm.IntentFilterVerificationInfo;
105import android.content.pm.KeySet;
106import android.content.pm.ManifestDigest;
107import android.content.pm.PackageCleanItem;
108import android.content.pm.PackageInfo;
109import android.content.pm.PackageInfoLite;
110import android.content.pm.PackageInstaller;
111import android.content.pm.PackageManager;
112import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
113import android.content.pm.PackageParser;
114import android.content.pm.PackageParser.ActivityIntentInfo;
115import android.content.pm.PackageParser.PackageLite;
116import android.content.pm.PackageParser.PackageParserException;
117import android.content.pm.PackageStats;
118import android.content.pm.PackageUserState;
119import android.content.pm.ParceledListSlice;
120import android.content.pm.PermissionGroupInfo;
121import android.content.pm.PermissionInfo;
122import android.content.pm.ProviderInfo;
123import android.content.pm.ResolveInfo;
124import android.content.pm.ServiceInfo;
125import android.content.pm.Signature;
126import android.content.pm.UserInfo;
127import android.content.pm.VerificationParams;
128import android.content.pm.VerifierDeviceIdentity;
129import android.content.pm.VerifierInfo;
130import android.content.res.Resources;
131import android.hardware.display.DisplayManager;
132import android.net.Uri;
133import android.os.Binder;
134import android.os.Build;
135import android.os.Bundle;
136import android.os.Debug;
137import android.os.Environment;
138import android.os.Environment.UserEnvironment;
139import android.os.FileUtils;
140import android.os.Handler;
141import android.os.IBinder;
142import android.os.Looper;
143import android.os.Message;
144import android.os.Parcel;
145import android.os.ParcelFileDescriptor;
146import android.os.Process;
147import android.os.RemoteException;
148import android.os.SELinux;
149import android.os.ServiceManager;
150import android.os.SystemClock;
151import android.os.SystemProperties;
152import android.os.UserHandle;
153import android.os.UserManager;
154import android.os.storage.IMountService;
155import android.os.storage.StorageEventListener;
156import android.os.storage.StorageManager;
157import android.os.storage.VolumeInfo;
158import android.security.KeyStore;
159import android.security.SystemKeyStore;
160import android.system.ErrnoException;
161import android.system.Os;
162import android.system.StructStat;
163import android.text.TextUtils;
164import android.text.format.DateUtils;
165import android.util.ArrayMap;
166import android.util.ArraySet;
167import android.util.AtomicFile;
168import android.util.DisplayMetrics;
169import android.util.EventLog;
170import android.util.ExceptionUtils;
171import android.util.Log;
172import android.util.LogPrinter;
173import android.util.PrintStreamPrinter;
174import android.util.Slog;
175import android.util.SparseArray;
176import android.util.SparseBooleanArray;
177import android.util.Xml;
178import android.view.Display;
179
180import dalvik.system.DexFile;
181import dalvik.system.VMRuntime;
182
183import libcore.io.IoUtils;
184import libcore.util.EmptyArray;
185
186import com.android.internal.R;
187import com.android.internal.app.IMediaContainerService;
188import com.android.internal.app.ResolverActivity;
189import com.android.internal.content.NativeLibraryHelper;
190import com.android.internal.content.PackageHelper;
191import com.android.internal.os.IParcelFileDescriptorFactory;
192import com.android.internal.util.ArrayUtils;
193import com.android.internal.util.FastPrintWriter;
194import com.android.internal.util.FastXmlSerializer;
195import com.android.internal.util.IndentingPrintWriter;
196import com.android.server.EventLogTags;
197import com.android.server.IntentResolver;
198import com.android.server.LocalServices;
199import com.android.server.ServiceThread;
200import com.android.server.SystemConfig;
201import com.android.server.Watchdog;
202import com.android.server.pm.Settings.DatabaseVersion;
203import com.android.server.storage.DeviceStorageMonitorInternal;
204
205import org.xmlpull.v1.XmlSerializer;
206
207import java.io.BufferedInputStream;
208import java.io.BufferedOutputStream;
209import java.io.BufferedReader;
210import java.io.ByteArrayInputStream;
211import java.io.ByteArrayOutputStream;
212import java.io.File;
213import java.io.FileDescriptor;
214import java.io.FileNotFoundException;
215import java.io.FileOutputStream;
216import java.io.FileReader;
217import java.io.FilenameFilter;
218import java.io.IOException;
219import java.io.InputStream;
220import java.io.PrintWriter;
221import java.nio.charset.StandardCharsets;
222import java.security.NoSuchAlgorithmException;
223import java.security.PublicKey;
224import java.security.cert.CertificateEncodingException;
225import java.security.cert.CertificateException;
226import java.text.SimpleDateFormat;
227import java.util.ArrayList;
228import java.util.Arrays;
229import java.util.Collection;
230import java.util.Collections;
231import java.util.Comparator;
232import java.util.Date;
233import java.util.Iterator;
234import java.util.List;
235import java.util.Map;
236import java.util.Objects;
237import java.util.Set;
238import java.util.concurrent.atomic.AtomicBoolean;
239import java.util.concurrent.atomic.AtomicLong;
240
241/**
242 * Keep track of all those .apks everywhere.
243 *
244 * This is very central to the platform's security; please run the unit
245 * tests whenever making modifications here:
246 *
247mmm frameworks/base/tests/AndroidTests
248adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
249adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
250 *
251 * {@hide}
252 */
253public class PackageManagerService extends IPackageManager.Stub {
254    static final String TAG = "PackageManager";
255    static final boolean DEBUG_SETTINGS = false;
256    static final boolean DEBUG_PREFERRED = false;
257    static final boolean DEBUG_UPGRADE = false;
258    private static final boolean DEBUG_BACKUP = true;
259    private static final boolean DEBUG_INSTALL = false;
260    private static final boolean DEBUG_REMOVE = false;
261    private static final boolean DEBUG_BROADCASTS = false;
262    private static final boolean DEBUG_SHOW_INFO = false;
263    private static final boolean DEBUG_PACKAGE_INFO = false;
264    private static final boolean DEBUG_INTENT_MATCHING = false;
265    private static final boolean DEBUG_PACKAGE_SCANNING = false;
266    private static final boolean DEBUG_VERIFY = false;
267    private static final boolean DEBUG_DEXOPT = false;
268    private static final boolean DEBUG_ABI_SELECTION = false;
269
270    static final boolean RUNTIME_PERMISSIONS_ENABLED = true;
271
272    private static final int RADIO_UID = Process.PHONE_UID;
273    private static final int LOG_UID = Process.LOG_UID;
274    private static final int NFC_UID = Process.NFC_UID;
275    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
276    private static final int SHELL_UID = Process.SHELL_UID;
277
278    // Cap the size of permission trees that 3rd party apps can define
279    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
280
281    // Suffix used during package installation when copying/moving
282    // package apks to install directory.
283    private static final String INSTALL_PACKAGE_SUFFIX = "-";
284
285    static final int SCAN_NO_DEX = 1<<1;
286    static final int SCAN_FORCE_DEX = 1<<2;
287    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
288    static final int SCAN_NEW_INSTALL = 1<<4;
289    static final int SCAN_NO_PATHS = 1<<5;
290    static final int SCAN_UPDATE_TIME = 1<<6;
291    static final int SCAN_DEFER_DEX = 1<<7;
292    static final int SCAN_BOOTING = 1<<8;
293    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
294    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
295    static final int SCAN_REPLACING = 1<<11;
296    static final int SCAN_REQUIRE_KNOWN = 1<<12;
297
298    static final int REMOVE_CHATTY = 1<<16;
299
300    /**
301     * Timeout (in milliseconds) after which the watchdog should declare that
302     * our handler thread is wedged.  The usual default for such things is one
303     * minute but we sometimes do very lengthy I/O operations on this thread,
304     * such as installing multi-gigabyte applications, so ours needs to be longer.
305     */
306    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
307
308    /**
309     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
310     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
311     * settings entry if available, otherwise we use the hardcoded default.  If it's been
312     * more than this long since the last fstrim, we force one during the boot sequence.
313     *
314     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
315     * one gets run at the next available charging+idle time.  This final mandatory
316     * no-fstrim check kicks in only of the other scheduling criteria is never met.
317     */
318    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
319
320    /**
321     * Whether verification is enabled by default.
322     */
323    private static final boolean DEFAULT_VERIFY_ENABLE = true;
324
325    /**
326     * The default maximum time to wait for the verification agent to return in
327     * milliseconds.
328     */
329    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
330
331    /**
332     * The default response for package verification timeout.
333     *
334     * This can be either PackageManager.VERIFICATION_ALLOW or
335     * PackageManager.VERIFICATION_REJECT.
336     */
337    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
338
339    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
340
341    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
342            DEFAULT_CONTAINER_PACKAGE,
343            "com.android.defcontainer.DefaultContainerService");
344
345    private static final String KILL_APP_REASON_GIDS_CHANGED =
346            "permission grant or revoke changed gids";
347
348    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
349            "permissions revoked";
350
351    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
352
353    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
354
355    /** Permission grant: not grant the permission. */
356    private static final int GRANT_DENIED = 1;
357
358    /** Permission grant: grant the permission as an install permission. */
359    private static final int GRANT_INSTALL = 2;
360
361    /** Permission grant: grant the permission as a runtime one. */
362    private static final int GRANT_RUNTIME = 3;
363
364    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
365    private static final int GRANT_UPGRADE = 4;
366
367    final ServiceThread mHandlerThread;
368
369    final PackageHandler mHandler;
370
371    /**
372     * Messages for {@link #mHandler} that need to wait for system ready before
373     * being dispatched.
374     */
375    private ArrayList<Message> mPostSystemReadyMessages;
376
377    final int mSdkVersion = Build.VERSION.SDK_INT;
378
379    final Context mContext;
380    final boolean mFactoryTest;
381    final boolean mOnlyCore;
382    final boolean mLazyDexOpt;
383    final long mDexOptLRUThresholdInMills;
384    final DisplayMetrics mMetrics;
385    final int mDefParseFlags;
386    final String[] mSeparateProcesses;
387    final boolean mIsUpgrade;
388
389    // This is where all application persistent data goes.
390    final File mAppDataDir;
391
392    // This is where all application persistent data goes for secondary users.
393    final File mUserAppDataDir;
394
395    /** The location for ASEC container files on internal storage. */
396    final String mAsecInternalPath;
397
398    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
399    // LOCK HELD.  Can be called with mInstallLock held.
400    final Installer mInstaller;
401
402    /** Directory where installed third-party apps stored */
403    final File mAppInstallDir;
404
405    /**
406     * Directory to which applications installed internally have their
407     * 32 bit native libraries copied.
408     */
409    private File mAppLib32InstallDir;
410
411    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
412    // apps.
413    final File mDrmAppPrivateInstallDir;
414
415    // ----------------------------------------------------------------
416
417    // Lock for state used when installing and doing other long running
418    // operations.  Methods that must be called with this lock held have
419    // the suffix "LI".
420    final Object mInstallLock = new Object();
421
422    // ----------------------------------------------------------------
423
424    // Keys are String (package name), values are Package.  This also serves
425    // as the lock for the global state.  Methods that must be called with
426    // this lock held have the prefix "LP".
427    final ArrayMap<String, PackageParser.Package> mPackages =
428            new ArrayMap<String, PackageParser.Package>();
429
430    // Tracks available target package names -> overlay package paths.
431    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
432        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
433
434    final Settings mSettings;
435    boolean mRestoredSettings;
436
437    // System configuration read by SystemConfig.
438    final int[] mGlobalGids;
439    final SparseArray<ArraySet<String>> mSystemPermissions;
440    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
441
442    // If mac_permissions.xml was found for seinfo labeling.
443    boolean mFoundPolicyFile;
444
445    // If a recursive restorecon of /data/data/<pkg> is needed.
446    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
447
448    public static final class SharedLibraryEntry {
449        public final String path;
450        public final String apk;
451
452        SharedLibraryEntry(String _path, String _apk) {
453            path = _path;
454            apk = _apk;
455        }
456    }
457
458    // Currently known shared libraries.
459    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
460            new ArrayMap<String, SharedLibraryEntry>();
461
462    // All available activities, for your resolving pleasure.
463    final ActivityIntentResolver mActivities =
464            new ActivityIntentResolver();
465
466    // All available receivers, for your resolving pleasure.
467    final ActivityIntentResolver mReceivers =
468            new ActivityIntentResolver();
469
470    // All available services, for your resolving pleasure.
471    final ServiceIntentResolver mServices = new ServiceIntentResolver();
472
473    // All available providers, for your resolving pleasure.
474    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
475
476    // Mapping from provider base names (first directory in content URI codePath)
477    // to the provider information.
478    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
479            new ArrayMap<String, PackageParser.Provider>();
480
481    // Mapping from instrumentation class names to info about them.
482    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
483            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
484
485    // Mapping from permission names to info about them.
486    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
487            new ArrayMap<String, PackageParser.PermissionGroup>();
488
489    // Packages whose data we have transfered into another package, thus
490    // should no longer exist.
491    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
492
493    // Broadcast actions that are only available to the system.
494    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
495
496    /** List of packages waiting for verification. */
497    final SparseArray<PackageVerificationState> mPendingVerification
498            = new SparseArray<PackageVerificationState>();
499
500    /** Set of packages associated with each app op permission. */
501    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
502
503    final PackageInstallerService mInstallerService;
504
505    private final PackageDexOptimizer mPackageDexOptimizer;
506    // Cache of users who need badging.
507    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
508
509    /** Token for keys in mPendingVerification. */
510    private int mPendingVerificationToken = 0;
511
512    volatile boolean mSystemReady;
513    volatile boolean mSafeMode;
514    volatile boolean mHasSystemUidErrors;
515
516    ApplicationInfo mAndroidApplication;
517    final ActivityInfo mResolveActivity = new ActivityInfo();
518    final ResolveInfo mResolveInfo = new ResolveInfo();
519    ComponentName mResolveComponentName;
520    PackageParser.Package mPlatformPackage;
521    ComponentName mCustomResolverComponentName;
522
523    boolean mResolverReplaced = false;
524
525    private final ComponentName mIntentFilterVerifierComponent;
526    private int mIntentFilterVerificationToken = 0;
527
528    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
529            = new SparseArray<IntentFilterVerificationState>();
530
531    private interface IntentFilterVerifier<T extends IntentFilter> {
532        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
533                                               T filter, String packageName);
534        void startVerifications(int userId);
535        void receiveVerificationResponse(int verificationId);
536    }
537
538    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
539        private Context mContext;
540        private ComponentName mIntentFilterVerifierComponent;
541        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
542
543        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
544            mContext = context;
545            mIntentFilterVerifierComponent = verifierComponent;
546        }
547
548        private String getDefaultScheme() {
549            // TODO: replace SCHEME_HTTP with SCHEME_HTTPS
550            return IntentFilter.SCHEME_HTTP;
551        }
552
553        @Override
554        public void startVerifications(int userId) {
555            // Launch verifications requests
556            int count = mCurrentIntentFilterVerifications.size();
557            for (int n=0; n<count; n++) {
558                int verificationId = mCurrentIntentFilterVerifications.get(n);
559                final IntentFilterVerificationState ivs =
560                        mIntentFilterVerificationStates.get(verificationId);
561
562                String packageName = ivs.getPackageName();
563
564                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
565                final int filterCount = filters.size();
566                ArraySet<String> domainsSet = new ArraySet<>();
567                for (int m=0; m<filterCount; m++) {
568                    PackageParser.ActivityIntentInfo filter = filters.get(m);
569                    domainsSet.addAll(filter.getHostsList());
570                }
571                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
572                synchronized (mPackages) {
573                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
574                            packageName, domainsList) != null) {
575                        scheduleWriteSettingsLocked();
576                    }
577                }
578                sendVerificationRequest(userId, verificationId, ivs);
579            }
580            mCurrentIntentFilterVerifications.clear();
581        }
582
583        private void sendVerificationRequest(int userId, int verificationId,
584                IntentFilterVerificationState ivs) {
585
586            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
587            verificationIntent.putExtra(
588                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
589                    verificationId);
590            verificationIntent.putExtra(
591                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
592                    getDefaultScheme());
593            verificationIntent.putExtra(
594                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
595                    ivs.getHostsString());
596            verificationIntent.putExtra(
597                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
598                    ivs.getPackageName());
599            verificationIntent.setComponent(mIntentFilterVerifierComponent);
600            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
601
602            UserHandle user = new UserHandle(userId);
603            mContext.sendBroadcastAsUser(verificationIntent, user);
604            Slog.d(TAG, "Sending IntenFilter verification broadcast");
605        }
606
607        public void receiveVerificationResponse(int verificationId) {
608            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
609
610            final boolean verified = ivs.isVerified();
611
612            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
613            final int count = filters.size();
614            for (int n=0; n<count; n++) {
615                PackageParser.ActivityIntentInfo filter = filters.get(n);
616                filter.setVerified(verified);
617
618                Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:"
619                        + verified + " and hosts:" + ivs.getHostsString());
620            }
621
622            mIntentFilterVerificationStates.remove(verificationId);
623
624            final String packageName = ivs.getPackageName();
625            IntentFilterVerificationInfo ivi = null;
626
627            synchronized (mPackages) {
628                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
629            }
630            if (ivi == null) {
631                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
632                        + verificationId + " packageName:" + packageName);
633                return;
634            }
635            Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:"
636                    + verificationId);
637
638            synchronized (mPackages) {
639                if (verified) {
640                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
641                } else {
642                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
643                }
644                scheduleWriteSettingsLocked();
645
646                final int userId = ivs.getUserId();
647                if (userId != UserHandle.USER_ALL) {
648                    final int userStatus =
649                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
650
651                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
652                    boolean needUpdate = false;
653
654                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
655                    // already been set by the User thru the Disambiguation dialog
656                    switch (userStatus) {
657                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
658                            if (verified) {
659                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
660                            } else {
661                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
662                            }
663                            needUpdate = true;
664                            break;
665
666                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
667                            if (verified) {
668                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
669                                needUpdate = true;
670                            }
671                            break;
672
673                        default:
674                            // Nothing to do
675                    }
676
677                    if (needUpdate) {
678                        mSettings.updateIntentFilterVerificationStatusLPw(
679                                packageName, updatedStatus, userId);
680                        scheduleWritePackageRestrictionsLocked(userId);
681                    }
682                }
683            }
684        }
685
686        @Override
687        public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
688                    ActivityIntentInfo filter, String packageName) {
689            if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
690                    filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
691                Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme");
692                return false;
693            }
694            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
695            if (ivs == null) {
696                ivs = createDomainVerificationState(verifierId, userId, verificationId,
697                        packageName);
698            }
699            if (!hasValidDomains(filter)) {
700                return false;
701            }
702            ivs.addFilter(filter);
703            return true;
704        }
705
706        private IntentFilterVerificationState createDomainVerificationState(int verifierId,
707                int userId, int verificationId, String packageName) {
708            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
709                    verifierId, userId, packageName);
710            ivs.setPendingState();
711            synchronized (mPackages) {
712                mIntentFilterVerificationStates.append(verificationId, ivs);
713                mCurrentIntentFilterVerifications.add(verificationId);
714            }
715            return ivs;
716        }
717    }
718
719    private static boolean hasValidDomains(ActivityIntentInfo filter) {
720        return hasValidDomains(filter, true);
721    }
722
723    private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) {
724        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
725                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
726        if (!hasHTTPorHTTPS) {
727            if (logging) {
728                Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme");
729            }
730            return false;
731        }
732        return true;
733    }
734
735    private IntentFilterVerifier mIntentFilterVerifier;
736
737    // Set of pending broadcasts for aggregating enable/disable of components.
738    static class PendingPackageBroadcasts {
739        // for each user id, a map of <package name -> components within that package>
740        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
741
742        public PendingPackageBroadcasts() {
743            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
744        }
745
746        public ArrayList<String> get(int userId, String packageName) {
747            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
748            return packages.get(packageName);
749        }
750
751        public void put(int userId, String packageName, ArrayList<String> components) {
752            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
753            packages.put(packageName, components);
754        }
755
756        public void remove(int userId, String packageName) {
757            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
758            if (packages != null) {
759                packages.remove(packageName);
760            }
761        }
762
763        public void remove(int userId) {
764            mUidMap.remove(userId);
765        }
766
767        public int userIdCount() {
768            return mUidMap.size();
769        }
770
771        public int userIdAt(int n) {
772            return mUidMap.keyAt(n);
773        }
774
775        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
776            return mUidMap.get(userId);
777        }
778
779        public int size() {
780            // total number of pending broadcast entries across all userIds
781            int num = 0;
782            for (int i = 0; i< mUidMap.size(); i++) {
783                num += mUidMap.valueAt(i).size();
784            }
785            return num;
786        }
787
788        public void clear() {
789            mUidMap.clear();
790        }
791
792        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
793            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
794            if (map == null) {
795                map = new ArrayMap<String, ArrayList<String>>();
796                mUidMap.put(userId, map);
797            }
798            return map;
799        }
800    }
801    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
802
803    // Service Connection to remote media container service to copy
804    // package uri's from external media onto secure containers
805    // or internal storage.
806    private IMediaContainerService mContainerService = null;
807
808    static final int SEND_PENDING_BROADCAST = 1;
809    static final int MCS_BOUND = 3;
810    static final int END_COPY = 4;
811    static final int INIT_COPY = 5;
812    static final int MCS_UNBIND = 6;
813    static final int START_CLEANING_PACKAGE = 7;
814    static final int FIND_INSTALL_LOC = 8;
815    static final int POST_INSTALL = 9;
816    static final int MCS_RECONNECT = 10;
817    static final int MCS_GIVE_UP = 11;
818    static final int UPDATED_MEDIA_STATUS = 12;
819    static final int WRITE_SETTINGS = 13;
820    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
821    static final int PACKAGE_VERIFIED = 15;
822    static final int CHECK_PENDING_VERIFICATION = 16;
823    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
824    static final int INTENT_FILTER_VERIFIED = 18;
825
826    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
827
828    // Delay time in millisecs
829    static final int BROADCAST_DELAY = 10 * 1000;
830
831    static UserManagerService sUserManager;
832
833    // Stores a list of users whose package restrictions file needs to be updated
834    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
835
836    final private DefaultContainerConnection mDefContainerConn =
837            new DefaultContainerConnection();
838    class DefaultContainerConnection implements ServiceConnection {
839        public void onServiceConnected(ComponentName name, IBinder service) {
840            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
841            IMediaContainerService imcs =
842                IMediaContainerService.Stub.asInterface(service);
843            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
844        }
845
846        public void onServiceDisconnected(ComponentName name) {
847            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
848        }
849    };
850
851    // Recordkeeping of restore-after-install operations that are currently in flight
852    // between the Package Manager and the Backup Manager
853    class PostInstallData {
854        public InstallArgs args;
855        public PackageInstalledInfo res;
856
857        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
858            args = _a;
859            res = _r;
860        }
861    };
862    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
863    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
864
865    // backup/restore of preferred activity state
866    private static final String TAG_PREFERRED_BACKUP = "pa";
867
868    private final String mRequiredVerifierPackage;
869
870    private final PackageUsage mPackageUsage = new PackageUsage();
871
872    private class PackageUsage {
873        private static final int WRITE_INTERVAL
874            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
875
876        private final Object mFileLock = new Object();
877        private final AtomicLong mLastWritten = new AtomicLong(0);
878        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
879
880        private boolean mIsHistoricalPackageUsageAvailable = true;
881
882        boolean isHistoricalPackageUsageAvailable() {
883            return mIsHistoricalPackageUsageAvailable;
884        }
885
886        void write(boolean force) {
887            if (force) {
888                writeInternal();
889                return;
890            }
891            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
892                && !DEBUG_DEXOPT) {
893                return;
894            }
895            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
896                new Thread("PackageUsage_DiskWriter") {
897                    @Override
898                    public void run() {
899                        try {
900                            writeInternal();
901                        } finally {
902                            mBackgroundWriteRunning.set(false);
903                        }
904                    }
905                }.start();
906            }
907        }
908
909        private void writeInternal() {
910            synchronized (mPackages) {
911                synchronized (mFileLock) {
912                    AtomicFile file = getFile();
913                    FileOutputStream f = null;
914                    try {
915                        f = file.startWrite();
916                        BufferedOutputStream out = new BufferedOutputStream(f);
917                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
918                        StringBuilder sb = new StringBuilder();
919                        for (PackageParser.Package pkg : mPackages.values()) {
920                            if (pkg.mLastPackageUsageTimeInMills == 0) {
921                                continue;
922                            }
923                            sb.setLength(0);
924                            sb.append(pkg.packageName);
925                            sb.append(' ');
926                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
927                            sb.append('\n');
928                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
929                        }
930                        out.flush();
931                        file.finishWrite(f);
932                    } catch (IOException e) {
933                        if (f != null) {
934                            file.failWrite(f);
935                        }
936                        Log.e(TAG, "Failed to write package usage times", e);
937                    }
938                }
939            }
940            mLastWritten.set(SystemClock.elapsedRealtime());
941        }
942
943        void readLP() {
944            synchronized (mFileLock) {
945                AtomicFile file = getFile();
946                BufferedInputStream in = null;
947                try {
948                    in = new BufferedInputStream(file.openRead());
949                    StringBuffer sb = new StringBuffer();
950                    while (true) {
951                        String packageName = readToken(in, sb, ' ');
952                        if (packageName == null) {
953                            break;
954                        }
955                        String timeInMillisString = readToken(in, sb, '\n');
956                        if (timeInMillisString == null) {
957                            throw new IOException("Failed to find last usage time for package "
958                                                  + packageName);
959                        }
960                        PackageParser.Package pkg = mPackages.get(packageName);
961                        if (pkg == null) {
962                            continue;
963                        }
964                        long timeInMillis;
965                        try {
966                            timeInMillis = Long.parseLong(timeInMillisString.toString());
967                        } catch (NumberFormatException e) {
968                            throw new IOException("Failed to parse " + timeInMillisString
969                                                  + " as a long.", e);
970                        }
971                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
972                    }
973                } catch (FileNotFoundException expected) {
974                    mIsHistoricalPackageUsageAvailable = false;
975                } catch (IOException e) {
976                    Log.w(TAG, "Failed to read package usage times", e);
977                } finally {
978                    IoUtils.closeQuietly(in);
979                }
980            }
981            mLastWritten.set(SystemClock.elapsedRealtime());
982        }
983
984        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
985                throws IOException {
986            sb.setLength(0);
987            while (true) {
988                int ch = in.read();
989                if (ch == -1) {
990                    if (sb.length() == 0) {
991                        return null;
992                    }
993                    throw new IOException("Unexpected EOF");
994                }
995                if (ch == endOfToken) {
996                    return sb.toString();
997                }
998                sb.append((char)ch);
999            }
1000        }
1001
1002        private AtomicFile getFile() {
1003            File dataDir = Environment.getDataDirectory();
1004            File systemDir = new File(dataDir, "system");
1005            File fname = new File(systemDir, "package-usage.list");
1006            return new AtomicFile(fname);
1007        }
1008    }
1009
1010    class PackageHandler extends Handler {
1011        private boolean mBound = false;
1012        final ArrayList<HandlerParams> mPendingInstalls =
1013            new ArrayList<HandlerParams>();
1014
1015        private boolean connectToService() {
1016            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1017                    " DefaultContainerService");
1018            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1019            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1020            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1021                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1022                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1023                mBound = true;
1024                return true;
1025            }
1026            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1027            return false;
1028        }
1029
1030        private void disconnectService() {
1031            mContainerService = null;
1032            mBound = false;
1033            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1034            mContext.unbindService(mDefContainerConn);
1035            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1036        }
1037
1038        PackageHandler(Looper looper) {
1039            super(looper);
1040        }
1041
1042        public void handleMessage(Message msg) {
1043            try {
1044                doHandleMessage(msg);
1045            } finally {
1046                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1047            }
1048        }
1049
1050        void doHandleMessage(Message msg) {
1051            switch (msg.what) {
1052                case INIT_COPY: {
1053                    HandlerParams params = (HandlerParams) msg.obj;
1054                    int idx = mPendingInstalls.size();
1055                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1056                    // If a bind was already initiated we dont really
1057                    // need to do anything. The pending install
1058                    // will be processed later on.
1059                    if (!mBound) {
1060                        // If this is the only one pending we might
1061                        // have to bind to the service again.
1062                        if (!connectToService()) {
1063                            Slog.e(TAG, "Failed to bind to media container service");
1064                            params.serviceError();
1065                            return;
1066                        } else {
1067                            // Once we bind to the service, the first
1068                            // pending request will be processed.
1069                            mPendingInstalls.add(idx, params);
1070                        }
1071                    } else {
1072                        mPendingInstalls.add(idx, params);
1073                        // Already bound to the service. Just make
1074                        // sure we trigger off processing the first request.
1075                        if (idx == 0) {
1076                            mHandler.sendEmptyMessage(MCS_BOUND);
1077                        }
1078                    }
1079                    break;
1080                }
1081                case MCS_BOUND: {
1082                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1083                    if (msg.obj != null) {
1084                        mContainerService = (IMediaContainerService) msg.obj;
1085                    }
1086                    if (mContainerService == null) {
1087                        // Something seriously wrong. Bail out
1088                        Slog.e(TAG, "Cannot bind to media container service");
1089                        for (HandlerParams params : mPendingInstalls) {
1090                            // Indicate service bind error
1091                            params.serviceError();
1092                        }
1093                        mPendingInstalls.clear();
1094                    } else if (mPendingInstalls.size() > 0) {
1095                        HandlerParams params = mPendingInstalls.get(0);
1096                        if (params != null) {
1097                            if (params.startCopy()) {
1098                                // We are done...  look for more work or to
1099                                // go idle.
1100                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1101                                        "Checking for more work or unbind...");
1102                                // Delete pending install
1103                                if (mPendingInstalls.size() > 0) {
1104                                    mPendingInstalls.remove(0);
1105                                }
1106                                if (mPendingInstalls.size() == 0) {
1107                                    if (mBound) {
1108                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1109                                                "Posting delayed MCS_UNBIND");
1110                                        removeMessages(MCS_UNBIND);
1111                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1112                                        // Unbind after a little delay, to avoid
1113                                        // continual thrashing.
1114                                        sendMessageDelayed(ubmsg, 10000);
1115                                    }
1116                                } else {
1117                                    // There are more pending requests in queue.
1118                                    // Just post MCS_BOUND message to trigger processing
1119                                    // of next pending install.
1120                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1121                                            "Posting MCS_BOUND for next work");
1122                                    mHandler.sendEmptyMessage(MCS_BOUND);
1123                                }
1124                            }
1125                        }
1126                    } else {
1127                        // Should never happen ideally.
1128                        Slog.w(TAG, "Empty queue");
1129                    }
1130                    break;
1131                }
1132                case MCS_RECONNECT: {
1133                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1134                    if (mPendingInstalls.size() > 0) {
1135                        if (mBound) {
1136                            disconnectService();
1137                        }
1138                        if (!connectToService()) {
1139                            Slog.e(TAG, "Failed to bind to media container service");
1140                            for (HandlerParams params : mPendingInstalls) {
1141                                // Indicate service bind error
1142                                params.serviceError();
1143                            }
1144                            mPendingInstalls.clear();
1145                        }
1146                    }
1147                    break;
1148                }
1149                case MCS_UNBIND: {
1150                    // If there is no actual work left, then time to unbind.
1151                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1152
1153                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1154                        if (mBound) {
1155                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1156
1157                            disconnectService();
1158                        }
1159                    } else if (mPendingInstalls.size() > 0) {
1160                        // There are more pending requests in queue.
1161                        // Just post MCS_BOUND message to trigger processing
1162                        // of next pending install.
1163                        mHandler.sendEmptyMessage(MCS_BOUND);
1164                    }
1165
1166                    break;
1167                }
1168                case MCS_GIVE_UP: {
1169                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1170                    mPendingInstalls.remove(0);
1171                    break;
1172                }
1173                case SEND_PENDING_BROADCAST: {
1174                    String packages[];
1175                    ArrayList<String> components[];
1176                    int size = 0;
1177                    int uids[];
1178                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1179                    synchronized (mPackages) {
1180                        if (mPendingBroadcasts == null) {
1181                            return;
1182                        }
1183                        size = mPendingBroadcasts.size();
1184                        if (size <= 0) {
1185                            // Nothing to be done. Just return
1186                            return;
1187                        }
1188                        packages = new String[size];
1189                        components = new ArrayList[size];
1190                        uids = new int[size];
1191                        int i = 0;  // filling out the above arrays
1192
1193                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1194                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1195                            Iterator<Map.Entry<String, ArrayList<String>>> it
1196                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1197                                            .entrySet().iterator();
1198                            while (it.hasNext() && i < size) {
1199                                Map.Entry<String, ArrayList<String>> ent = it.next();
1200                                packages[i] = ent.getKey();
1201                                components[i] = ent.getValue();
1202                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1203                                uids[i] = (ps != null)
1204                                        ? UserHandle.getUid(packageUserId, ps.appId)
1205                                        : -1;
1206                                i++;
1207                            }
1208                        }
1209                        size = i;
1210                        mPendingBroadcasts.clear();
1211                    }
1212                    // Send broadcasts
1213                    for (int i = 0; i < size; i++) {
1214                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1215                    }
1216                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1217                    break;
1218                }
1219                case START_CLEANING_PACKAGE: {
1220                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1221                    final String packageName = (String)msg.obj;
1222                    final int userId = msg.arg1;
1223                    final boolean andCode = msg.arg2 != 0;
1224                    synchronized (mPackages) {
1225                        if (userId == UserHandle.USER_ALL) {
1226                            int[] users = sUserManager.getUserIds();
1227                            for (int user : users) {
1228                                mSettings.addPackageToCleanLPw(
1229                                        new PackageCleanItem(user, packageName, andCode));
1230                            }
1231                        } else {
1232                            mSettings.addPackageToCleanLPw(
1233                                    new PackageCleanItem(userId, packageName, andCode));
1234                        }
1235                    }
1236                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1237                    startCleaningPackages();
1238                } break;
1239                case POST_INSTALL: {
1240                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1241                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1242                    mRunningInstalls.delete(msg.arg1);
1243                    boolean deleteOld = false;
1244
1245                    if (data != null) {
1246                        InstallArgs args = data.args;
1247                        PackageInstalledInfo res = data.res;
1248
1249                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1250                            res.removedInfo.sendBroadcast(false, true, false);
1251                            Bundle extras = new Bundle(1);
1252                            extras.putInt(Intent.EXTRA_UID, res.uid);
1253
1254                            // Now that we successfully installed the package, grant runtime
1255                            // permissions if requested before broadcasting the install.
1256                            if ((args.installFlags
1257                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1258                                grantRequestedRuntimePermissions(res.pkg,
1259                                        args.user.getIdentifier());
1260                            }
1261
1262                            // Determine the set of users who are adding this
1263                            // package for the first time vs. those who are seeing
1264                            // an update.
1265                            int[] firstUsers;
1266                            int[] updateUsers = new int[0];
1267                            if (res.origUsers == null || res.origUsers.length == 0) {
1268                                firstUsers = res.newUsers;
1269                            } else {
1270                                firstUsers = new int[0];
1271                                for (int i=0; i<res.newUsers.length; i++) {
1272                                    int user = res.newUsers[i];
1273                                    boolean isNew = true;
1274                                    for (int j=0; j<res.origUsers.length; j++) {
1275                                        if (res.origUsers[j] == user) {
1276                                            isNew = false;
1277                                            break;
1278                                        }
1279                                    }
1280                                    if (isNew) {
1281                                        int[] newFirst = new int[firstUsers.length+1];
1282                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1283                                                firstUsers.length);
1284                                        newFirst[firstUsers.length] = user;
1285                                        firstUsers = newFirst;
1286                                    } else {
1287                                        int[] newUpdate = new int[updateUsers.length+1];
1288                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1289                                                updateUsers.length);
1290                                        newUpdate[updateUsers.length] = user;
1291                                        updateUsers = newUpdate;
1292                                    }
1293                                }
1294                            }
1295                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1296                                    res.pkg.applicationInfo.packageName,
1297                                    extras, null, null, firstUsers);
1298                            final boolean update = res.removedInfo.removedPackage != null;
1299                            if (update) {
1300                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1301                            }
1302                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1303                                    res.pkg.applicationInfo.packageName,
1304                                    extras, null, null, updateUsers);
1305                            if (update) {
1306                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1307                                        res.pkg.applicationInfo.packageName,
1308                                        extras, null, null, updateUsers);
1309                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1310                                        null, null,
1311                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1312
1313                                // treat asec-hosted packages like removable media on upgrade
1314                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1315                                    if (DEBUG_INSTALL) {
1316                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1317                                                + " is ASEC-hosted -> AVAILABLE");
1318                                    }
1319                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1320                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1321                                    pkgList.add(res.pkg.applicationInfo.packageName);
1322                                    sendResourcesChangedBroadcast(true, true,
1323                                            pkgList,uidArray, null);
1324                                }
1325                            }
1326                            if (res.removedInfo.args != null) {
1327                                // Remove the replaced package's older resources safely now
1328                                deleteOld = true;
1329                            }
1330
1331                            // Log current value of "unknown sources" setting
1332                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1333                                getUnknownSourcesSettings());
1334                        }
1335                        // Force a gc to clear up things
1336                        Runtime.getRuntime().gc();
1337                        // We delete after a gc for applications  on sdcard.
1338                        if (deleteOld) {
1339                            synchronized (mInstallLock) {
1340                                res.removedInfo.args.doPostDeleteLI(true);
1341                            }
1342                        }
1343                        if (args.observer != null) {
1344                            try {
1345                                Bundle extras = extrasForInstallResult(res);
1346                                args.observer.onPackageInstalled(res.name, res.returnCode,
1347                                        res.returnMsg, extras);
1348                            } catch (RemoteException e) {
1349                                Slog.i(TAG, "Observer no longer exists.");
1350                            }
1351                        }
1352                    } else {
1353                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1354                    }
1355                } break;
1356                case UPDATED_MEDIA_STATUS: {
1357                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1358                    boolean reportStatus = msg.arg1 == 1;
1359                    boolean doGc = msg.arg2 == 1;
1360                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1361                    if (doGc) {
1362                        // Force a gc to clear up stale containers.
1363                        Runtime.getRuntime().gc();
1364                    }
1365                    if (msg.obj != null) {
1366                        @SuppressWarnings("unchecked")
1367                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1368                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1369                        // Unload containers
1370                        unloadAllContainers(args);
1371                    }
1372                    if (reportStatus) {
1373                        try {
1374                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1375                            PackageHelper.getMountService().finishMediaUpdate();
1376                        } catch (RemoteException e) {
1377                            Log.e(TAG, "MountService not running?");
1378                        }
1379                    }
1380                } break;
1381                case WRITE_SETTINGS: {
1382                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1383                    synchronized (mPackages) {
1384                        removeMessages(WRITE_SETTINGS);
1385                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1386                        mSettings.writeLPr();
1387                        mDirtyUsers.clear();
1388                    }
1389                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1390                } break;
1391                case WRITE_PACKAGE_RESTRICTIONS: {
1392                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1393                    synchronized (mPackages) {
1394                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1395                        for (int userId : mDirtyUsers) {
1396                            mSettings.writePackageRestrictionsLPr(userId);
1397                        }
1398                        mDirtyUsers.clear();
1399                    }
1400                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1401                } break;
1402                case CHECK_PENDING_VERIFICATION: {
1403                    final int verificationId = msg.arg1;
1404                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1405
1406                    if ((state != null) && !state.timeoutExtended()) {
1407                        final InstallArgs args = state.getInstallArgs();
1408                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1409
1410                        Slog.i(TAG, "Verification timed out for " + originUri);
1411                        mPendingVerification.remove(verificationId);
1412
1413                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1414
1415                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1416                            Slog.i(TAG, "Continuing with installation of " + originUri);
1417                            state.setVerifierResponse(Binder.getCallingUid(),
1418                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1419                            broadcastPackageVerified(verificationId, originUri,
1420                                    PackageManager.VERIFICATION_ALLOW,
1421                                    state.getInstallArgs().getUser());
1422                            try {
1423                                ret = args.copyApk(mContainerService, true);
1424                            } catch (RemoteException e) {
1425                                Slog.e(TAG, "Could not contact the ContainerService");
1426                            }
1427                        } else {
1428                            broadcastPackageVerified(verificationId, originUri,
1429                                    PackageManager.VERIFICATION_REJECT,
1430                                    state.getInstallArgs().getUser());
1431                        }
1432
1433                        processPendingInstall(args, ret);
1434                        mHandler.sendEmptyMessage(MCS_UNBIND);
1435                    }
1436                    break;
1437                }
1438                case PACKAGE_VERIFIED: {
1439                    final int verificationId = msg.arg1;
1440
1441                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1442                    if (state == null) {
1443                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1444                        break;
1445                    }
1446
1447                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1448
1449                    state.setVerifierResponse(response.callerUid, response.code);
1450
1451                    if (state.isVerificationComplete()) {
1452                        mPendingVerification.remove(verificationId);
1453
1454                        final InstallArgs args = state.getInstallArgs();
1455                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1456
1457                        int ret;
1458                        if (state.isInstallAllowed()) {
1459                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1460                            broadcastPackageVerified(verificationId, originUri,
1461                                    response.code, state.getInstallArgs().getUser());
1462                            try {
1463                                ret = args.copyApk(mContainerService, true);
1464                            } catch (RemoteException e) {
1465                                Slog.e(TAG, "Could not contact the ContainerService");
1466                            }
1467                        } else {
1468                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1469                        }
1470
1471                        processPendingInstall(args, ret);
1472
1473                        mHandler.sendEmptyMessage(MCS_UNBIND);
1474                    }
1475
1476                    break;
1477                }
1478                case START_INTENT_FILTER_VERIFICATIONS: {
1479                    int userId = msg.arg1;
1480                    int verifierUid = msg.arg2;
1481                    PackageParser.Package pkg = (PackageParser.Package)msg.obj;
1482
1483                    verifyIntentFiltersIfNeeded(userId, verifierUid, pkg);
1484                    break;
1485                }
1486                case INTENT_FILTER_VERIFIED: {
1487                    final int verificationId = msg.arg1;
1488
1489                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1490                            verificationId);
1491                    if (state == null) {
1492                        Slog.w(TAG, "Invalid IntentFilter verification token "
1493                                + verificationId + " received");
1494                        break;
1495                    }
1496
1497                    final int userId = state.getUserId();
1498
1499                    Slog.d(TAG, "Processing IntentFilter verification with token:"
1500                            + verificationId + " and userId:" + userId);
1501
1502                    final IntentFilterVerificationResponse response =
1503                            (IntentFilterVerificationResponse) msg.obj;
1504
1505                    state.setVerifierResponse(response.callerUid, response.code);
1506
1507                    Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1508                            + " and userId:" + userId
1509                            + " is settings verifier response with response code:"
1510                            + response.code);
1511
1512                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1513                        Slog.d(TAG, "Domains failing verification: "
1514                                + response.getFailedDomainsString());
1515                    }
1516
1517                    if (state.isVerificationComplete()) {
1518                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1519                    } else {
1520                        Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1521                                + " was not said to be complete");
1522                    }
1523
1524                    break;
1525                }
1526            }
1527        }
1528    }
1529
1530    private StorageEventListener mStorageListener = new StorageEventListener() {
1531        @Override
1532        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1533            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1534                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1535                    loadPrivatePackages(vol);
1536                } else if (vol.state == VolumeInfo.STATE_UNMOUNTING) {
1537                    unloadPrivatePackages(vol);
1538                }
1539            }
1540
1541            if (vol.isPrimary() && vol.type == VolumeInfo.TYPE_PUBLIC) {
1542                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1543                    updateExternalMediaStatus(true, false);
1544                } else if (vol.state == VolumeInfo.STATE_UNMOUNTING) {
1545                    updateExternalMediaStatus(false, false);
1546                }
1547            }
1548        }
1549    };
1550
1551    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1552        if (userId >= UserHandle.USER_OWNER) {
1553            grantRequestedRuntimePermissionsForUser(pkg, userId);
1554        } else if (userId == UserHandle.USER_ALL) {
1555            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1556                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1557            }
1558        }
1559    }
1560
1561    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1562        SettingBase sb = (SettingBase) pkg.mExtras;
1563        if (sb == null) {
1564            return;
1565        }
1566
1567        PermissionsState permissionsState = sb.getPermissionsState();
1568
1569        for (String permission : pkg.requestedPermissions) {
1570            BasePermission bp = mSettings.mPermissions.get(permission);
1571            if (bp != null && bp.isRuntime()) {
1572                permissionsState.grantRuntimePermission(bp, userId);
1573            }
1574        }
1575    }
1576
1577    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1578        Bundle extras = null;
1579        switch (res.returnCode) {
1580            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1581                extras = new Bundle();
1582                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1583                        res.origPermission);
1584                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1585                        res.origPackage);
1586                break;
1587            }
1588        }
1589        return extras;
1590    }
1591
1592    void scheduleWriteSettingsLocked() {
1593        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1594            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1595        }
1596    }
1597
1598    void scheduleWritePackageRestrictionsLocked(int userId) {
1599        if (!sUserManager.exists(userId)) return;
1600        mDirtyUsers.add(userId);
1601        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1602            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1603        }
1604    }
1605
1606    public static PackageManagerService main(Context context, Installer installer,
1607            boolean factoryTest, boolean onlyCore) {
1608        PackageManagerService m = new PackageManagerService(context, installer,
1609                factoryTest, onlyCore);
1610        ServiceManager.addService("package", m);
1611        return m;
1612    }
1613
1614    static String[] splitString(String str, char sep) {
1615        int count = 1;
1616        int i = 0;
1617        while ((i=str.indexOf(sep, i)) >= 0) {
1618            count++;
1619            i++;
1620        }
1621
1622        String[] res = new String[count];
1623        i=0;
1624        count = 0;
1625        int lastI=0;
1626        while ((i=str.indexOf(sep, i)) >= 0) {
1627            res[count] = str.substring(lastI, i);
1628            count++;
1629            i++;
1630            lastI = i;
1631        }
1632        res[count] = str.substring(lastI, str.length());
1633        return res;
1634    }
1635
1636    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1637        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1638                Context.DISPLAY_SERVICE);
1639        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1640    }
1641
1642    public PackageManagerService(Context context, Installer installer,
1643            boolean factoryTest, boolean onlyCore) {
1644        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1645                SystemClock.uptimeMillis());
1646
1647        if (mSdkVersion <= 0) {
1648            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1649        }
1650
1651        mContext = context;
1652        mFactoryTest = factoryTest;
1653        mOnlyCore = onlyCore;
1654        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1655        mMetrics = new DisplayMetrics();
1656        mSettings = new Settings(mPackages);
1657        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1658                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1659        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1660                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1661        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1662                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1663        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1664                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1665        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1666                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1667        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1668                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1669
1670        // TODO: add a property to control this?
1671        long dexOptLRUThresholdInMinutes;
1672        if (mLazyDexOpt) {
1673            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1674        } else {
1675            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1676        }
1677        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1678
1679        String separateProcesses = SystemProperties.get("debug.separate_processes");
1680        if (separateProcesses != null && separateProcesses.length() > 0) {
1681            if ("*".equals(separateProcesses)) {
1682                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1683                mSeparateProcesses = null;
1684                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1685            } else {
1686                mDefParseFlags = 0;
1687                mSeparateProcesses = separateProcesses.split(",");
1688                Slog.w(TAG, "Running with debug.separate_processes: "
1689                        + separateProcesses);
1690            }
1691        } else {
1692            mDefParseFlags = 0;
1693            mSeparateProcesses = null;
1694        }
1695
1696        mInstaller = installer;
1697        mPackageDexOptimizer = new PackageDexOptimizer(this);
1698
1699        getDefaultDisplayMetrics(context, mMetrics);
1700
1701        SystemConfig systemConfig = SystemConfig.getInstance();
1702        mGlobalGids = systemConfig.getGlobalGids();
1703        mSystemPermissions = systemConfig.getSystemPermissions();
1704        mAvailableFeatures = systemConfig.getAvailableFeatures();
1705
1706        synchronized (mInstallLock) {
1707        // writer
1708        synchronized (mPackages) {
1709            mHandlerThread = new ServiceThread(TAG,
1710                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1711            mHandlerThread.start();
1712            mHandler = new PackageHandler(mHandlerThread.getLooper());
1713            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1714
1715            File dataDir = Environment.getDataDirectory();
1716            mAppDataDir = new File(dataDir, "data");
1717            mAppInstallDir = new File(dataDir, "app");
1718            mAppLib32InstallDir = new File(dataDir, "app-lib");
1719            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1720            mUserAppDataDir = new File(dataDir, "user");
1721            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1722
1723            sUserManager = new UserManagerService(context, this,
1724                    mInstallLock, mPackages);
1725
1726            // Propagate permission configuration in to package manager.
1727            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1728                    = systemConfig.getPermissions();
1729            for (int i=0; i<permConfig.size(); i++) {
1730                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1731                BasePermission bp = mSettings.mPermissions.get(perm.name);
1732                if (bp == null) {
1733                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1734                    mSettings.mPermissions.put(perm.name, bp);
1735                }
1736                if (perm.gids != null) {
1737                    bp.setGids(perm.gids, perm.perUser);
1738                }
1739            }
1740
1741            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1742            for (int i=0; i<libConfig.size(); i++) {
1743                mSharedLibraries.put(libConfig.keyAt(i),
1744                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1745            }
1746
1747            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1748
1749            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1750                    mSdkVersion, mOnlyCore);
1751
1752            String customResolverActivity = Resources.getSystem().getString(
1753                    R.string.config_customResolverActivity);
1754            if (TextUtils.isEmpty(customResolverActivity)) {
1755                customResolverActivity = null;
1756            } else {
1757                mCustomResolverComponentName = ComponentName.unflattenFromString(
1758                        customResolverActivity);
1759            }
1760
1761            long startTime = SystemClock.uptimeMillis();
1762
1763            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1764                    startTime);
1765
1766            // Set flag to monitor and not change apk file paths when
1767            // scanning install directories.
1768            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1769
1770            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1771
1772            /**
1773             * Add everything in the in the boot class path to the
1774             * list of process files because dexopt will have been run
1775             * if necessary during zygote startup.
1776             */
1777            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1778            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1779
1780            if (bootClassPath != null) {
1781                String[] bootClassPathElements = splitString(bootClassPath, ':');
1782                for (String element : bootClassPathElements) {
1783                    alreadyDexOpted.add(element);
1784                }
1785            } else {
1786                Slog.w(TAG, "No BOOTCLASSPATH found!");
1787            }
1788
1789            if (systemServerClassPath != null) {
1790                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1791                for (String element : systemServerClassPathElements) {
1792                    alreadyDexOpted.add(element);
1793                }
1794            } else {
1795                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1796            }
1797
1798            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1799            final String[] dexCodeInstructionSets =
1800                    getDexCodeInstructionSets(
1801                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1802
1803            /**
1804             * Ensure all external libraries have had dexopt run on them.
1805             */
1806            if (mSharedLibraries.size() > 0) {
1807                // NOTE: For now, we're compiling these system "shared libraries"
1808                // (and framework jars) into all available architectures. It's possible
1809                // to compile them only when we come across an app that uses them (there's
1810                // already logic for that in scanPackageLI) but that adds some complexity.
1811                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1812                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1813                        final String lib = libEntry.path;
1814                        if (lib == null) {
1815                            continue;
1816                        }
1817
1818                        try {
1819                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1820                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1821                                alreadyDexOpted.add(lib);
1822                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1823                            }
1824                        } catch (FileNotFoundException e) {
1825                            Slog.w(TAG, "Library not found: " + lib);
1826                        } catch (IOException e) {
1827                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1828                                    + e.getMessage());
1829                        }
1830                    }
1831                }
1832            }
1833
1834            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1835
1836            // Gross hack for now: we know this file doesn't contain any
1837            // code, so don't dexopt it to avoid the resulting log spew.
1838            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1839
1840            // Gross hack for now: we know this file is only part of
1841            // the boot class path for art, so don't dexopt it to
1842            // avoid the resulting log spew.
1843            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1844
1845            /**
1846             * And there are a number of commands implemented in Java, which
1847             * we currently need to do the dexopt on so that they can be
1848             * run from a non-root shell.
1849             */
1850            String[] frameworkFiles = frameworkDir.list();
1851            if (frameworkFiles != null) {
1852                // TODO: We could compile these only for the most preferred ABI. We should
1853                // first double check that the dex files for these commands are not referenced
1854                // by other system apps.
1855                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1856                    for (int i=0; i<frameworkFiles.length; i++) {
1857                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1858                        String path = libPath.getPath();
1859                        // Skip the file if we already did it.
1860                        if (alreadyDexOpted.contains(path)) {
1861                            continue;
1862                        }
1863                        // Skip the file if it is not a type we want to dexopt.
1864                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1865                            continue;
1866                        }
1867                        try {
1868                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1869                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1870                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1871                            }
1872                        } catch (FileNotFoundException e) {
1873                            Slog.w(TAG, "Jar not found: " + path);
1874                        } catch (IOException e) {
1875                            Slog.w(TAG, "Exception reading jar: " + path, e);
1876                        }
1877                    }
1878                }
1879            }
1880
1881            // Collect vendor overlay packages.
1882            // (Do this before scanning any apps.)
1883            // For security and version matching reason, only consider
1884            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1885            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1886            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1887                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1888
1889            // Find base frameworks (resource packages without code).
1890            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1891                    | PackageParser.PARSE_IS_SYSTEM_DIR
1892                    | PackageParser.PARSE_IS_PRIVILEGED,
1893                    scanFlags | SCAN_NO_DEX, 0);
1894
1895            // Collected privileged system packages.
1896            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1897            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1898                    | PackageParser.PARSE_IS_SYSTEM_DIR
1899                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1900
1901            // Collect ordinary system packages.
1902            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1903            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1904                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1905
1906            // Collect all vendor packages.
1907            File vendorAppDir = new File("/vendor/app");
1908            try {
1909                vendorAppDir = vendorAppDir.getCanonicalFile();
1910            } catch (IOException e) {
1911                // failed to look up canonical path, continue with original one
1912            }
1913            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1914                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1915
1916            // Collect all OEM packages.
1917            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1918            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1919                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1920
1921            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1922            mInstaller.moveFiles();
1923
1924            // Prune any system packages that no longer exist.
1925            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1926            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1927            if (!mOnlyCore) {
1928                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1929                while (psit.hasNext()) {
1930                    PackageSetting ps = psit.next();
1931
1932                    /*
1933                     * If this is not a system app, it can't be a
1934                     * disable system app.
1935                     */
1936                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1937                        continue;
1938                    }
1939
1940                    /*
1941                     * If the package is scanned, it's not erased.
1942                     */
1943                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1944                    if (scannedPkg != null) {
1945                        /*
1946                         * If the system app is both scanned and in the
1947                         * disabled packages list, then it must have been
1948                         * added via OTA. Remove it from the currently
1949                         * scanned package so the previously user-installed
1950                         * application can be scanned.
1951                         */
1952                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1953                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1954                                    + ps.name + "; removing system app.  Last known codePath="
1955                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1956                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1957                                    + scannedPkg.mVersionCode);
1958                            removePackageLI(ps, true);
1959                            expectingBetter.put(ps.name, ps.codePath);
1960                        }
1961
1962                        continue;
1963                    }
1964
1965                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1966                        psit.remove();
1967                        logCriticalInfo(Log.WARN, "System package " + ps.name
1968                                + " no longer exists; wiping its data");
1969                        removeDataDirsLI(ps.name);
1970                    } else {
1971                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1972                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1973                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1974                        }
1975                    }
1976                }
1977            }
1978
1979            //look for any incomplete package installations
1980            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1981            //clean up list
1982            for(int i = 0; i < deletePkgsList.size(); i++) {
1983                //clean up here
1984                cleanupInstallFailedPackage(deletePkgsList.get(i));
1985            }
1986            //delete tmp files
1987            deleteTempPackageFiles();
1988
1989            // Remove any shared userIDs that have no associated packages
1990            mSettings.pruneSharedUsersLPw();
1991
1992            if (!mOnlyCore) {
1993                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1994                        SystemClock.uptimeMillis());
1995                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
1996
1997                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1998                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
1999
2000                /**
2001                 * Remove disable package settings for any updated system
2002                 * apps that were removed via an OTA. If they're not a
2003                 * previously-updated app, remove them completely.
2004                 * Otherwise, just revoke their system-level permissions.
2005                 */
2006                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2007                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2008                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2009
2010                    String msg;
2011                    if (deletedPkg == null) {
2012                        msg = "Updated system package " + deletedAppName
2013                                + " no longer exists; wiping its data";
2014                        removeDataDirsLI(deletedAppName);
2015                    } else {
2016                        msg = "Updated system app + " + deletedAppName
2017                                + " no longer present; removing system privileges for "
2018                                + deletedAppName;
2019
2020                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2021
2022                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2023                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2024                    }
2025                    logCriticalInfo(Log.WARN, msg);
2026                }
2027
2028                /**
2029                 * Make sure all system apps that we expected to appear on
2030                 * the userdata partition actually showed up. If they never
2031                 * appeared, crawl back and revive the system version.
2032                 */
2033                for (int i = 0; i < expectingBetter.size(); i++) {
2034                    final String packageName = expectingBetter.keyAt(i);
2035                    if (!mPackages.containsKey(packageName)) {
2036                        final File scanFile = expectingBetter.valueAt(i);
2037
2038                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2039                                + " but never showed up; reverting to system");
2040
2041                        final int reparseFlags;
2042                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2043                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2044                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2045                                    | PackageParser.PARSE_IS_PRIVILEGED;
2046                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2047                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2048                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2049                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2050                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2051                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2052                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2053                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2054                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2055                        } else {
2056                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2057                            continue;
2058                        }
2059
2060                        mSettings.enableSystemPackageLPw(packageName);
2061
2062                        try {
2063                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2064                        } catch (PackageManagerException e) {
2065                            Slog.e(TAG, "Failed to parse original system package: "
2066                                    + e.getMessage());
2067                        }
2068                    }
2069                }
2070            }
2071
2072            // Now that we know all of the shared libraries, update all clients to have
2073            // the correct library paths.
2074            updateAllSharedLibrariesLPw();
2075
2076            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2077                // NOTE: We ignore potential failures here during a system scan (like
2078                // the rest of the commands above) because there's precious little we
2079                // can do about it. A settings error is reported, though.
2080                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2081                        false /* force dexopt */, false /* defer dexopt */);
2082            }
2083
2084            // Now that we know all the packages we are keeping,
2085            // read and update their last usage times.
2086            mPackageUsage.readLP();
2087
2088            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2089                    SystemClock.uptimeMillis());
2090            Slog.i(TAG, "Time to scan packages: "
2091                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2092                    + " seconds");
2093
2094            // If the platform SDK has changed since the last time we booted,
2095            // we need to re-grant app permission to catch any new ones that
2096            // appear.  This is really a hack, and means that apps can in some
2097            // cases get permissions that the user didn't initially explicitly
2098            // allow...  it would be nice to have some better way to handle
2099            // this situation.
2100            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2101                    != mSdkVersion;
2102            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2103                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2104                    + "; regranting permissions for internal storage");
2105            mSettings.mInternalSdkPlatform = mSdkVersion;
2106
2107            // For now runtime permissions are toggled via a system property.
2108            if (!RUNTIME_PERMISSIONS_ENABLED) {
2109                // Remove the runtime permissions state if the feature
2110                // was disabled by flipping the system property.
2111                mSettings.deleteRuntimePermissionsFiles();
2112            }
2113
2114            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2115                    | (regrantPermissions
2116                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2117                            : 0));
2118
2119            // If this is the first boot, and it is a normal boot, then
2120            // we need to initialize the default preferred apps.
2121            if (!mRestoredSettings && !onlyCore) {
2122                mSettings.readDefaultPreferredAppsLPw(this, 0);
2123            }
2124
2125            // If this is first boot after an OTA, and a normal boot, then
2126            // we need to clear code cache directories.
2127            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2128            if (mIsUpgrade && !onlyCore) {
2129                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2130                for (String pkgName : mSettings.mPackages.keySet()) {
2131                    deleteCodeCacheDirsLI(pkgName);
2132                }
2133                mSettings.mFingerprint = Build.FINGERPRINT;
2134            }
2135
2136            // All the changes are done during package scanning.
2137            mSettings.updateInternalDatabaseVersion();
2138
2139            // can downgrade to reader
2140            mSettings.writeLPr();
2141
2142            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2143                    SystemClock.uptimeMillis());
2144
2145            mRequiredVerifierPackage = getRequiredVerifierLPr();
2146
2147            mInstallerService = new PackageInstallerService(context, this);
2148
2149            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2150            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2151                    mIntentFilterVerifierComponent);
2152
2153            primeDomainVerificationsLPw(false);
2154
2155        } // synchronized (mPackages)
2156        } // synchronized (mInstallLock)
2157
2158        // Now after opening every single application zip, make sure they
2159        // are all flushed.  Not really needed, but keeps things nice and
2160        // tidy.
2161        Runtime.getRuntime().gc();
2162    }
2163
2164    @Override
2165    public boolean isFirstBoot() {
2166        return !mRestoredSettings;
2167    }
2168
2169    @Override
2170    public boolean isOnlyCoreApps() {
2171        return mOnlyCore;
2172    }
2173
2174    @Override
2175    public boolean isUpgrade() {
2176        return mIsUpgrade;
2177    }
2178
2179    private String getRequiredVerifierLPr() {
2180        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2181        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2182                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2183
2184        String requiredVerifier = null;
2185
2186        final int N = receivers.size();
2187        for (int i = 0; i < N; i++) {
2188            final ResolveInfo info = receivers.get(i);
2189
2190            if (info.activityInfo == null) {
2191                continue;
2192            }
2193
2194            final String packageName = info.activityInfo.packageName;
2195
2196            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2197                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2198                continue;
2199            }
2200
2201            if (requiredVerifier != null) {
2202                throw new RuntimeException("There can be only one required verifier");
2203            }
2204
2205            requiredVerifier = packageName;
2206        }
2207
2208        return requiredVerifier;
2209    }
2210
2211    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2212        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2213        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2214                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2215
2216        ComponentName verifierComponentName = null;
2217
2218        int priority = -1000;
2219        final int N = receivers.size();
2220        for (int i = 0; i < N; i++) {
2221            final ResolveInfo info = receivers.get(i);
2222
2223            if (info.activityInfo == null) {
2224                continue;
2225            }
2226
2227            final String packageName = info.activityInfo.packageName;
2228
2229            final PackageSetting ps = mSettings.mPackages.get(packageName);
2230            if (ps == null) {
2231                continue;
2232            }
2233
2234            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2235                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2236                continue;
2237            }
2238
2239            // Select the IntentFilterVerifier with the highest priority
2240            if (priority < info.priority) {
2241                priority = info.priority;
2242                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2243                Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName +
2244                        " with priority: " + info.priority);
2245            }
2246        }
2247
2248        return verifierComponentName;
2249    }
2250
2251    private void primeDomainVerificationsLPw(boolean logging) {
2252        Slog.d(TAG, "Start priming domain verification");
2253        boolean updated = false;
2254        ArrayList<String> allHosts = new ArrayList<>();
2255        for (PackageParser.Package pkg : mPackages.values()) {
2256            final String packageName = pkg.packageName;
2257            if (!hasDomainURLs(pkg)) {
2258                if (logging) {
2259                    Slog.d(TAG, "No priming domain verifications for " +
2260                            "package with no domain URLs: " + packageName);
2261                }
2262                continue;
2263            }
2264            for (PackageParser.Activity a : pkg.activities) {
2265                for (ActivityIntentInfo filter : a.intents) {
2266                    if (hasValidDomains(filter, false)) {
2267                        allHosts.addAll(filter.getHostsList());
2268                    }
2269                }
2270            }
2271            if (allHosts.size() > 0) {
2272                allHosts.add("*");
2273            }
2274            IntentFilterVerificationInfo ivi =
2275                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHosts);
2276            if (ivi != null) {
2277                // We will always log this
2278                Slog.d(TAG, "Priming domain verifications for package: " + packageName);
2279                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2280                updated = true;
2281            }
2282            else {
2283                if (logging) {
2284                    Slog.d(TAG, "No priming domain verifications for package: " + packageName);
2285                }
2286            }
2287            allHosts.clear();
2288        }
2289        if (updated) {
2290            scheduleWriteSettingsLocked();
2291        }
2292        Slog.d(TAG, "End priming domain verification");
2293    }
2294
2295    @Override
2296    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2297            throws RemoteException {
2298        try {
2299            return super.onTransact(code, data, reply, flags);
2300        } catch (RuntimeException e) {
2301            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2302                Slog.wtf(TAG, "Package Manager Crash", e);
2303            }
2304            throw e;
2305        }
2306    }
2307
2308    void cleanupInstallFailedPackage(PackageSetting ps) {
2309        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2310
2311        removeDataDirsLI(ps.name);
2312        if (ps.codePath != null) {
2313            if (ps.codePath.isDirectory()) {
2314                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2315            } else {
2316                ps.codePath.delete();
2317            }
2318        }
2319        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2320            if (ps.resourcePath.isDirectory()) {
2321                FileUtils.deleteContents(ps.resourcePath);
2322            }
2323            ps.resourcePath.delete();
2324        }
2325        mSettings.removePackageLPw(ps.name);
2326    }
2327
2328    static int[] appendInts(int[] cur, int[] add) {
2329        if (add == null) return cur;
2330        if (cur == null) return add;
2331        final int N = add.length;
2332        for (int i=0; i<N; i++) {
2333            cur = appendInt(cur, add[i]);
2334        }
2335        return cur;
2336    }
2337
2338    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2339        if (!sUserManager.exists(userId)) return null;
2340        final PackageSetting ps = (PackageSetting) p.mExtras;
2341        if (ps == null) {
2342            return null;
2343        }
2344
2345        final PermissionsState permissionsState = ps.getPermissionsState();
2346
2347        final int[] gids = permissionsState.computeGids(userId);
2348        final Set<String> permissions = permissionsState.getPermissions(userId);
2349        final PackageUserState state = ps.readUserState(userId);
2350
2351        return PackageParser.generatePackageInfo(p, gids, flags,
2352                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2353    }
2354
2355    @Override
2356    public boolean isPackageAvailable(String packageName, int userId) {
2357        if (!sUserManager.exists(userId)) return false;
2358        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2359        synchronized (mPackages) {
2360            PackageParser.Package p = mPackages.get(packageName);
2361            if (p != null) {
2362                final PackageSetting ps = (PackageSetting) p.mExtras;
2363                if (ps != null) {
2364                    final PackageUserState state = ps.readUserState(userId);
2365                    if (state != null) {
2366                        return PackageParser.isAvailable(state);
2367                    }
2368                }
2369            }
2370        }
2371        return false;
2372    }
2373
2374    @Override
2375    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2376        if (!sUserManager.exists(userId)) return null;
2377        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2378        // reader
2379        synchronized (mPackages) {
2380            PackageParser.Package p = mPackages.get(packageName);
2381            if (DEBUG_PACKAGE_INFO)
2382                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2383            if (p != null) {
2384                return generatePackageInfo(p, flags, userId);
2385            }
2386            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2387                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2388            }
2389        }
2390        return null;
2391    }
2392
2393    @Override
2394    public String[] currentToCanonicalPackageNames(String[] names) {
2395        String[] out = new String[names.length];
2396        // reader
2397        synchronized (mPackages) {
2398            for (int i=names.length-1; i>=0; i--) {
2399                PackageSetting ps = mSettings.mPackages.get(names[i]);
2400                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2401            }
2402        }
2403        return out;
2404    }
2405
2406    @Override
2407    public String[] canonicalToCurrentPackageNames(String[] names) {
2408        String[] out = new String[names.length];
2409        // reader
2410        synchronized (mPackages) {
2411            for (int i=names.length-1; i>=0; i--) {
2412                String cur = mSettings.mRenamedPackages.get(names[i]);
2413                out[i] = cur != null ? cur : names[i];
2414            }
2415        }
2416        return out;
2417    }
2418
2419    @Override
2420    public int getPackageUid(String packageName, int userId) {
2421        if (!sUserManager.exists(userId)) return -1;
2422        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2423
2424        // reader
2425        synchronized (mPackages) {
2426            PackageParser.Package p = mPackages.get(packageName);
2427            if(p != null) {
2428                return UserHandle.getUid(userId, p.applicationInfo.uid);
2429            }
2430            PackageSetting ps = mSettings.mPackages.get(packageName);
2431            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2432                return -1;
2433            }
2434            p = ps.pkg;
2435            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2436        }
2437    }
2438
2439    @Override
2440    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2441        if (!sUserManager.exists(userId)) {
2442            return null;
2443        }
2444
2445        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2446                "getPackageGids");
2447
2448        // reader
2449        synchronized (mPackages) {
2450            PackageParser.Package p = mPackages.get(packageName);
2451            if (DEBUG_PACKAGE_INFO) {
2452                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2453            }
2454            if (p != null) {
2455                PackageSetting ps = (PackageSetting) p.mExtras;
2456                return ps.getPermissionsState().computeGids(userId);
2457            }
2458        }
2459
2460        return null;
2461    }
2462
2463    static PermissionInfo generatePermissionInfo(
2464            BasePermission bp, int flags) {
2465        if (bp.perm != null) {
2466            return PackageParser.generatePermissionInfo(bp.perm, flags);
2467        }
2468        PermissionInfo pi = new PermissionInfo();
2469        pi.name = bp.name;
2470        pi.packageName = bp.sourcePackage;
2471        pi.nonLocalizedLabel = bp.name;
2472        pi.protectionLevel = bp.protectionLevel;
2473        return pi;
2474    }
2475
2476    @Override
2477    public PermissionInfo getPermissionInfo(String name, int flags) {
2478        // reader
2479        synchronized (mPackages) {
2480            final BasePermission p = mSettings.mPermissions.get(name);
2481            if (p != null) {
2482                return generatePermissionInfo(p, flags);
2483            }
2484            return null;
2485        }
2486    }
2487
2488    @Override
2489    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2490        // reader
2491        synchronized (mPackages) {
2492            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2493            for (BasePermission p : mSettings.mPermissions.values()) {
2494                if (group == null) {
2495                    if (p.perm == null || p.perm.info.group == null) {
2496                        out.add(generatePermissionInfo(p, flags));
2497                    }
2498                } else {
2499                    if (p.perm != null && group.equals(p.perm.info.group)) {
2500                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2501                    }
2502                }
2503            }
2504
2505            if (out.size() > 0) {
2506                return out;
2507            }
2508            return mPermissionGroups.containsKey(group) ? out : null;
2509        }
2510    }
2511
2512    @Override
2513    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2514        // reader
2515        synchronized (mPackages) {
2516            return PackageParser.generatePermissionGroupInfo(
2517                    mPermissionGroups.get(name), flags);
2518        }
2519    }
2520
2521    @Override
2522    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2523        // reader
2524        synchronized (mPackages) {
2525            final int N = mPermissionGroups.size();
2526            ArrayList<PermissionGroupInfo> out
2527                    = new ArrayList<PermissionGroupInfo>(N);
2528            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2529                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2530            }
2531            return out;
2532        }
2533    }
2534
2535    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2536            int userId) {
2537        if (!sUserManager.exists(userId)) return null;
2538        PackageSetting ps = mSettings.mPackages.get(packageName);
2539        if (ps != null) {
2540            if (ps.pkg == null) {
2541                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2542                        flags, userId);
2543                if (pInfo != null) {
2544                    return pInfo.applicationInfo;
2545                }
2546                return null;
2547            }
2548            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2549                    ps.readUserState(userId), userId);
2550        }
2551        return null;
2552    }
2553
2554    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2555            int userId) {
2556        if (!sUserManager.exists(userId)) return null;
2557        PackageSetting ps = mSettings.mPackages.get(packageName);
2558        if (ps != null) {
2559            PackageParser.Package pkg = ps.pkg;
2560            if (pkg == null) {
2561                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2562                    return null;
2563                }
2564                // Only data remains, so we aren't worried about code paths
2565                pkg = new PackageParser.Package(packageName);
2566                pkg.applicationInfo.packageName = packageName;
2567                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2568                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2569                pkg.applicationInfo.dataDir =
2570                        getDataPathForPackage(packageName, 0).getPath();
2571                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2572                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2573            }
2574            return generatePackageInfo(pkg, flags, userId);
2575        }
2576        return null;
2577    }
2578
2579    @Override
2580    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2581        if (!sUserManager.exists(userId)) return null;
2582        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2583        // writer
2584        synchronized (mPackages) {
2585            PackageParser.Package p = mPackages.get(packageName);
2586            if (DEBUG_PACKAGE_INFO) Log.v(
2587                    TAG, "getApplicationInfo " + packageName
2588                    + ": " + p);
2589            if (p != null) {
2590                PackageSetting ps = mSettings.mPackages.get(packageName);
2591                if (ps == null) return null;
2592                // Note: isEnabledLP() does not apply here - always return info
2593                return PackageParser.generateApplicationInfo(
2594                        p, flags, ps.readUserState(userId), userId);
2595            }
2596            if ("android".equals(packageName)||"system".equals(packageName)) {
2597                return mAndroidApplication;
2598            }
2599            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2600                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2601            }
2602        }
2603        return null;
2604    }
2605
2606
2607    @Override
2608    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2609        mContext.enforceCallingOrSelfPermission(
2610                android.Manifest.permission.CLEAR_APP_CACHE, null);
2611        // Queue up an async operation since clearing cache may take a little while.
2612        mHandler.post(new Runnable() {
2613            public void run() {
2614                mHandler.removeCallbacks(this);
2615                int retCode = -1;
2616                synchronized (mInstallLock) {
2617                    retCode = mInstaller.freeCache(freeStorageSize);
2618                    if (retCode < 0) {
2619                        Slog.w(TAG, "Couldn't clear application caches");
2620                    }
2621                }
2622                if (observer != null) {
2623                    try {
2624                        observer.onRemoveCompleted(null, (retCode >= 0));
2625                    } catch (RemoteException e) {
2626                        Slog.w(TAG, "RemoveException when invoking call back");
2627                    }
2628                }
2629            }
2630        });
2631    }
2632
2633    @Override
2634    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2635        mContext.enforceCallingOrSelfPermission(
2636                android.Manifest.permission.CLEAR_APP_CACHE, null);
2637        // Queue up an async operation since clearing cache may take a little while.
2638        mHandler.post(new Runnable() {
2639            public void run() {
2640                mHandler.removeCallbacks(this);
2641                int retCode = -1;
2642                synchronized (mInstallLock) {
2643                    retCode = mInstaller.freeCache(freeStorageSize);
2644                    if (retCode < 0) {
2645                        Slog.w(TAG, "Couldn't clear application caches");
2646                    }
2647                }
2648                if(pi != null) {
2649                    try {
2650                        // Callback via pending intent
2651                        int code = (retCode >= 0) ? 1 : 0;
2652                        pi.sendIntent(null, code, null,
2653                                null, null);
2654                    } catch (SendIntentException e1) {
2655                        Slog.i(TAG, "Failed to send pending intent");
2656                    }
2657                }
2658            }
2659        });
2660    }
2661
2662    void freeStorage(long freeStorageSize) throws IOException {
2663        synchronized (mInstallLock) {
2664            if (mInstaller.freeCache(freeStorageSize) < 0) {
2665                throw new IOException("Failed to free enough space");
2666            }
2667        }
2668    }
2669
2670    @Override
2671    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2672        if (!sUserManager.exists(userId)) return null;
2673        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2674        synchronized (mPackages) {
2675            PackageParser.Activity a = mActivities.mActivities.get(component);
2676
2677            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2678            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2679                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2680                if (ps == null) return null;
2681                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2682                        userId);
2683            }
2684            if (mResolveComponentName.equals(component)) {
2685                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2686                        new PackageUserState(), userId);
2687            }
2688        }
2689        return null;
2690    }
2691
2692    @Override
2693    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2694            String resolvedType) {
2695        synchronized (mPackages) {
2696            PackageParser.Activity a = mActivities.mActivities.get(component);
2697            if (a == null) {
2698                return false;
2699            }
2700            for (int i=0; i<a.intents.size(); i++) {
2701                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2702                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2703                    return true;
2704                }
2705            }
2706            return false;
2707        }
2708    }
2709
2710    @Override
2711    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2712        if (!sUserManager.exists(userId)) return null;
2713        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2714        synchronized (mPackages) {
2715            PackageParser.Activity a = mReceivers.mActivities.get(component);
2716            if (DEBUG_PACKAGE_INFO) Log.v(
2717                TAG, "getReceiverInfo " + component + ": " + a);
2718            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2719                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2720                if (ps == null) return null;
2721                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2722                        userId);
2723            }
2724        }
2725        return null;
2726    }
2727
2728    @Override
2729    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2730        if (!sUserManager.exists(userId)) return null;
2731        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2732        synchronized (mPackages) {
2733            PackageParser.Service s = mServices.mServices.get(component);
2734            if (DEBUG_PACKAGE_INFO) Log.v(
2735                TAG, "getServiceInfo " + component + ": " + s);
2736            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2737                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2738                if (ps == null) return null;
2739                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2740                        userId);
2741            }
2742        }
2743        return null;
2744    }
2745
2746    @Override
2747    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2748        if (!sUserManager.exists(userId)) return null;
2749        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2750        synchronized (mPackages) {
2751            PackageParser.Provider p = mProviders.mProviders.get(component);
2752            if (DEBUG_PACKAGE_INFO) Log.v(
2753                TAG, "getProviderInfo " + component + ": " + p);
2754            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2755                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2756                if (ps == null) return null;
2757                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2758                        userId);
2759            }
2760        }
2761        return null;
2762    }
2763
2764    @Override
2765    public String[] getSystemSharedLibraryNames() {
2766        Set<String> libSet;
2767        synchronized (mPackages) {
2768            libSet = mSharedLibraries.keySet();
2769            int size = libSet.size();
2770            if (size > 0) {
2771                String[] libs = new String[size];
2772                libSet.toArray(libs);
2773                return libs;
2774            }
2775        }
2776        return null;
2777    }
2778
2779    /**
2780     * @hide
2781     */
2782    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2783        synchronized (mPackages) {
2784            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2785            if (lib != null && lib.apk != null) {
2786                return mPackages.get(lib.apk);
2787            }
2788        }
2789        return null;
2790    }
2791
2792    @Override
2793    public FeatureInfo[] getSystemAvailableFeatures() {
2794        Collection<FeatureInfo> featSet;
2795        synchronized (mPackages) {
2796            featSet = mAvailableFeatures.values();
2797            int size = featSet.size();
2798            if (size > 0) {
2799                FeatureInfo[] features = new FeatureInfo[size+1];
2800                featSet.toArray(features);
2801                FeatureInfo fi = new FeatureInfo();
2802                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2803                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2804                features[size] = fi;
2805                return features;
2806            }
2807        }
2808        return null;
2809    }
2810
2811    @Override
2812    public boolean hasSystemFeature(String name) {
2813        synchronized (mPackages) {
2814            return mAvailableFeatures.containsKey(name);
2815        }
2816    }
2817
2818    private void checkValidCaller(int uid, int userId) {
2819        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2820            return;
2821
2822        throw new SecurityException("Caller uid=" + uid
2823                + " is not privileged to communicate with user=" + userId);
2824    }
2825
2826    @Override
2827    public int checkPermission(String permName, String pkgName, int userId) {
2828        if (!sUserManager.exists(userId)) {
2829            return PackageManager.PERMISSION_DENIED;
2830        }
2831
2832        synchronized (mPackages) {
2833            final PackageParser.Package p = mPackages.get(pkgName);
2834            if (p != null && p.mExtras != null) {
2835                final PackageSetting ps = (PackageSetting) p.mExtras;
2836                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2837                    return PackageManager.PERMISSION_GRANTED;
2838                }
2839            }
2840        }
2841
2842        return PackageManager.PERMISSION_DENIED;
2843    }
2844
2845    @Override
2846    public int checkUidPermission(String permName, int uid) {
2847        final int userId = UserHandle.getUserId(uid);
2848
2849        if (!sUserManager.exists(userId)) {
2850            return PackageManager.PERMISSION_DENIED;
2851        }
2852
2853        synchronized (mPackages) {
2854            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2855            if (obj != null) {
2856                final SettingBase ps = (SettingBase) obj;
2857                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2858                    return PackageManager.PERMISSION_GRANTED;
2859                }
2860            } else {
2861                ArraySet<String> perms = mSystemPermissions.get(uid);
2862                if (perms != null && perms.contains(permName)) {
2863                    return PackageManager.PERMISSION_GRANTED;
2864                }
2865            }
2866        }
2867
2868        return PackageManager.PERMISSION_DENIED;
2869    }
2870
2871    /**
2872     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2873     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2874     * @param checkShell TODO(yamasani):
2875     * @param message the message to log on security exception
2876     */
2877    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2878            boolean checkShell, String message) {
2879        if (userId < 0) {
2880            throw new IllegalArgumentException("Invalid userId " + userId);
2881        }
2882        if (checkShell) {
2883            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2884        }
2885        if (userId == UserHandle.getUserId(callingUid)) return;
2886        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2887            if (requireFullPermission) {
2888                mContext.enforceCallingOrSelfPermission(
2889                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2890            } else {
2891                try {
2892                    mContext.enforceCallingOrSelfPermission(
2893                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2894                } catch (SecurityException se) {
2895                    mContext.enforceCallingOrSelfPermission(
2896                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2897                }
2898            }
2899        }
2900    }
2901
2902    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2903        if (callingUid == Process.SHELL_UID) {
2904            if (userHandle >= 0
2905                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2906                throw new SecurityException("Shell does not have permission to access user "
2907                        + userHandle);
2908            } else if (userHandle < 0) {
2909                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2910                        + Debug.getCallers(3));
2911            }
2912        }
2913    }
2914
2915    private BasePermission findPermissionTreeLP(String permName) {
2916        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2917            if (permName.startsWith(bp.name) &&
2918                    permName.length() > bp.name.length() &&
2919                    permName.charAt(bp.name.length()) == '.') {
2920                return bp;
2921            }
2922        }
2923        return null;
2924    }
2925
2926    private BasePermission checkPermissionTreeLP(String permName) {
2927        if (permName != null) {
2928            BasePermission bp = findPermissionTreeLP(permName);
2929            if (bp != null) {
2930                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2931                    return bp;
2932                }
2933                throw new SecurityException("Calling uid "
2934                        + Binder.getCallingUid()
2935                        + " is not allowed to add to permission tree "
2936                        + bp.name + " owned by uid " + bp.uid);
2937            }
2938        }
2939        throw new SecurityException("No permission tree found for " + permName);
2940    }
2941
2942    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2943        if (s1 == null) {
2944            return s2 == null;
2945        }
2946        if (s2 == null) {
2947            return false;
2948        }
2949        if (s1.getClass() != s2.getClass()) {
2950            return false;
2951        }
2952        return s1.equals(s2);
2953    }
2954
2955    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2956        if (pi1.icon != pi2.icon) return false;
2957        if (pi1.logo != pi2.logo) return false;
2958        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2959        if (!compareStrings(pi1.name, pi2.name)) return false;
2960        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2961        // We'll take care of setting this one.
2962        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2963        // These are not currently stored in settings.
2964        //if (!compareStrings(pi1.group, pi2.group)) return false;
2965        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2966        //if (pi1.labelRes != pi2.labelRes) return false;
2967        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2968        return true;
2969    }
2970
2971    int permissionInfoFootprint(PermissionInfo info) {
2972        int size = info.name.length();
2973        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2974        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2975        return size;
2976    }
2977
2978    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2979        int size = 0;
2980        for (BasePermission perm : mSettings.mPermissions.values()) {
2981            if (perm.uid == tree.uid) {
2982                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2983            }
2984        }
2985        return size;
2986    }
2987
2988    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2989        // We calculate the max size of permissions defined by this uid and throw
2990        // if that plus the size of 'info' would exceed our stated maximum.
2991        if (tree.uid != Process.SYSTEM_UID) {
2992            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2993            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2994                throw new SecurityException("Permission tree size cap exceeded");
2995            }
2996        }
2997    }
2998
2999    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3000        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3001            throw new SecurityException("Label must be specified in permission");
3002        }
3003        BasePermission tree = checkPermissionTreeLP(info.name);
3004        BasePermission bp = mSettings.mPermissions.get(info.name);
3005        boolean added = bp == null;
3006        boolean changed = true;
3007        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3008        if (added) {
3009            enforcePermissionCapLocked(info, tree);
3010            bp = new BasePermission(info.name, tree.sourcePackage,
3011                    BasePermission.TYPE_DYNAMIC);
3012        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3013            throw new SecurityException(
3014                    "Not allowed to modify non-dynamic permission "
3015                    + info.name);
3016        } else {
3017            if (bp.protectionLevel == fixedLevel
3018                    && bp.perm.owner.equals(tree.perm.owner)
3019                    && bp.uid == tree.uid
3020                    && comparePermissionInfos(bp.perm.info, info)) {
3021                changed = false;
3022            }
3023        }
3024        bp.protectionLevel = fixedLevel;
3025        info = new PermissionInfo(info);
3026        info.protectionLevel = fixedLevel;
3027        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3028        bp.perm.info.packageName = tree.perm.info.packageName;
3029        bp.uid = tree.uid;
3030        if (added) {
3031            mSettings.mPermissions.put(info.name, bp);
3032        }
3033        if (changed) {
3034            if (!async) {
3035                mSettings.writeLPr();
3036            } else {
3037                scheduleWriteSettingsLocked();
3038            }
3039        }
3040        return added;
3041    }
3042
3043    @Override
3044    public boolean addPermission(PermissionInfo info) {
3045        synchronized (mPackages) {
3046            return addPermissionLocked(info, false);
3047        }
3048    }
3049
3050    @Override
3051    public boolean addPermissionAsync(PermissionInfo info) {
3052        synchronized (mPackages) {
3053            return addPermissionLocked(info, true);
3054        }
3055    }
3056
3057    @Override
3058    public void removePermission(String name) {
3059        synchronized (mPackages) {
3060            checkPermissionTreeLP(name);
3061            BasePermission bp = mSettings.mPermissions.get(name);
3062            if (bp != null) {
3063                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3064                    throw new SecurityException(
3065                            "Not allowed to modify non-dynamic permission "
3066                            + name);
3067                }
3068                mSettings.mPermissions.remove(name);
3069                mSettings.writeLPr();
3070            }
3071        }
3072    }
3073
3074    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3075            BasePermission bp) {
3076        int index = pkg.requestedPermissions.indexOf(bp.name);
3077        if (index == -1) {
3078            throw new SecurityException("Package " + pkg.packageName
3079                    + " has not requested permission " + bp.name);
3080        }
3081        if (!bp.isRuntime()) {
3082            throw new SecurityException("Permission " + bp.name
3083                    + " is not a changeable permission type");
3084        }
3085    }
3086
3087    @Override
3088    public boolean grantPermission(String packageName, String name, int userId) {
3089        if (!RUNTIME_PERMISSIONS_ENABLED) {
3090            return false;
3091        }
3092
3093        if (!sUserManager.exists(userId)) {
3094            return false;
3095        }
3096
3097        mContext.enforceCallingOrSelfPermission(
3098                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3099                "grantPermission");
3100
3101        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3102                "grantPermission");
3103
3104        boolean gidsChanged = false;
3105        final SettingBase sb;
3106
3107        synchronized (mPackages) {
3108            final PackageParser.Package pkg = mPackages.get(packageName);
3109            if (pkg == null) {
3110                throw new IllegalArgumentException("Unknown package: " + packageName);
3111            }
3112
3113            final BasePermission bp = mSettings.mPermissions.get(name);
3114            if (bp == null) {
3115                throw new IllegalArgumentException("Unknown permission: " + name);
3116            }
3117
3118            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3119
3120            sb = (SettingBase) pkg.mExtras;
3121            if (sb == null) {
3122                throw new IllegalArgumentException("Unknown package: " + packageName);
3123            }
3124
3125            final PermissionsState permissionsState = sb.getPermissionsState();
3126
3127            final int result = permissionsState.grantRuntimePermission(bp, userId);
3128            switch (result) {
3129                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3130                    return false;
3131                }
3132
3133                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3134                    gidsChanged = true;
3135                } break;
3136            }
3137
3138            // Not critical if that is lost - app has to request again.
3139            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3140        }
3141
3142        if (gidsChanged) {
3143            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3144        }
3145
3146        return true;
3147    }
3148
3149    @Override
3150    public boolean revokePermission(String packageName, String name, int userId) {
3151        if (!RUNTIME_PERMISSIONS_ENABLED) {
3152            return false;
3153        }
3154
3155        if (!sUserManager.exists(userId)) {
3156            return false;
3157        }
3158
3159        mContext.enforceCallingOrSelfPermission(
3160                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3161                "revokePermission");
3162
3163        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3164                "revokePermission");
3165
3166        final SettingBase sb;
3167
3168        synchronized (mPackages) {
3169            final PackageParser.Package pkg = mPackages.get(packageName);
3170            if (pkg == null) {
3171                throw new IllegalArgumentException("Unknown package: " + packageName);
3172            }
3173
3174            final BasePermission bp = mSettings.mPermissions.get(name);
3175            if (bp == null) {
3176                throw new IllegalArgumentException("Unknown permission: " + name);
3177            }
3178
3179            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3180
3181            sb = (SettingBase) pkg.mExtras;
3182            if (sb == null) {
3183                throw new IllegalArgumentException("Unknown package: " + packageName);
3184            }
3185
3186            final PermissionsState permissionsState = sb.getPermissionsState();
3187
3188            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3189                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3190                return false;
3191            }
3192
3193            // Critical, after this call all should never have the permission.
3194            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3195        }
3196
3197        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3198
3199        return true;
3200    }
3201
3202    @Override
3203    public boolean isProtectedBroadcast(String actionName) {
3204        synchronized (mPackages) {
3205            return mProtectedBroadcasts.contains(actionName);
3206        }
3207    }
3208
3209    @Override
3210    public int checkSignatures(String pkg1, String pkg2) {
3211        synchronized (mPackages) {
3212            final PackageParser.Package p1 = mPackages.get(pkg1);
3213            final PackageParser.Package p2 = mPackages.get(pkg2);
3214            if (p1 == null || p1.mExtras == null
3215                    || p2 == null || p2.mExtras == null) {
3216                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3217            }
3218            return compareSignatures(p1.mSignatures, p2.mSignatures);
3219        }
3220    }
3221
3222    @Override
3223    public int checkUidSignatures(int uid1, int uid2) {
3224        // Map to base uids.
3225        uid1 = UserHandle.getAppId(uid1);
3226        uid2 = UserHandle.getAppId(uid2);
3227        // reader
3228        synchronized (mPackages) {
3229            Signature[] s1;
3230            Signature[] s2;
3231            Object obj = mSettings.getUserIdLPr(uid1);
3232            if (obj != null) {
3233                if (obj instanceof SharedUserSetting) {
3234                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3235                } else if (obj instanceof PackageSetting) {
3236                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3237                } else {
3238                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3239                }
3240            } else {
3241                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3242            }
3243            obj = mSettings.getUserIdLPr(uid2);
3244            if (obj != null) {
3245                if (obj instanceof SharedUserSetting) {
3246                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3247                } else if (obj instanceof PackageSetting) {
3248                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3249                } else {
3250                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3251                }
3252            } else {
3253                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3254            }
3255            return compareSignatures(s1, s2);
3256        }
3257    }
3258
3259    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3260        final long identity = Binder.clearCallingIdentity();
3261        try {
3262            if (sb instanceof SharedUserSetting) {
3263                SharedUserSetting sus = (SharedUserSetting) sb;
3264                final int packageCount = sus.packages.size();
3265                for (int i = 0; i < packageCount; i++) {
3266                    PackageSetting susPs = sus.packages.valueAt(i);
3267                    if (userId == UserHandle.USER_ALL) {
3268                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3269                    } else {
3270                        final int uid = UserHandle.getUid(userId, susPs.appId);
3271                        killUid(uid, reason);
3272                    }
3273                }
3274            } else if (sb instanceof PackageSetting) {
3275                PackageSetting ps = (PackageSetting) sb;
3276                if (userId == UserHandle.USER_ALL) {
3277                    killApplication(ps.pkg.packageName, ps.appId, reason);
3278                } else {
3279                    final int uid = UserHandle.getUid(userId, ps.appId);
3280                    killUid(uid, reason);
3281                }
3282            }
3283        } finally {
3284            Binder.restoreCallingIdentity(identity);
3285        }
3286    }
3287
3288    private static void killUid(int uid, String reason) {
3289        IActivityManager am = ActivityManagerNative.getDefault();
3290        if (am != null) {
3291            try {
3292                am.killUid(uid, reason);
3293            } catch (RemoteException e) {
3294                /* ignore - same process */
3295            }
3296        }
3297    }
3298
3299    /**
3300     * Compares two sets of signatures. Returns:
3301     * <br />
3302     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3303     * <br />
3304     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3305     * <br />
3306     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3307     * <br />
3308     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3309     * <br />
3310     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3311     */
3312    static int compareSignatures(Signature[] s1, Signature[] s2) {
3313        if (s1 == null) {
3314            return s2 == null
3315                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3316                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3317        }
3318
3319        if (s2 == null) {
3320            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3321        }
3322
3323        if (s1.length != s2.length) {
3324            return PackageManager.SIGNATURE_NO_MATCH;
3325        }
3326
3327        // Since both signature sets are of size 1, we can compare without HashSets.
3328        if (s1.length == 1) {
3329            return s1[0].equals(s2[0]) ?
3330                    PackageManager.SIGNATURE_MATCH :
3331                    PackageManager.SIGNATURE_NO_MATCH;
3332        }
3333
3334        ArraySet<Signature> set1 = new ArraySet<Signature>();
3335        for (Signature sig : s1) {
3336            set1.add(sig);
3337        }
3338        ArraySet<Signature> set2 = new ArraySet<Signature>();
3339        for (Signature sig : s2) {
3340            set2.add(sig);
3341        }
3342        // Make sure s2 contains all signatures in s1.
3343        if (set1.equals(set2)) {
3344            return PackageManager.SIGNATURE_MATCH;
3345        }
3346        return PackageManager.SIGNATURE_NO_MATCH;
3347    }
3348
3349    /**
3350     * If the database version for this type of package (internal storage or
3351     * external storage) is less than the version where package signatures
3352     * were updated, return true.
3353     */
3354    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3355        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3356                DatabaseVersion.SIGNATURE_END_ENTITY))
3357                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3358                        DatabaseVersion.SIGNATURE_END_ENTITY));
3359    }
3360
3361    /**
3362     * Used for backward compatibility to make sure any packages with
3363     * certificate chains get upgraded to the new style. {@code existingSigs}
3364     * will be in the old format (since they were stored on disk from before the
3365     * system upgrade) and {@code scannedSigs} will be in the newer format.
3366     */
3367    private int compareSignaturesCompat(PackageSignatures existingSigs,
3368            PackageParser.Package scannedPkg) {
3369        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3370            return PackageManager.SIGNATURE_NO_MATCH;
3371        }
3372
3373        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3374        for (Signature sig : existingSigs.mSignatures) {
3375            existingSet.add(sig);
3376        }
3377        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3378        for (Signature sig : scannedPkg.mSignatures) {
3379            try {
3380                Signature[] chainSignatures = sig.getChainSignatures();
3381                for (Signature chainSig : chainSignatures) {
3382                    scannedCompatSet.add(chainSig);
3383                }
3384            } catch (CertificateEncodingException e) {
3385                scannedCompatSet.add(sig);
3386            }
3387        }
3388        /*
3389         * Make sure the expanded scanned set contains all signatures in the
3390         * existing one.
3391         */
3392        if (scannedCompatSet.equals(existingSet)) {
3393            // Migrate the old signatures to the new scheme.
3394            existingSigs.assignSignatures(scannedPkg.mSignatures);
3395            // The new KeySets will be re-added later in the scanning process.
3396            synchronized (mPackages) {
3397                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3398            }
3399            return PackageManager.SIGNATURE_MATCH;
3400        }
3401        return PackageManager.SIGNATURE_NO_MATCH;
3402    }
3403
3404    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3405        if (isExternal(scannedPkg)) {
3406            return mSettings.isExternalDatabaseVersionOlderThan(
3407                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3408        } else {
3409            return mSettings.isInternalDatabaseVersionOlderThan(
3410                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3411        }
3412    }
3413
3414    private int compareSignaturesRecover(PackageSignatures existingSigs,
3415            PackageParser.Package scannedPkg) {
3416        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3417            return PackageManager.SIGNATURE_NO_MATCH;
3418        }
3419
3420        String msg = null;
3421        try {
3422            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3423                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3424                        + scannedPkg.packageName);
3425                return PackageManager.SIGNATURE_MATCH;
3426            }
3427        } catch (CertificateException e) {
3428            msg = e.getMessage();
3429        }
3430
3431        logCriticalInfo(Log.INFO,
3432                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3433        return PackageManager.SIGNATURE_NO_MATCH;
3434    }
3435
3436    @Override
3437    public String[] getPackagesForUid(int uid) {
3438        uid = UserHandle.getAppId(uid);
3439        // reader
3440        synchronized (mPackages) {
3441            Object obj = mSettings.getUserIdLPr(uid);
3442            if (obj instanceof SharedUserSetting) {
3443                final SharedUserSetting sus = (SharedUserSetting) obj;
3444                final int N = sus.packages.size();
3445                final String[] res = new String[N];
3446                final Iterator<PackageSetting> it = sus.packages.iterator();
3447                int i = 0;
3448                while (it.hasNext()) {
3449                    res[i++] = it.next().name;
3450                }
3451                return res;
3452            } else if (obj instanceof PackageSetting) {
3453                final PackageSetting ps = (PackageSetting) obj;
3454                return new String[] { ps.name };
3455            }
3456        }
3457        return null;
3458    }
3459
3460    @Override
3461    public String getNameForUid(int uid) {
3462        // reader
3463        synchronized (mPackages) {
3464            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3465            if (obj instanceof SharedUserSetting) {
3466                final SharedUserSetting sus = (SharedUserSetting) obj;
3467                return sus.name + ":" + sus.userId;
3468            } else if (obj instanceof PackageSetting) {
3469                final PackageSetting ps = (PackageSetting) obj;
3470                return ps.name;
3471            }
3472        }
3473        return null;
3474    }
3475
3476    @Override
3477    public int getUidForSharedUser(String sharedUserName) {
3478        if(sharedUserName == null) {
3479            return -1;
3480        }
3481        // reader
3482        synchronized (mPackages) {
3483            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3484            if (suid == null) {
3485                return -1;
3486            }
3487            return suid.userId;
3488        }
3489    }
3490
3491    @Override
3492    public int getFlagsForUid(int uid) {
3493        synchronized (mPackages) {
3494            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3495            if (obj instanceof SharedUserSetting) {
3496                final SharedUserSetting sus = (SharedUserSetting) obj;
3497                return sus.pkgFlags;
3498            } else if (obj instanceof PackageSetting) {
3499                final PackageSetting ps = (PackageSetting) obj;
3500                return ps.pkgFlags;
3501            }
3502        }
3503        return 0;
3504    }
3505
3506    @Override
3507    public int getPrivateFlagsForUid(int uid) {
3508        synchronized (mPackages) {
3509            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3510            if (obj instanceof SharedUserSetting) {
3511                final SharedUserSetting sus = (SharedUserSetting) obj;
3512                return sus.pkgPrivateFlags;
3513            } else if (obj instanceof PackageSetting) {
3514                final PackageSetting ps = (PackageSetting) obj;
3515                return ps.pkgPrivateFlags;
3516            }
3517        }
3518        return 0;
3519    }
3520
3521    @Override
3522    public boolean isUidPrivileged(int uid) {
3523        uid = UserHandle.getAppId(uid);
3524        // reader
3525        synchronized (mPackages) {
3526            Object obj = mSettings.getUserIdLPr(uid);
3527            if (obj instanceof SharedUserSetting) {
3528                final SharedUserSetting sus = (SharedUserSetting) obj;
3529                final Iterator<PackageSetting> it = sus.packages.iterator();
3530                while (it.hasNext()) {
3531                    if (it.next().isPrivileged()) {
3532                        return true;
3533                    }
3534                }
3535            } else if (obj instanceof PackageSetting) {
3536                final PackageSetting ps = (PackageSetting) obj;
3537                return ps.isPrivileged();
3538            }
3539        }
3540        return false;
3541    }
3542
3543    @Override
3544    public String[] getAppOpPermissionPackages(String permissionName) {
3545        synchronized (mPackages) {
3546            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3547            if (pkgs == null) {
3548                return null;
3549            }
3550            return pkgs.toArray(new String[pkgs.size()]);
3551        }
3552    }
3553
3554    @Override
3555    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3556            int flags, int userId) {
3557        if (!sUserManager.exists(userId)) return null;
3558        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3559        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3560        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3561    }
3562
3563    @Override
3564    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3565            IntentFilter filter, int match, ComponentName activity) {
3566        final int userId = UserHandle.getCallingUserId();
3567        if (DEBUG_PREFERRED) {
3568            Log.v(TAG, "setLastChosenActivity intent=" + intent
3569                + " resolvedType=" + resolvedType
3570                + " flags=" + flags
3571                + " filter=" + filter
3572                + " match=" + match
3573                + " activity=" + activity);
3574            filter.dump(new PrintStreamPrinter(System.out), "    ");
3575        }
3576        intent.setComponent(null);
3577        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3578        // Find any earlier preferred or last chosen entries and nuke them
3579        findPreferredActivity(intent, resolvedType,
3580                flags, query, 0, false, true, false, userId);
3581        // Add the new activity as the last chosen for this filter
3582        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3583                "Setting last chosen");
3584    }
3585
3586    @Override
3587    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3588        final int userId = UserHandle.getCallingUserId();
3589        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3590        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3591        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3592                false, false, false, userId);
3593    }
3594
3595    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3596            int flags, List<ResolveInfo> query, int userId) {
3597        if (query != null) {
3598            final int N = query.size();
3599            if (N == 1) {
3600                return query.get(0);
3601            } else if (N > 1) {
3602                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3603                // If there is more than one activity with the same priority,
3604                // then let the user decide between them.
3605                ResolveInfo r0 = query.get(0);
3606                ResolveInfo r1 = query.get(1);
3607                if (DEBUG_INTENT_MATCHING || debug) {
3608                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3609                            + r1.activityInfo.name + "=" + r1.priority);
3610                }
3611                // If the first activity has a higher priority, or a different
3612                // default, then it is always desireable to pick it.
3613                if (r0.priority != r1.priority
3614                        || r0.preferredOrder != r1.preferredOrder
3615                        || r0.isDefault != r1.isDefault) {
3616                    return query.get(0);
3617                }
3618                // If we have saved a preference for a preferred activity for
3619                // this Intent, use that.
3620                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3621                        flags, query, r0.priority, true, false, debug, userId);
3622                if (ri != null) {
3623                    return ri;
3624                }
3625                if (userId != 0) {
3626                    ri = new ResolveInfo(mResolveInfo);
3627                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3628                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3629                            ri.activityInfo.applicationInfo);
3630                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3631                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3632                    return ri;
3633                }
3634                return mResolveInfo;
3635            }
3636        }
3637        return null;
3638    }
3639
3640    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3641            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3642        final int N = query.size();
3643        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3644                .get(userId);
3645        // Get the list of persistent preferred activities that handle the intent
3646        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3647        List<PersistentPreferredActivity> pprefs = ppir != null
3648                ? ppir.queryIntent(intent, resolvedType,
3649                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3650                : null;
3651        if (pprefs != null && pprefs.size() > 0) {
3652            final int M = pprefs.size();
3653            for (int i=0; i<M; i++) {
3654                final PersistentPreferredActivity ppa = pprefs.get(i);
3655                if (DEBUG_PREFERRED || debug) {
3656                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3657                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3658                            + "\n  component=" + ppa.mComponent);
3659                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3660                }
3661                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3662                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3663                if (DEBUG_PREFERRED || debug) {
3664                    Slog.v(TAG, "Found persistent preferred activity:");
3665                    if (ai != null) {
3666                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3667                    } else {
3668                        Slog.v(TAG, "  null");
3669                    }
3670                }
3671                if (ai == null) {
3672                    // This previously registered persistent preferred activity
3673                    // component is no longer known. Ignore it and do NOT remove it.
3674                    continue;
3675                }
3676                for (int j=0; j<N; j++) {
3677                    final ResolveInfo ri = query.get(j);
3678                    if (!ri.activityInfo.applicationInfo.packageName
3679                            .equals(ai.applicationInfo.packageName)) {
3680                        continue;
3681                    }
3682                    if (!ri.activityInfo.name.equals(ai.name)) {
3683                        continue;
3684                    }
3685                    //  Found a persistent preference that can handle the intent.
3686                    if (DEBUG_PREFERRED || debug) {
3687                        Slog.v(TAG, "Returning persistent preferred activity: " +
3688                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3689                    }
3690                    return ri;
3691                }
3692            }
3693        }
3694        return null;
3695    }
3696
3697    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3698            List<ResolveInfo> query, int priority, boolean always,
3699            boolean removeMatches, boolean debug, int userId) {
3700        if (!sUserManager.exists(userId)) return null;
3701        // writer
3702        synchronized (mPackages) {
3703            if (intent.getSelector() != null) {
3704                intent = intent.getSelector();
3705            }
3706            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3707
3708            // Try to find a matching persistent preferred activity.
3709            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3710                    debug, userId);
3711
3712            // If a persistent preferred activity matched, use it.
3713            if (pri != null) {
3714                return pri;
3715            }
3716
3717            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3718            // Get the list of preferred activities that handle the intent
3719            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3720            List<PreferredActivity> prefs = pir != null
3721                    ? pir.queryIntent(intent, resolvedType,
3722                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3723                    : null;
3724            if (prefs != null && prefs.size() > 0) {
3725                boolean changed = false;
3726                try {
3727                    // First figure out how good the original match set is.
3728                    // We will only allow preferred activities that came
3729                    // from the same match quality.
3730                    int match = 0;
3731
3732                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3733
3734                    final int N = query.size();
3735                    for (int j=0; j<N; j++) {
3736                        final ResolveInfo ri = query.get(j);
3737                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3738                                + ": 0x" + Integer.toHexString(match));
3739                        if (ri.match > match) {
3740                            match = ri.match;
3741                        }
3742                    }
3743
3744                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3745                            + Integer.toHexString(match));
3746
3747                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3748                    final int M = prefs.size();
3749                    for (int i=0; i<M; i++) {
3750                        final PreferredActivity pa = prefs.get(i);
3751                        if (DEBUG_PREFERRED || debug) {
3752                            Slog.v(TAG, "Checking PreferredActivity ds="
3753                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3754                                    + "\n  component=" + pa.mPref.mComponent);
3755                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3756                        }
3757                        if (pa.mPref.mMatch != match) {
3758                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3759                                    + Integer.toHexString(pa.mPref.mMatch));
3760                            continue;
3761                        }
3762                        // If it's not an "always" type preferred activity and that's what we're
3763                        // looking for, skip it.
3764                        if (always && !pa.mPref.mAlways) {
3765                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3766                            continue;
3767                        }
3768                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3769                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3770                        if (DEBUG_PREFERRED || debug) {
3771                            Slog.v(TAG, "Found preferred activity:");
3772                            if (ai != null) {
3773                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3774                            } else {
3775                                Slog.v(TAG, "  null");
3776                            }
3777                        }
3778                        if (ai == null) {
3779                            // This previously registered preferred activity
3780                            // component is no longer known.  Most likely an update
3781                            // to the app was installed and in the new version this
3782                            // component no longer exists.  Clean it up by removing
3783                            // it from the preferred activities list, and skip it.
3784                            Slog.w(TAG, "Removing dangling preferred activity: "
3785                                    + pa.mPref.mComponent);
3786                            pir.removeFilter(pa);
3787                            changed = true;
3788                            continue;
3789                        }
3790                        for (int j=0; j<N; j++) {
3791                            final ResolveInfo ri = query.get(j);
3792                            if (!ri.activityInfo.applicationInfo.packageName
3793                                    .equals(ai.applicationInfo.packageName)) {
3794                                continue;
3795                            }
3796                            if (!ri.activityInfo.name.equals(ai.name)) {
3797                                continue;
3798                            }
3799
3800                            if (removeMatches) {
3801                                pir.removeFilter(pa);
3802                                changed = true;
3803                                if (DEBUG_PREFERRED) {
3804                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3805                                }
3806                                break;
3807                            }
3808
3809                            // Okay we found a previously set preferred or last chosen app.
3810                            // If the result set is different from when this
3811                            // was created, we need to clear it and re-ask the
3812                            // user their preference, if we're looking for an "always" type entry.
3813                            if (always && !pa.mPref.sameSet(query)) {
3814                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3815                                        + intent + " type " + resolvedType);
3816                                if (DEBUG_PREFERRED) {
3817                                    Slog.v(TAG, "Removing preferred activity since set changed "
3818                                            + pa.mPref.mComponent);
3819                                }
3820                                pir.removeFilter(pa);
3821                                // Re-add the filter as a "last chosen" entry (!always)
3822                                PreferredActivity lastChosen = new PreferredActivity(
3823                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3824                                pir.addFilter(lastChosen);
3825                                changed = true;
3826                                return null;
3827                            }
3828
3829                            // Yay! Either the set matched or we're looking for the last chosen
3830                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3831                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3832                            return ri;
3833                        }
3834                    }
3835                } finally {
3836                    if (changed) {
3837                        if (DEBUG_PREFERRED) {
3838                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3839                        }
3840                        scheduleWritePackageRestrictionsLocked(userId);
3841                    }
3842                }
3843            }
3844        }
3845        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3846        return null;
3847    }
3848
3849    /*
3850     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3851     */
3852    @Override
3853    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3854            int targetUserId) {
3855        mContext.enforceCallingOrSelfPermission(
3856                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3857        List<CrossProfileIntentFilter> matches =
3858                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3859        if (matches != null) {
3860            int size = matches.size();
3861            for (int i = 0; i < size; i++) {
3862                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3863            }
3864        }
3865        return false;
3866    }
3867
3868    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3869            String resolvedType, int userId) {
3870        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3871        if (resolver != null) {
3872            return resolver.queryIntent(intent, resolvedType, false, userId);
3873        }
3874        return null;
3875    }
3876
3877    @Override
3878    public List<ResolveInfo> queryIntentActivities(Intent intent,
3879            String resolvedType, int flags, int userId) {
3880        if (!sUserManager.exists(userId)) return Collections.emptyList();
3881        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3882        ComponentName comp = intent.getComponent();
3883        if (comp == null) {
3884            if (intent.getSelector() != null) {
3885                intent = intent.getSelector();
3886                comp = intent.getComponent();
3887            }
3888        }
3889
3890        if (comp != null) {
3891            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3892            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3893            if (ai != null) {
3894                final ResolveInfo ri = new ResolveInfo();
3895                ri.activityInfo = ai;
3896                list.add(ri);
3897            }
3898            return list;
3899        }
3900
3901        // reader
3902        synchronized (mPackages) {
3903            final String pkgName = intent.getPackage();
3904            if (pkgName == null) {
3905                List<CrossProfileIntentFilter> matchingFilters =
3906                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3907                // Check for results that need to skip the current profile.
3908                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3909                        resolvedType, flags, userId);
3910                if (resolveInfo != null) {
3911                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3912                    result.add(resolveInfo);
3913                    return filterIfNotPrimaryUser(result, userId);
3914                }
3915                // Check for cross profile results.
3916                resolveInfo = queryCrossProfileIntents(
3917                        matchingFilters, intent, resolvedType, flags, userId);
3918
3919                // Check for results in the current profile.
3920                List<ResolveInfo> result = mActivities.queryIntent(
3921                        intent, resolvedType, flags, userId);
3922                if (resolveInfo != null) {
3923                    result.add(resolveInfo);
3924                    Collections.sort(result, mResolvePrioritySorter);
3925                }
3926                result = filterIfNotPrimaryUser(result, userId);
3927                if (result.size() > 1 && hasWebURI(intent)) {
3928                    return filterCandidatesWithDomainPreferedActivitiesLPr(result);
3929                }
3930                return result;
3931            }
3932            final PackageParser.Package pkg = mPackages.get(pkgName);
3933            if (pkg != null) {
3934                return filterIfNotPrimaryUser(
3935                        mActivities.queryIntentForPackage(
3936                                intent, resolvedType, flags, pkg.activities, userId),
3937                        userId);
3938            }
3939            return new ArrayList<ResolveInfo>();
3940        }
3941    }
3942
3943    /**
3944     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
3945     *
3946     * @return filtered list
3947     */
3948    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
3949        if (userId == UserHandle.USER_OWNER) {
3950            return resolveInfos;
3951        }
3952        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
3953            ResolveInfo info = resolveInfos.get(i);
3954            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
3955                resolveInfos.remove(i);
3956            }
3957        }
3958        return resolveInfos;
3959    }
3960
3961    private static boolean hasWebURI(Intent intent) {
3962        if (intent.getData() == null) {
3963            return false;
3964        }
3965        final String scheme = intent.getScheme();
3966        if (TextUtils.isEmpty(scheme)) {
3967            return false;
3968        }
3969        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
3970    }
3971
3972    private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr(
3973            List<ResolveInfo> candidates) {
3974        if (DEBUG_PREFERRED) {
3975            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
3976                    candidates.size());
3977        }
3978
3979        final int userId = UserHandle.getCallingUserId();
3980        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
3981        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
3982        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
3983        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
3984
3985        synchronized (mPackages) {
3986            final int count = candidates.size();
3987            // First, try to use the domain prefered App
3988            for (int n=0; n<count; n++) {
3989                ResolveInfo info = candidates.get(n);
3990                String packageName = info.activityInfo.packageName;
3991                PackageSetting ps = mSettings.mPackages.get(packageName);
3992                if (ps != null) {
3993                    // Try to get the status from User settings first
3994                    int status = getDomainVerificationStatusLPr(ps, userId);
3995                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
3996                        result.add(info);
3997                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
3998                        neverList.add(info);
3999                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4000                        undefinedList.add(info);
4001                    }
4002                    // Add to the special match all list (Browser use case)
4003                    if (info.handleAllWebDataURI) {
4004                        matchAllList.add(info);
4005                    }
4006                }
4007            }
4008            // If there is nothing selected, add all candidates and remove the ones that the User
4009            // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and
4010            // also remove any Browser Apps ones.
4011            // If there is still none after this pass, add all undefined one and Browser Apps and
4012            // let the User decide with the Disambiguation dialog if there are several ones.
4013            if (result.size() == 0) {
4014                result.addAll(candidates);
4015            }
4016            result.removeAll(neverList);
4017            result.removeAll(matchAllList);
4018            if (result.size() == 0) {
4019                result.addAll(undefinedList);
4020                result.addAll(matchAllList);
4021            }
4022        }
4023        if (DEBUG_PREFERRED) {
4024            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4025                    result.size());
4026        }
4027        return result;
4028    }
4029
4030    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4031        int status = ps.getDomainVerificationStatusForUser(userId);
4032        // if none available, get the master status
4033        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4034            if (ps.getIntentFilterVerificationInfo() != null) {
4035                status = ps.getIntentFilterVerificationInfo().getStatus();
4036            }
4037        }
4038        return status;
4039    }
4040
4041    private ResolveInfo querySkipCurrentProfileIntents(
4042            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4043            int flags, int sourceUserId) {
4044        if (matchingFilters != null) {
4045            int size = matchingFilters.size();
4046            for (int i = 0; i < size; i ++) {
4047                CrossProfileIntentFilter filter = matchingFilters.get(i);
4048                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4049                    // Checking if there are activities in the target user that can handle the
4050                    // intent.
4051                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4052                            flags, sourceUserId);
4053                    if (resolveInfo != null) {
4054                        return resolveInfo;
4055                    }
4056                }
4057            }
4058        }
4059        return null;
4060    }
4061
4062    // Return matching ResolveInfo if any for skip current profile intent filters.
4063    private ResolveInfo queryCrossProfileIntents(
4064            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4065            int flags, int sourceUserId) {
4066        if (matchingFilters != null) {
4067            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4068            // match the same intent. For performance reasons, it is better not to
4069            // run queryIntent twice for the same userId
4070            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4071            int size = matchingFilters.size();
4072            for (int i = 0; i < size; i++) {
4073                CrossProfileIntentFilter filter = matchingFilters.get(i);
4074                int targetUserId = filter.getTargetUserId();
4075                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4076                        && !alreadyTriedUserIds.get(targetUserId)) {
4077                    // Checking if there are activities in the target user that can handle the
4078                    // intent.
4079                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4080                            flags, sourceUserId);
4081                    if (resolveInfo != null) return resolveInfo;
4082                    alreadyTriedUserIds.put(targetUserId, true);
4083                }
4084            }
4085        }
4086        return null;
4087    }
4088
4089    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4090            String resolvedType, int flags, int sourceUserId) {
4091        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4092                resolvedType, flags, filter.getTargetUserId());
4093        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4094            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4095        }
4096        return null;
4097    }
4098
4099    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4100            int sourceUserId, int targetUserId) {
4101        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4102        String className;
4103        if (targetUserId == UserHandle.USER_OWNER) {
4104            className = FORWARD_INTENT_TO_USER_OWNER;
4105        } else {
4106            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4107        }
4108        ComponentName forwardingActivityComponentName = new ComponentName(
4109                mAndroidApplication.packageName, className);
4110        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4111                sourceUserId);
4112        if (targetUserId == UserHandle.USER_OWNER) {
4113            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4114            forwardingResolveInfo.noResourceId = true;
4115        }
4116        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4117        forwardingResolveInfo.priority = 0;
4118        forwardingResolveInfo.preferredOrder = 0;
4119        forwardingResolveInfo.match = 0;
4120        forwardingResolveInfo.isDefault = true;
4121        forwardingResolveInfo.filter = filter;
4122        forwardingResolveInfo.targetUserId = targetUserId;
4123        return forwardingResolveInfo;
4124    }
4125
4126    @Override
4127    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4128            Intent[] specifics, String[] specificTypes, Intent intent,
4129            String resolvedType, int flags, int userId) {
4130        if (!sUserManager.exists(userId)) return Collections.emptyList();
4131        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4132                false, "query intent activity options");
4133        final String resultsAction = intent.getAction();
4134
4135        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4136                | PackageManager.GET_RESOLVED_FILTER, userId);
4137
4138        if (DEBUG_INTENT_MATCHING) {
4139            Log.v(TAG, "Query " + intent + ": " + results);
4140        }
4141
4142        int specificsPos = 0;
4143        int N;
4144
4145        // todo: note that the algorithm used here is O(N^2).  This
4146        // isn't a problem in our current environment, but if we start running
4147        // into situations where we have more than 5 or 10 matches then this
4148        // should probably be changed to something smarter...
4149
4150        // First we go through and resolve each of the specific items
4151        // that were supplied, taking care of removing any corresponding
4152        // duplicate items in the generic resolve list.
4153        if (specifics != null) {
4154            for (int i=0; i<specifics.length; i++) {
4155                final Intent sintent = specifics[i];
4156                if (sintent == null) {
4157                    continue;
4158                }
4159
4160                if (DEBUG_INTENT_MATCHING) {
4161                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4162                }
4163
4164                String action = sintent.getAction();
4165                if (resultsAction != null && resultsAction.equals(action)) {
4166                    // If this action was explicitly requested, then don't
4167                    // remove things that have it.
4168                    action = null;
4169                }
4170
4171                ResolveInfo ri = null;
4172                ActivityInfo ai = null;
4173
4174                ComponentName comp = sintent.getComponent();
4175                if (comp == null) {
4176                    ri = resolveIntent(
4177                        sintent,
4178                        specificTypes != null ? specificTypes[i] : null,
4179                            flags, userId);
4180                    if (ri == null) {
4181                        continue;
4182                    }
4183                    if (ri == mResolveInfo) {
4184                        // ACK!  Must do something better with this.
4185                    }
4186                    ai = ri.activityInfo;
4187                    comp = new ComponentName(ai.applicationInfo.packageName,
4188                            ai.name);
4189                } else {
4190                    ai = getActivityInfo(comp, flags, userId);
4191                    if (ai == null) {
4192                        continue;
4193                    }
4194                }
4195
4196                // Look for any generic query activities that are duplicates
4197                // of this specific one, and remove them from the results.
4198                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4199                N = results.size();
4200                int j;
4201                for (j=specificsPos; j<N; j++) {
4202                    ResolveInfo sri = results.get(j);
4203                    if ((sri.activityInfo.name.equals(comp.getClassName())
4204                            && sri.activityInfo.applicationInfo.packageName.equals(
4205                                    comp.getPackageName()))
4206                        || (action != null && sri.filter.matchAction(action))) {
4207                        results.remove(j);
4208                        if (DEBUG_INTENT_MATCHING) Log.v(
4209                            TAG, "Removing duplicate item from " + j
4210                            + " due to specific " + specificsPos);
4211                        if (ri == null) {
4212                            ri = sri;
4213                        }
4214                        j--;
4215                        N--;
4216                    }
4217                }
4218
4219                // Add this specific item to its proper place.
4220                if (ri == null) {
4221                    ri = new ResolveInfo();
4222                    ri.activityInfo = ai;
4223                }
4224                results.add(specificsPos, ri);
4225                ri.specificIndex = i;
4226                specificsPos++;
4227            }
4228        }
4229
4230        // Now we go through the remaining generic results and remove any
4231        // duplicate actions that are found here.
4232        N = results.size();
4233        for (int i=specificsPos; i<N-1; i++) {
4234            final ResolveInfo rii = results.get(i);
4235            if (rii.filter == null) {
4236                continue;
4237            }
4238
4239            // Iterate over all of the actions of this result's intent
4240            // filter...  typically this should be just one.
4241            final Iterator<String> it = rii.filter.actionsIterator();
4242            if (it == null) {
4243                continue;
4244            }
4245            while (it.hasNext()) {
4246                final String action = it.next();
4247                if (resultsAction != null && resultsAction.equals(action)) {
4248                    // If this action was explicitly requested, then don't
4249                    // remove things that have it.
4250                    continue;
4251                }
4252                for (int j=i+1; j<N; j++) {
4253                    final ResolveInfo rij = results.get(j);
4254                    if (rij.filter != null && rij.filter.hasAction(action)) {
4255                        results.remove(j);
4256                        if (DEBUG_INTENT_MATCHING) Log.v(
4257                            TAG, "Removing duplicate item from " + j
4258                            + " due to action " + action + " at " + i);
4259                        j--;
4260                        N--;
4261                    }
4262                }
4263            }
4264
4265            // If the caller didn't request filter information, drop it now
4266            // so we don't have to marshall/unmarshall it.
4267            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4268                rii.filter = null;
4269            }
4270        }
4271
4272        // Filter out the caller activity if so requested.
4273        if (caller != null) {
4274            N = results.size();
4275            for (int i=0; i<N; i++) {
4276                ActivityInfo ainfo = results.get(i).activityInfo;
4277                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4278                        && caller.getClassName().equals(ainfo.name)) {
4279                    results.remove(i);
4280                    break;
4281                }
4282            }
4283        }
4284
4285        // If the caller didn't request filter information,
4286        // drop them now so we don't have to
4287        // marshall/unmarshall it.
4288        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4289            N = results.size();
4290            for (int i=0; i<N; i++) {
4291                results.get(i).filter = null;
4292            }
4293        }
4294
4295        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4296        return results;
4297    }
4298
4299    @Override
4300    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4301            int userId) {
4302        if (!sUserManager.exists(userId)) return Collections.emptyList();
4303        ComponentName comp = intent.getComponent();
4304        if (comp == null) {
4305            if (intent.getSelector() != null) {
4306                intent = intent.getSelector();
4307                comp = intent.getComponent();
4308            }
4309        }
4310        if (comp != null) {
4311            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4312            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4313            if (ai != null) {
4314                ResolveInfo ri = new ResolveInfo();
4315                ri.activityInfo = ai;
4316                list.add(ri);
4317            }
4318            return list;
4319        }
4320
4321        // reader
4322        synchronized (mPackages) {
4323            String pkgName = intent.getPackage();
4324            if (pkgName == null) {
4325                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4326            }
4327            final PackageParser.Package pkg = mPackages.get(pkgName);
4328            if (pkg != null) {
4329                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4330                        userId);
4331            }
4332            return null;
4333        }
4334    }
4335
4336    @Override
4337    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4338        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4339        if (!sUserManager.exists(userId)) return null;
4340        if (query != null) {
4341            if (query.size() >= 1) {
4342                // If there is more than one service with the same priority,
4343                // just arbitrarily pick the first one.
4344                return query.get(0);
4345            }
4346        }
4347        return null;
4348    }
4349
4350    @Override
4351    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4352            int userId) {
4353        if (!sUserManager.exists(userId)) return Collections.emptyList();
4354        ComponentName comp = intent.getComponent();
4355        if (comp == null) {
4356            if (intent.getSelector() != null) {
4357                intent = intent.getSelector();
4358                comp = intent.getComponent();
4359            }
4360        }
4361        if (comp != null) {
4362            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4363            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4364            if (si != null) {
4365                final ResolveInfo ri = new ResolveInfo();
4366                ri.serviceInfo = si;
4367                list.add(ri);
4368            }
4369            return list;
4370        }
4371
4372        // reader
4373        synchronized (mPackages) {
4374            String pkgName = intent.getPackage();
4375            if (pkgName == null) {
4376                return mServices.queryIntent(intent, resolvedType, flags, userId);
4377            }
4378            final PackageParser.Package pkg = mPackages.get(pkgName);
4379            if (pkg != null) {
4380                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4381                        userId);
4382            }
4383            return null;
4384        }
4385    }
4386
4387    @Override
4388    public List<ResolveInfo> queryIntentContentProviders(
4389            Intent intent, String resolvedType, int flags, int userId) {
4390        if (!sUserManager.exists(userId)) return Collections.emptyList();
4391        ComponentName comp = intent.getComponent();
4392        if (comp == null) {
4393            if (intent.getSelector() != null) {
4394                intent = intent.getSelector();
4395                comp = intent.getComponent();
4396            }
4397        }
4398        if (comp != null) {
4399            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4400            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4401            if (pi != null) {
4402                final ResolveInfo ri = new ResolveInfo();
4403                ri.providerInfo = pi;
4404                list.add(ri);
4405            }
4406            return list;
4407        }
4408
4409        // reader
4410        synchronized (mPackages) {
4411            String pkgName = intent.getPackage();
4412            if (pkgName == null) {
4413                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4414            }
4415            final PackageParser.Package pkg = mPackages.get(pkgName);
4416            if (pkg != null) {
4417                return mProviders.queryIntentForPackage(
4418                        intent, resolvedType, flags, pkg.providers, userId);
4419            }
4420            return null;
4421        }
4422    }
4423
4424    @Override
4425    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4426        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4427
4428        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4429
4430        // writer
4431        synchronized (mPackages) {
4432            ArrayList<PackageInfo> list;
4433            if (listUninstalled) {
4434                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4435                for (PackageSetting ps : mSettings.mPackages.values()) {
4436                    PackageInfo pi;
4437                    if (ps.pkg != null) {
4438                        pi = generatePackageInfo(ps.pkg, flags, userId);
4439                    } else {
4440                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4441                    }
4442                    if (pi != null) {
4443                        list.add(pi);
4444                    }
4445                }
4446            } else {
4447                list = new ArrayList<PackageInfo>(mPackages.size());
4448                for (PackageParser.Package p : mPackages.values()) {
4449                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4450                    if (pi != null) {
4451                        list.add(pi);
4452                    }
4453                }
4454            }
4455
4456            return new ParceledListSlice<PackageInfo>(list);
4457        }
4458    }
4459
4460    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4461            String[] permissions, boolean[] tmp, int flags, int userId) {
4462        int numMatch = 0;
4463        final PermissionsState permissionsState = ps.getPermissionsState();
4464        for (int i=0; i<permissions.length; i++) {
4465            final String permission = permissions[i];
4466            if (permissionsState.hasPermission(permission, userId)) {
4467                tmp[i] = true;
4468                numMatch++;
4469            } else {
4470                tmp[i] = false;
4471            }
4472        }
4473        if (numMatch == 0) {
4474            return;
4475        }
4476        PackageInfo pi;
4477        if (ps.pkg != null) {
4478            pi = generatePackageInfo(ps.pkg, flags, userId);
4479        } else {
4480            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4481        }
4482        // The above might return null in cases of uninstalled apps or install-state
4483        // skew across users/profiles.
4484        if (pi != null) {
4485            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4486                if (numMatch == permissions.length) {
4487                    pi.requestedPermissions = permissions;
4488                } else {
4489                    pi.requestedPermissions = new String[numMatch];
4490                    numMatch = 0;
4491                    for (int i=0; i<permissions.length; i++) {
4492                        if (tmp[i]) {
4493                            pi.requestedPermissions[numMatch] = permissions[i];
4494                            numMatch++;
4495                        }
4496                    }
4497                }
4498            }
4499            list.add(pi);
4500        }
4501    }
4502
4503    @Override
4504    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4505            String[] permissions, int flags, int userId) {
4506        if (!sUserManager.exists(userId)) return null;
4507        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4508
4509        // writer
4510        synchronized (mPackages) {
4511            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4512            boolean[] tmpBools = new boolean[permissions.length];
4513            if (listUninstalled) {
4514                for (PackageSetting ps : mSettings.mPackages.values()) {
4515                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4516                }
4517            } else {
4518                for (PackageParser.Package pkg : mPackages.values()) {
4519                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4520                    if (ps != null) {
4521                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4522                                userId);
4523                    }
4524                }
4525            }
4526
4527            return new ParceledListSlice<PackageInfo>(list);
4528        }
4529    }
4530
4531    @Override
4532    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4533        if (!sUserManager.exists(userId)) return null;
4534        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4535
4536        // writer
4537        synchronized (mPackages) {
4538            ArrayList<ApplicationInfo> list;
4539            if (listUninstalled) {
4540                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4541                for (PackageSetting ps : mSettings.mPackages.values()) {
4542                    ApplicationInfo ai;
4543                    if (ps.pkg != null) {
4544                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4545                                ps.readUserState(userId), userId);
4546                    } else {
4547                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4548                    }
4549                    if (ai != null) {
4550                        list.add(ai);
4551                    }
4552                }
4553            } else {
4554                list = new ArrayList<ApplicationInfo>(mPackages.size());
4555                for (PackageParser.Package p : mPackages.values()) {
4556                    if (p.mExtras != null) {
4557                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4558                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4559                        if (ai != null) {
4560                            list.add(ai);
4561                        }
4562                    }
4563                }
4564            }
4565
4566            return new ParceledListSlice<ApplicationInfo>(list);
4567        }
4568    }
4569
4570    public List<ApplicationInfo> getPersistentApplications(int flags) {
4571        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4572
4573        // reader
4574        synchronized (mPackages) {
4575            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4576            final int userId = UserHandle.getCallingUserId();
4577            while (i.hasNext()) {
4578                final PackageParser.Package p = i.next();
4579                if (p.applicationInfo != null
4580                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4581                        && (!mSafeMode || isSystemApp(p))) {
4582                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4583                    if (ps != null) {
4584                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4585                                ps.readUserState(userId), userId);
4586                        if (ai != null) {
4587                            finalList.add(ai);
4588                        }
4589                    }
4590                }
4591            }
4592        }
4593
4594        return finalList;
4595    }
4596
4597    @Override
4598    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4599        if (!sUserManager.exists(userId)) return null;
4600        // reader
4601        synchronized (mPackages) {
4602            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4603            PackageSetting ps = provider != null
4604                    ? mSettings.mPackages.get(provider.owner.packageName)
4605                    : null;
4606            return ps != null
4607                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4608                    && (!mSafeMode || (provider.info.applicationInfo.flags
4609                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4610                    ? PackageParser.generateProviderInfo(provider, flags,
4611                            ps.readUserState(userId), userId)
4612                    : null;
4613        }
4614    }
4615
4616    /**
4617     * @deprecated
4618     */
4619    @Deprecated
4620    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4621        // reader
4622        synchronized (mPackages) {
4623            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4624                    .entrySet().iterator();
4625            final int userId = UserHandle.getCallingUserId();
4626            while (i.hasNext()) {
4627                Map.Entry<String, PackageParser.Provider> entry = i.next();
4628                PackageParser.Provider p = entry.getValue();
4629                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4630
4631                if (ps != null && p.syncable
4632                        && (!mSafeMode || (p.info.applicationInfo.flags
4633                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4634                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4635                            ps.readUserState(userId), userId);
4636                    if (info != null) {
4637                        outNames.add(entry.getKey());
4638                        outInfo.add(info);
4639                    }
4640                }
4641            }
4642        }
4643    }
4644
4645    @Override
4646    public List<ProviderInfo> queryContentProviders(String processName,
4647            int uid, int flags) {
4648        ArrayList<ProviderInfo> finalList = null;
4649        // reader
4650        synchronized (mPackages) {
4651            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4652            final int userId = processName != null ?
4653                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4654            while (i.hasNext()) {
4655                final PackageParser.Provider p = i.next();
4656                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4657                if (ps != null && p.info.authority != null
4658                        && (processName == null
4659                                || (p.info.processName.equals(processName)
4660                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4661                        && mSettings.isEnabledLPr(p.info, flags, userId)
4662                        && (!mSafeMode
4663                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4664                    if (finalList == null) {
4665                        finalList = new ArrayList<ProviderInfo>(3);
4666                    }
4667                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4668                            ps.readUserState(userId), userId);
4669                    if (info != null) {
4670                        finalList.add(info);
4671                    }
4672                }
4673            }
4674        }
4675
4676        if (finalList != null) {
4677            Collections.sort(finalList, mProviderInitOrderSorter);
4678        }
4679
4680        return finalList;
4681    }
4682
4683    @Override
4684    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4685            int flags) {
4686        // reader
4687        synchronized (mPackages) {
4688            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4689            return PackageParser.generateInstrumentationInfo(i, flags);
4690        }
4691    }
4692
4693    @Override
4694    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4695            int flags) {
4696        ArrayList<InstrumentationInfo> finalList =
4697            new ArrayList<InstrumentationInfo>();
4698
4699        // reader
4700        synchronized (mPackages) {
4701            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4702            while (i.hasNext()) {
4703                final PackageParser.Instrumentation p = i.next();
4704                if (targetPackage == null
4705                        || targetPackage.equals(p.info.targetPackage)) {
4706                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4707                            flags);
4708                    if (ii != null) {
4709                        finalList.add(ii);
4710                    }
4711                }
4712            }
4713        }
4714
4715        return finalList;
4716    }
4717
4718    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4719        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4720        if (overlays == null) {
4721            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4722            return;
4723        }
4724        for (PackageParser.Package opkg : overlays.values()) {
4725            // Not much to do if idmap fails: we already logged the error
4726            // and we certainly don't want to abort installation of pkg simply
4727            // because an overlay didn't fit properly. For these reasons,
4728            // ignore the return value of createIdmapForPackagePairLI.
4729            createIdmapForPackagePairLI(pkg, opkg);
4730        }
4731    }
4732
4733    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4734            PackageParser.Package opkg) {
4735        if (!opkg.mTrustedOverlay) {
4736            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4737                    opkg.baseCodePath + ": overlay not trusted");
4738            return false;
4739        }
4740        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4741        if (overlaySet == null) {
4742            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4743                    opkg.baseCodePath + " but target package has no known overlays");
4744            return false;
4745        }
4746        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4747        // TODO: generate idmap for split APKs
4748        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4749            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4750                    + opkg.baseCodePath);
4751            return false;
4752        }
4753        PackageParser.Package[] overlayArray =
4754            overlaySet.values().toArray(new PackageParser.Package[0]);
4755        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4756            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4757                return p1.mOverlayPriority - p2.mOverlayPriority;
4758            }
4759        };
4760        Arrays.sort(overlayArray, cmp);
4761
4762        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4763        int i = 0;
4764        for (PackageParser.Package p : overlayArray) {
4765            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4766        }
4767        return true;
4768    }
4769
4770    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4771        final File[] files = dir.listFiles();
4772        if (ArrayUtils.isEmpty(files)) {
4773            Log.d(TAG, "No files in app dir " + dir);
4774            return;
4775        }
4776
4777        if (DEBUG_PACKAGE_SCANNING) {
4778            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4779                    + " flags=0x" + Integer.toHexString(parseFlags));
4780        }
4781
4782        for (File file : files) {
4783            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4784                    && !PackageInstallerService.isStageName(file.getName());
4785            if (!isPackage) {
4786                // Ignore entries which are not packages
4787                continue;
4788            }
4789            try {
4790                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4791                        scanFlags, currentTime, null);
4792            } catch (PackageManagerException e) {
4793                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4794
4795                // Delete invalid userdata apps
4796                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4797                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4798                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4799                    if (file.isDirectory()) {
4800                        mInstaller.rmPackageDir(file.getAbsolutePath());
4801                    } else {
4802                        file.delete();
4803                    }
4804                }
4805            }
4806        }
4807    }
4808
4809    private static File getSettingsProblemFile() {
4810        File dataDir = Environment.getDataDirectory();
4811        File systemDir = new File(dataDir, "system");
4812        File fname = new File(systemDir, "uiderrors.txt");
4813        return fname;
4814    }
4815
4816    static void reportSettingsProblem(int priority, String msg) {
4817        logCriticalInfo(priority, msg);
4818    }
4819
4820    static void logCriticalInfo(int priority, String msg) {
4821        Slog.println(priority, TAG, msg);
4822        EventLogTags.writePmCriticalInfo(msg);
4823        try {
4824            File fname = getSettingsProblemFile();
4825            FileOutputStream out = new FileOutputStream(fname, true);
4826            PrintWriter pw = new FastPrintWriter(out);
4827            SimpleDateFormat formatter = new SimpleDateFormat();
4828            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4829            pw.println(dateString + ": " + msg);
4830            pw.close();
4831            FileUtils.setPermissions(
4832                    fname.toString(),
4833                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4834                    -1, -1);
4835        } catch (java.io.IOException e) {
4836        }
4837    }
4838
4839    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4840            PackageParser.Package pkg, File srcFile, int parseFlags)
4841            throws PackageManagerException {
4842        if (ps != null
4843                && ps.codePath.equals(srcFile)
4844                && ps.timeStamp == srcFile.lastModified()
4845                && !isCompatSignatureUpdateNeeded(pkg)
4846                && !isRecoverSignatureUpdateNeeded(pkg)) {
4847            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4848            if (ps.signatures.mSignatures != null
4849                    && ps.signatures.mSignatures.length != 0
4850                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4851                // Optimization: reuse the existing cached certificates
4852                // if the package appears to be unchanged.
4853                pkg.mSignatures = ps.signatures.mSignatures;
4854                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4855                synchronized (mPackages) {
4856                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4857                }
4858                return;
4859            }
4860
4861            Slog.w(TAG, "PackageSetting for " + ps.name
4862                    + " is missing signatures.  Collecting certs again to recover them.");
4863        } else {
4864            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4865        }
4866
4867        try {
4868            pp.collectCertificates(pkg, parseFlags);
4869            pp.collectManifestDigest(pkg);
4870        } catch (PackageParserException e) {
4871            throw PackageManagerException.from(e);
4872        }
4873    }
4874
4875    /*
4876     *  Scan a package and return the newly parsed package.
4877     *  Returns null in case of errors and the error code is stored in mLastScanError
4878     */
4879    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4880            long currentTime, UserHandle user) throws PackageManagerException {
4881        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4882        parseFlags |= mDefParseFlags;
4883        PackageParser pp = new PackageParser();
4884        pp.setSeparateProcesses(mSeparateProcesses);
4885        pp.setOnlyCoreApps(mOnlyCore);
4886        pp.setDisplayMetrics(mMetrics);
4887
4888        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4889            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4890        }
4891
4892        final PackageParser.Package pkg;
4893        try {
4894            pkg = pp.parsePackage(scanFile, parseFlags);
4895        } catch (PackageParserException e) {
4896            throw PackageManagerException.from(e);
4897        }
4898
4899        PackageSetting ps = null;
4900        PackageSetting updatedPkg;
4901        // reader
4902        synchronized (mPackages) {
4903            // Look to see if we already know about this package.
4904            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4905            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4906                // This package has been renamed to its original name.  Let's
4907                // use that.
4908                ps = mSettings.peekPackageLPr(oldName);
4909            }
4910            // If there was no original package, see one for the real package name.
4911            if (ps == null) {
4912                ps = mSettings.peekPackageLPr(pkg.packageName);
4913            }
4914            // Check to see if this package could be hiding/updating a system
4915            // package.  Must look for it either under the original or real
4916            // package name depending on our state.
4917            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4918            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4919        }
4920        boolean updatedPkgBetter = false;
4921        // First check if this is a system package that may involve an update
4922        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4923            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
4924            // it needs to drop FLAG_PRIVILEGED.
4925            if (locationIsPrivileged(scanFile)) {
4926                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4927            } else {
4928                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4929            }
4930
4931            if (ps != null && !ps.codePath.equals(scanFile)) {
4932                // The path has changed from what was last scanned...  check the
4933                // version of the new path against what we have stored to determine
4934                // what to do.
4935                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4936                if (pkg.mVersionCode <= ps.versionCode) {
4937                    // The system package has been updated and the code path does not match
4938                    // Ignore entry. Skip it.
4939                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
4940                            + " ignored: updated version " + ps.versionCode
4941                            + " better than this " + pkg.mVersionCode);
4942                    if (!updatedPkg.codePath.equals(scanFile)) {
4943                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4944                                + ps.name + " changing from " + updatedPkg.codePathString
4945                                + " to " + scanFile);
4946                        updatedPkg.codePath = scanFile;
4947                        updatedPkg.codePathString = scanFile.toString();
4948                        updatedPkg.resourcePath = scanFile;
4949                        updatedPkg.resourcePathString = scanFile.toString();
4950                    }
4951                    updatedPkg.pkg = pkg;
4952                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4953                } else {
4954                    // The current app on the system partition is better than
4955                    // what we have updated to on the data partition; switch
4956                    // back to the system partition version.
4957                    // At this point, its safely assumed that package installation for
4958                    // apps in system partition will go through. If not there won't be a working
4959                    // version of the app
4960                    // writer
4961                    synchronized (mPackages) {
4962                        // Just remove the loaded entries from package lists.
4963                        mPackages.remove(ps.name);
4964                    }
4965
4966                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4967                            + " reverting from " + ps.codePathString
4968                            + ": new version " + pkg.mVersionCode
4969                            + " better than installed " + ps.versionCode);
4970
4971                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4972                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4973                            getAppDexInstructionSets(ps));
4974                    synchronized (mInstallLock) {
4975                        args.cleanUpResourcesLI();
4976                    }
4977                    synchronized (mPackages) {
4978                        mSettings.enableSystemPackageLPw(ps.name);
4979                    }
4980                    updatedPkgBetter = true;
4981                }
4982            }
4983        }
4984
4985        if (updatedPkg != null) {
4986            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4987            // initially
4988            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4989
4990            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4991            // flag set initially
4992            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
4993                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4994            }
4995        }
4996
4997        // Verify certificates against what was last scanned
4998        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4999
5000        /*
5001         * A new system app appeared, but we already had a non-system one of the
5002         * same name installed earlier.
5003         */
5004        boolean shouldHideSystemApp = false;
5005        if (updatedPkg == null && ps != null
5006                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5007            /*
5008             * Check to make sure the signatures match first. If they don't,
5009             * wipe the installed application and its data.
5010             */
5011            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5012                    != PackageManager.SIGNATURE_MATCH) {
5013                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5014                        + " signatures don't match existing userdata copy; removing");
5015                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5016                ps = null;
5017            } else {
5018                /*
5019                 * If the newly-added system app is an older version than the
5020                 * already installed version, hide it. It will be scanned later
5021                 * and re-added like an update.
5022                 */
5023                if (pkg.mVersionCode <= ps.versionCode) {
5024                    shouldHideSystemApp = true;
5025                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5026                            + " but new version " + pkg.mVersionCode + " better than installed "
5027                            + ps.versionCode + "; hiding system");
5028                } else {
5029                    /*
5030                     * The newly found system app is a newer version that the
5031                     * one previously installed. Simply remove the
5032                     * already-installed application and replace it with our own
5033                     * while keeping the application data.
5034                     */
5035                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5036                            + " reverting from " + ps.codePathString + ": new version "
5037                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5038                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5039                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
5040                            getAppDexInstructionSets(ps));
5041                    synchronized (mInstallLock) {
5042                        args.cleanUpResourcesLI();
5043                    }
5044                }
5045            }
5046        }
5047
5048        // The apk is forward locked (not public) if its code and resources
5049        // are kept in different files. (except for app in either system or
5050        // vendor path).
5051        // TODO grab this value from PackageSettings
5052        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5053            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5054                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5055            }
5056        }
5057
5058        // TODO: extend to support forward-locked splits
5059        String resourcePath = null;
5060        String baseResourcePath = null;
5061        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5062            if (ps != null && ps.resourcePathString != null) {
5063                resourcePath = ps.resourcePathString;
5064                baseResourcePath = ps.resourcePathString;
5065            } else {
5066                // Should not happen at all. Just log an error.
5067                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5068            }
5069        } else {
5070            resourcePath = pkg.codePath;
5071            baseResourcePath = pkg.baseCodePath;
5072        }
5073
5074        // Set application objects path explicitly.
5075        pkg.applicationInfo.setCodePath(pkg.codePath);
5076        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5077        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5078        pkg.applicationInfo.setResourcePath(resourcePath);
5079        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5080        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5081
5082        // Note that we invoke the following method only if we are about to unpack an application
5083        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5084                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5085
5086        /*
5087         * If the system app should be overridden by a previously installed
5088         * data, hide the system app now and let the /data/app scan pick it up
5089         * again.
5090         */
5091        if (shouldHideSystemApp) {
5092            synchronized (mPackages) {
5093                /*
5094                 * We have to grant systems permissions before we hide, because
5095                 * grantPermissions will assume the package update is trying to
5096                 * expand its permissions.
5097                 */
5098                grantPermissionsLPw(pkg, true, pkg.packageName);
5099                mSettings.disableSystemPackageLPw(pkg.packageName);
5100            }
5101        }
5102
5103        return scannedPkg;
5104    }
5105
5106    private static String fixProcessName(String defProcessName,
5107            String processName, int uid) {
5108        if (processName == null) {
5109            return defProcessName;
5110        }
5111        return processName;
5112    }
5113
5114    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5115            throws PackageManagerException {
5116        if (pkgSetting.signatures.mSignatures != null) {
5117            // Already existing package. Make sure signatures match
5118            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5119                    == PackageManager.SIGNATURE_MATCH;
5120            if (!match) {
5121                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5122                        == PackageManager.SIGNATURE_MATCH;
5123            }
5124            if (!match) {
5125                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5126                        == PackageManager.SIGNATURE_MATCH;
5127            }
5128            if (!match) {
5129                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5130                        + pkg.packageName + " signatures do not match the "
5131                        + "previously installed version; ignoring!");
5132            }
5133        }
5134
5135        // Check for shared user signatures
5136        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5137            // Already existing package. Make sure signatures match
5138            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5139                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5140            if (!match) {
5141                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5142                        == PackageManager.SIGNATURE_MATCH;
5143            }
5144            if (!match) {
5145                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5146                        == PackageManager.SIGNATURE_MATCH;
5147            }
5148            if (!match) {
5149                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5150                        "Package " + pkg.packageName
5151                        + " has no signatures that match those in shared user "
5152                        + pkgSetting.sharedUser.name + "; ignoring!");
5153            }
5154        }
5155    }
5156
5157    /**
5158     * Enforces that only the system UID or root's UID can call a method exposed
5159     * via Binder.
5160     *
5161     * @param message used as message if SecurityException is thrown
5162     * @throws SecurityException if the caller is not system or root
5163     */
5164    private static final void enforceSystemOrRoot(String message) {
5165        final int uid = Binder.getCallingUid();
5166        if (uid != Process.SYSTEM_UID && uid != 0) {
5167            throw new SecurityException(message);
5168        }
5169    }
5170
5171    @Override
5172    public void performBootDexOpt() {
5173        enforceSystemOrRoot("Only the system can request dexopt be performed");
5174
5175        // Before everything else, see whether we need to fstrim.
5176        try {
5177            IMountService ms = PackageHelper.getMountService();
5178            if (ms != null) {
5179                final boolean isUpgrade = isUpgrade();
5180                boolean doTrim = isUpgrade;
5181                if (doTrim) {
5182                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5183                } else {
5184                    final long interval = android.provider.Settings.Global.getLong(
5185                            mContext.getContentResolver(),
5186                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5187                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5188                    if (interval > 0) {
5189                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5190                        if (timeSinceLast > interval) {
5191                            doTrim = true;
5192                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5193                                    + "; running immediately");
5194                        }
5195                    }
5196                }
5197                if (doTrim) {
5198                    if (!isFirstBoot()) {
5199                        try {
5200                            ActivityManagerNative.getDefault().showBootMessage(
5201                                    mContext.getResources().getString(
5202                                            R.string.android_upgrading_fstrim), true);
5203                        } catch (RemoteException e) {
5204                        }
5205                    }
5206                    ms.runMaintenance();
5207                }
5208            } else {
5209                Slog.e(TAG, "Mount service unavailable!");
5210            }
5211        } catch (RemoteException e) {
5212            // Can't happen; MountService is local
5213        }
5214
5215        final ArraySet<PackageParser.Package> pkgs;
5216        synchronized (mPackages) {
5217            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5218        }
5219
5220        if (pkgs != null) {
5221            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5222            // in case the device runs out of space.
5223            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5224            // Give priority to core apps.
5225            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5226                PackageParser.Package pkg = it.next();
5227                if (pkg.coreApp) {
5228                    if (DEBUG_DEXOPT) {
5229                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5230                    }
5231                    sortedPkgs.add(pkg);
5232                    it.remove();
5233                }
5234            }
5235            // Give priority to system apps that listen for pre boot complete.
5236            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5237            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5238            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5239                PackageParser.Package pkg = it.next();
5240                if (pkgNames.contains(pkg.packageName)) {
5241                    if (DEBUG_DEXOPT) {
5242                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5243                    }
5244                    sortedPkgs.add(pkg);
5245                    it.remove();
5246                }
5247            }
5248            // Give priority to system apps.
5249            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5250                PackageParser.Package pkg = it.next();
5251                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5252                    if (DEBUG_DEXOPT) {
5253                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5254                    }
5255                    sortedPkgs.add(pkg);
5256                    it.remove();
5257                }
5258            }
5259            // Give priority to updated system apps.
5260            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5261                PackageParser.Package pkg = it.next();
5262                if (pkg.isUpdatedSystemApp()) {
5263                    if (DEBUG_DEXOPT) {
5264                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5265                    }
5266                    sortedPkgs.add(pkg);
5267                    it.remove();
5268                }
5269            }
5270            // Give priority to apps that listen for boot complete.
5271            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5272            pkgNames = getPackageNamesForIntent(intent);
5273            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5274                PackageParser.Package pkg = it.next();
5275                if (pkgNames.contains(pkg.packageName)) {
5276                    if (DEBUG_DEXOPT) {
5277                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5278                    }
5279                    sortedPkgs.add(pkg);
5280                    it.remove();
5281                }
5282            }
5283            // Filter out packages that aren't recently used.
5284            filterRecentlyUsedApps(pkgs);
5285            // Add all remaining apps.
5286            for (PackageParser.Package pkg : pkgs) {
5287                if (DEBUG_DEXOPT) {
5288                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5289                }
5290                sortedPkgs.add(pkg);
5291            }
5292
5293            // If we want to be lazy, filter everything that wasn't recently used.
5294            if (mLazyDexOpt) {
5295                filterRecentlyUsedApps(sortedPkgs);
5296            }
5297
5298            int i = 0;
5299            int total = sortedPkgs.size();
5300            File dataDir = Environment.getDataDirectory();
5301            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5302            if (lowThreshold == 0) {
5303                throw new IllegalStateException("Invalid low memory threshold");
5304            }
5305            for (PackageParser.Package pkg : sortedPkgs) {
5306                long usableSpace = dataDir.getUsableSpace();
5307                if (usableSpace < lowThreshold) {
5308                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5309                    break;
5310                }
5311                performBootDexOpt(pkg, ++i, total);
5312            }
5313        }
5314    }
5315
5316    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5317        // Filter out packages that aren't recently used.
5318        //
5319        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5320        // should do a full dexopt.
5321        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5322            int total = pkgs.size();
5323            int skipped = 0;
5324            long now = System.currentTimeMillis();
5325            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5326                PackageParser.Package pkg = i.next();
5327                long then = pkg.mLastPackageUsageTimeInMills;
5328                if (then + mDexOptLRUThresholdInMills < now) {
5329                    if (DEBUG_DEXOPT) {
5330                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5331                              ((then == 0) ? "never" : new Date(then)));
5332                    }
5333                    i.remove();
5334                    skipped++;
5335                }
5336            }
5337            if (DEBUG_DEXOPT) {
5338                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5339            }
5340        }
5341    }
5342
5343    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5344        List<ResolveInfo> ris = null;
5345        try {
5346            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5347                    intent, null, 0, UserHandle.USER_OWNER);
5348        } catch (RemoteException e) {
5349        }
5350        ArraySet<String> pkgNames = new ArraySet<String>();
5351        if (ris != null) {
5352            for (ResolveInfo ri : ris) {
5353                pkgNames.add(ri.activityInfo.packageName);
5354            }
5355        }
5356        return pkgNames;
5357    }
5358
5359    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5360        if (DEBUG_DEXOPT) {
5361            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5362        }
5363        if (!isFirstBoot()) {
5364            try {
5365                ActivityManagerNative.getDefault().showBootMessage(
5366                        mContext.getResources().getString(R.string.android_upgrading_apk,
5367                                curr, total), true);
5368            } catch (RemoteException e) {
5369            }
5370        }
5371        PackageParser.Package p = pkg;
5372        synchronized (mInstallLock) {
5373            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5374                    false /* force dex */, false /* defer */, true /* include dependencies */);
5375        }
5376    }
5377
5378    @Override
5379    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5380        return performDexOpt(packageName, instructionSet, false);
5381    }
5382
5383    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5384        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5385        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5386        if (!dexopt && !updateUsage) {
5387            // We aren't going to dexopt or update usage, so bail early.
5388            return false;
5389        }
5390        PackageParser.Package p;
5391        final String targetInstructionSet;
5392        synchronized (mPackages) {
5393            p = mPackages.get(packageName);
5394            if (p == null) {
5395                return false;
5396            }
5397            if (updateUsage) {
5398                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5399            }
5400            mPackageUsage.write(false);
5401            if (!dexopt) {
5402                // We aren't going to dexopt, so bail early.
5403                return false;
5404            }
5405
5406            targetInstructionSet = instructionSet != null ? instructionSet :
5407                    getPrimaryInstructionSet(p.applicationInfo);
5408            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5409                return false;
5410            }
5411        }
5412
5413        synchronized (mInstallLock) {
5414            final String[] instructionSets = new String[] { targetInstructionSet };
5415            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5416                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5417            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5418        }
5419    }
5420
5421    public ArraySet<String> getPackagesThatNeedDexOpt() {
5422        ArraySet<String> pkgs = null;
5423        synchronized (mPackages) {
5424            for (PackageParser.Package p : mPackages.values()) {
5425                if (DEBUG_DEXOPT) {
5426                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5427                }
5428                if (!p.mDexOptPerformed.isEmpty()) {
5429                    continue;
5430                }
5431                if (pkgs == null) {
5432                    pkgs = new ArraySet<String>();
5433                }
5434                pkgs.add(p.packageName);
5435            }
5436        }
5437        return pkgs;
5438    }
5439
5440    public void shutdown() {
5441        mPackageUsage.write(true);
5442    }
5443
5444    @Override
5445    public void forceDexOpt(String packageName) {
5446        enforceSystemOrRoot("forceDexOpt");
5447
5448        PackageParser.Package pkg;
5449        synchronized (mPackages) {
5450            pkg = mPackages.get(packageName);
5451            if (pkg == null) {
5452                throw new IllegalArgumentException("Missing package: " + packageName);
5453            }
5454        }
5455
5456        synchronized (mInstallLock) {
5457            final String[] instructionSets = new String[] {
5458                    getPrimaryInstructionSet(pkg.applicationInfo) };
5459            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5460                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5461            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5462                throw new IllegalStateException("Failed to dexopt: " + res);
5463            }
5464        }
5465    }
5466
5467    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5468        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5469            Slog.w(TAG, "Unable to update from " + oldPkg.name
5470                    + " to " + newPkg.packageName
5471                    + ": old package not in system partition");
5472            return false;
5473        } else if (mPackages.get(oldPkg.name) != null) {
5474            Slog.w(TAG, "Unable to update from " + oldPkg.name
5475                    + " to " + newPkg.packageName
5476                    + ": old package still exists");
5477            return false;
5478        }
5479        return true;
5480    }
5481
5482    private File getDataPathForPackage(String packageName, int userId) {
5483        /*
5484         * Until we fully support multiple users, return the directory we
5485         * previously would have. The PackageManagerTests will need to be
5486         * revised when this is changed back..
5487         */
5488        if (userId == 0) {
5489            return new File(mAppDataDir, packageName);
5490        } else {
5491            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
5492                + File.separator + packageName);
5493        }
5494    }
5495
5496    private int createDataDirsLI(String packageName, int uid, String seinfo) {
5497        int[] users = sUserManager.getUserIds();
5498        int res = mInstaller.install(packageName, uid, uid, seinfo);
5499        if (res < 0) {
5500            return res;
5501        }
5502        for (int user : users) {
5503            if (user != 0) {
5504                res = mInstaller.createUserData(packageName,
5505                        UserHandle.getUid(user, uid), user, seinfo);
5506                if (res < 0) {
5507                    return res;
5508                }
5509            }
5510        }
5511        return res;
5512    }
5513
5514    private int removeDataDirsLI(String packageName) {
5515        int[] users = sUserManager.getUserIds();
5516        int res = 0;
5517        for (int user : users) {
5518            int resInner = mInstaller.remove(packageName, user);
5519            if (resInner < 0) {
5520                res = resInner;
5521            }
5522        }
5523
5524        return res;
5525    }
5526
5527    private int deleteCodeCacheDirsLI(String packageName) {
5528        int[] users = sUserManager.getUserIds();
5529        int res = 0;
5530        for (int user : users) {
5531            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
5532            if (resInner < 0) {
5533                res = resInner;
5534            }
5535        }
5536        return res;
5537    }
5538
5539    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5540            PackageParser.Package changingLib) {
5541        if (file.path != null) {
5542            usesLibraryFiles.add(file.path);
5543            return;
5544        }
5545        PackageParser.Package p = mPackages.get(file.apk);
5546        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5547            // If we are doing this while in the middle of updating a library apk,
5548            // then we need to make sure to use that new apk for determining the
5549            // dependencies here.  (We haven't yet finished committing the new apk
5550            // to the package manager state.)
5551            if (p == null || p.packageName.equals(changingLib.packageName)) {
5552                p = changingLib;
5553            }
5554        }
5555        if (p != null) {
5556            usesLibraryFiles.addAll(p.getAllCodePaths());
5557        }
5558    }
5559
5560    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5561            PackageParser.Package changingLib) throws PackageManagerException {
5562        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5563            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5564            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5565            for (int i=0; i<N; i++) {
5566                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5567                if (file == null) {
5568                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5569                            "Package " + pkg.packageName + " requires unavailable shared library "
5570                            + pkg.usesLibraries.get(i) + "; failing!");
5571                }
5572                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5573            }
5574            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5575            for (int i=0; i<N; i++) {
5576                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5577                if (file == null) {
5578                    Slog.w(TAG, "Package " + pkg.packageName
5579                            + " desires unavailable shared library "
5580                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5581                } else {
5582                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5583                }
5584            }
5585            N = usesLibraryFiles.size();
5586            if (N > 0) {
5587                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5588            } else {
5589                pkg.usesLibraryFiles = null;
5590            }
5591        }
5592    }
5593
5594    private static boolean hasString(List<String> list, List<String> which) {
5595        if (list == null) {
5596            return false;
5597        }
5598        for (int i=list.size()-1; i>=0; i--) {
5599            for (int j=which.size()-1; j>=0; j--) {
5600                if (which.get(j).equals(list.get(i))) {
5601                    return true;
5602                }
5603            }
5604        }
5605        return false;
5606    }
5607
5608    private void updateAllSharedLibrariesLPw() {
5609        for (PackageParser.Package pkg : mPackages.values()) {
5610            try {
5611                updateSharedLibrariesLPw(pkg, null);
5612            } catch (PackageManagerException e) {
5613                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5614            }
5615        }
5616    }
5617
5618    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5619            PackageParser.Package changingPkg) {
5620        ArrayList<PackageParser.Package> res = null;
5621        for (PackageParser.Package pkg : mPackages.values()) {
5622            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5623                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5624                if (res == null) {
5625                    res = new ArrayList<PackageParser.Package>();
5626                }
5627                res.add(pkg);
5628                try {
5629                    updateSharedLibrariesLPw(pkg, changingPkg);
5630                } catch (PackageManagerException e) {
5631                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5632                }
5633            }
5634        }
5635        return res;
5636    }
5637
5638    /**
5639     * Derive the value of the {@code cpuAbiOverride} based on the provided
5640     * value and an optional stored value from the package settings.
5641     */
5642    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5643        String cpuAbiOverride = null;
5644
5645        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5646            cpuAbiOverride = null;
5647        } else if (abiOverride != null) {
5648            cpuAbiOverride = abiOverride;
5649        } else if (settings != null) {
5650            cpuAbiOverride = settings.cpuAbiOverrideString;
5651        }
5652
5653        return cpuAbiOverride;
5654    }
5655
5656    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5657            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5658        boolean success = false;
5659        try {
5660            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5661                    currentTime, user);
5662            success = true;
5663            return res;
5664        } finally {
5665            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5666                removeDataDirsLI(pkg.packageName);
5667            }
5668        }
5669    }
5670
5671    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5672            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5673        final File scanFile = new File(pkg.codePath);
5674        if (pkg.applicationInfo.getCodePath() == null ||
5675                pkg.applicationInfo.getResourcePath() == null) {
5676            // Bail out. The resource and code paths haven't been set.
5677            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5678                    "Code and resource paths haven't been set correctly");
5679        }
5680
5681        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5682            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5683        } else {
5684            // Only allow system apps to be flagged as core apps.
5685            pkg.coreApp = false;
5686        }
5687
5688        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5689            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5690        }
5691
5692        if (mCustomResolverComponentName != null &&
5693                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5694            setUpCustomResolverActivity(pkg);
5695        }
5696
5697        if (pkg.packageName.equals("android")) {
5698            synchronized (mPackages) {
5699                if (mAndroidApplication != null) {
5700                    Slog.w(TAG, "*************************************************");
5701                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5702                    Slog.w(TAG, " file=" + scanFile);
5703                    Slog.w(TAG, "*************************************************");
5704                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5705                            "Core android package being redefined.  Skipping.");
5706                }
5707
5708                // Set up information for our fall-back user intent resolution activity.
5709                mPlatformPackage = pkg;
5710                pkg.mVersionCode = mSdkVersion;
5711                mAndroidApplication = pkg.applicationInfo;
5712
5713                if (!mResolverReplaced) {
5714                    mResolveActivity.applicationInfo = mAndroidApplication;
5715                    mResolveActivity.name = ResolverActivity.class.getName();
5716                    mResolveActivity.packageName = mAndroidApplication.packageName;
5717                    mResolveActivity.processName = "system:ui";
5718                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5719                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5720                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5721                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5722                    mResolveActivity.exported = true;
5723                    mResolveActivity.enabled = true;
5724                    mResolveInfo.activityInfo = mResolveActivity;
5725                    mResolveInfo.priority = 0;
5726                    mResolveInfo.preferredOrder = 0;
5727                    mResolveInfo.match = 0;
5728                    mResolveComponentName = new ComponentName(
5729                            mAndroidApplication.packageName, mResolveActivity.name);
5730                }
5731            }
5732        }
5733
5734        if (DEBUG_PACKAGE_SCANNING) {
5735            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5736                Log.d(TAG, "Scanning package " + pkg.packageName);
5737        }
5738
5739        if (mPackages.containsKey(pkg.packageName)
5740                || mSharedLibraries.containsKey(pkg.packageName)) {
5741            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5742                    "Application package " + pkg.packageName
5743                    + " already installed.  Skipping duplicate.");
5744        }
5745
5746        // If we're only installing presumed-existing packages, require that the
5747        // scanned APK is both already known and at the path previously established
5748        // for it.  Previously unknown packages we pick up normally, but if we have an
5749        // a priori expectation about this package's install presence, enforce it.
5750        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
5751            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
5752            if (known != null) {
5753                if (DEBUG_PACKAGE_SCANNING) {
5754                    Log.d(TAG, "Examining " + pkg.codePath
5755                            + " and requiring known paths " + known.codePathString
5756                            + " & " + known.resourcePathString);
5757                }
5758                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
5759                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
5760                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
5761                            "Application package " + pkg.packageName
5762                            + " found at " + pkg.applicationInfo.getCodePath()
5763                            + " but expected at " + known.codePathString + "; ignoring.");
5764                }
5765            }
5766        }
5767
5768        // Initialize package source and resource directories
5769        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5770        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5771
5772        SharedUserSetting suid = null;
5773        PackageSetting pkgSetting = null;
5774
5775        if (!isSystemApp(pkg)) {
5776            // Only system apps can use these features.
5777            pkg.mOriginalPackages = null;
5778            pkg.mRealPackage = null;
5779            pkg.mAdoptPermissions = null;
5780        }
5781
5782        // writer
5783        synchronized (mPackages) {
5784            if (pkg.mSharedUserId != null) {
5785                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5786                if (suid == null) {
5787                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5788                            "Creating application package " + pkg.packageName
5789                            + " for shared user failed");
5790                }
5791                if (DEBUG_PACKAGE_SCANNING) {
5792                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5793                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5794                                + "): packages=" + suid.packages);
5795                }
5796            }
5797
5798            // Check if we are renaming from an original package name.
5799            PackageSetting origPackage = null;
5800            String realName = null;
5801            if (pkg.mOriginalPackages != null) {
5802                // This package may need to be renamed to a previously
5803                // installed name.  Let's check on that...
5804                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5805                if (pkg.mOriginalPackages.contains(renamed)) {
5806                    // This package had originally been installed as the
5807                    // original name, and we have already taken care of
5808                    // transitioning to the new one.  Just update the new
5809                    // one to continue using the old name.
5810                    realName = pkg.mRealPackage;
5811                    if (!pkg.packageName.equals(renamed)) {
5812                        // Callers into this function may have already taken
5813                        // care of renaming the package; only do it here if
5814                        // it is not already done.
5815                        pkg.setPackageName(renamed);
5816                    }
5817
5818                } else {
5819                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5820                        if ((origPackage = mSettings.peekPackageLPr(
5821                                pkg.mOriginalPackages.get(i))) != null) {
5822                            // We do have the package already installed under its
5823                            // original name...  should we use it?
5824                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5825                                // New package is not compatible with original.
5826                                origPackage = null;
5827                                continue;
5828                            } else if (origPackage.sharedUser != null) {
5829                                // Make sure uid is compatible between packages.
5830                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5831                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5832                                            + " to " + pkg.packageName + ": old uid "
5833                                            + origPackage.sharedUser.name
5834                                            + " differs from " + pkg.mSharedUserId);
5835                                    origPackage = null;
5836                                    continue;
5837                                }
5838                            } else {
5839                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5840                                        + pkg.packageName + " to old name " + origPackage.name);
5841                            }
5842                            break;
5843                        }
5844                    }
5845                }
5846            }
5847
5848            if (mTransferedPackages.contains(pkg.packageName)) {
5849                Slog.w(TAG, "Package " + pkg.packageName
5850                        + " was transferred to another, but its .apk remains");
5851            }
5852
5853            // Just create the setting, don't add it yet. For already existing packages
5854            // the PkgSetting exists already and doesn't have to be created.
5855            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5856                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5857                    pkg.applicationInfo.primaryCpuAbi,
5858                    pkg.applicationInfo.secondaryCpuAbi,
5859                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
5860                    user, false);
5861            if (pkgSetting == null) {
5862                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5863                        "Creating application package " + pkg.packageName + " failed");
5864            }
5865
5866            if (pkgSetting.origPackage != null) {
5867                // If we are first transitioning from an original package,
5868                // fix up the new package's name now.  We need to do this after
5869                // looking up the package under its new name, so getPackageLP
5870                // can take care of fiddling things correctly.
5871                pkg.setPackageName(origPackage.name);
5872
5873                // File a report about this.
5874                String msg = "New package " + pkgSetting.realName
5875                        + " renamed to replace old package " + pkgSetting.name;
5876                reportSettingsProblem(Log.WARN, msg);
5877
5878                // Make a note of it.
5879                mTransferedPackages.add(origPackage.name);
5880
5881                // No longer need to retain this.
5882                pkgSetting.origPackage = null;
5883            }
5884
5885            if (realName != null) {
5886                // Make a note of it.
5887                mTransferedPackages.add(pkg.packageName);
5888            }
5889
5890            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5891                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5892            }
5893
5894            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5895                // Check all shared libraries and map to their actual file path.
5896                // We only do this here for apps not on a system dir, because those
5897                // are the only ones that can fail an install due to this.  We
5898                // will take care of the system apps by updating all of their
5899                // library paths after the scan is done.
5900                updateSharedLibrariesLPw(pkg, null);
5901            }
5902
5903            if (mFoundPolicyFile) {
5904                SELinuxMMAC.assignSeinfoValue(pkg);
5905            }
5906
5907            pkg.applicationInfo.uid = pkgSetting.appId;
5908            pkg.mExtras = pkgSetting;
5909            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5910                try {
5911                    verifySignaturesLP(pkgSetting, pkg);
5912                    // We just determined the app is signed correctly, so bring
5913                    // over the latest parsed certs.
5914                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5915                } catch (PackageManagerException e) {
5916                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5917                        throw e;
5918                    }
5919                    // The signature has changed, but this package is in the system
5920                    // image...  let's recover!
5921                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5922                    // However...  if this package is part of a shared user, but it
5923                    // doesn't match the signature of the shared user, let's fail.
5924                    // What this means is that you can't change the signatures
5925                    // associated with an overall shared user, which doesn't seem all
5926                    // that unreasonable.
5927                    if (pkgSetting.sharedUser != null) {
5928                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5929                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5930                            throw new PackageManagerException(
5931                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5932                                            "Signature mismatch for shared user : "
5933                                            + pkgSetting.sharedUser);
5934                        }
5935                    }
5936                    // File a report about this.
5937                    String msg = "System package " + pkg.packageName
5938                        + " signature changed; retaining data.";
5939                    reportSettingsProblem(Log.WARN, msg);
5940                }
5941            } else {
5942                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5943                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5944                            + pkg.packageName + " upgrade keys do not match the "
5945                            + "previously installed version");
5946                } else {
5947                    // We just determined the app is signed correctly, so bring
5948                    // over the latest parsed certs.
5949                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5950                }
5951            }
5952            // Verify that this new package doesn't have any content providers
5953            // that conflict with existing packages.  Only do this if the
5954            // package isn't already installed, since we don't want to break
5955            // things that are installed.
5956            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5957                final int N = pkg.providers.size();
5958                int i;
5959                for (i=0; i<N; i++) {
5960                    PackageParser.Provider p = pkg.providers.get(i);
5961                    if (p.info.authority != null) {
5962                        String names[] = p.info.authority.split(";");
5963                        for (int j = 0; j < names.length; j++) {
5964                            if (mProvidersByAuthority.containsKey(names[j])) {
5965                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5966                                final String otherPackageName =
5967                                        ((other != null && other.getComponentName() != null) ?
5968                                                other.getComponentName().getPackageName() : "?");
5969                                throw new PackageManagerException(
5970                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5971                                                "Can't install because provider name " + names[j]
5972                                                + " (in package " + pkg.applicationInfo.packageName
5973                                                + ") is already used by " + otherPackageName);
5974                            }
5975                        }
5976                    }
5977                }
5978            }
5979
5980            if (pkg.mAdoptPermissions != null) {
5981                // This package wants to adopt ownership of permissions from
5982                // another package.
5983                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5984                    final String origName = pkg.mAdoptPermissions.get(i);
5985                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5986                    if (orig != null) {
5987                        if (verifyPackageUpdateLPr(orig, pkg)) {
5988                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5989                                    + pkg.packageName);
5990                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5991                        }
5992                    }
5993                }
5994            }
5995        }
5996
5997        final String pkgName = pkg.packageName;
5998
5999        final long scanFileTime = scanFile.lastModified();
6000        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6001        pkg.applicationInfo.processName = fixProcessName(
6002                pkg.applicationInfo.packageName,
6003                pkg.applicationInfo.processName,
6004                pkg.applicationInfo.uid);
6005
6006        File dataPath;
6007        if (mPlatformPackage == pkg) {
6008            // The system package is special.
6009            dataPath = new File(Environment.getDataDirectory(), "system");
6010
6011            pkg.applicationInfo.dataDir = dataPath.getPath();
6012
6013        } else {
6014            // This is a normal package, need to make its data directory.
6015            dataPath = getDataPathForPackage(pkg.packageName, 0);
6016
6017            boolean uidError = false;
6018            if (dataPath.exists()) {
6019                int currentUid = 0;
6020                try {
6021                    StructStat stat = Os.stat(dataPath.getPath());
6022                    currentUid = stat.st_uid;
6023                } catch (ErrnoException e) {
6024                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6025                }
6026
6027                // If we have mismatched owners for the data path, we have a problem.
6028                if (currentUid != pkg.applicationInfo.uid) {
6029                    boolean recovered = false;
6030                    if (currentUid == 0) {
6031                        // The directory somehow became owned by root.  Wow.
6032                        // This is probably because the system was stopped while
6033                        // installd was in the middle of messing with its libs
6034                        // directory.  Ask installd to fix that.
6035                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
6036                                pkg.applicationInfo.uid);
6037                        if (ret >= 0) {
6038                            recovered = true;
6039                            String msg = "Package " + pkg.packageName
6040                                    + " unexpectedly changed to uid 0; recovered to " +
6041                                    + pkg.applicationInfo.uid;
6042                            reportSettingsProblem(Log.WARN, msg);
6043                        }
6044                    }
6045                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6046                            || (scanFlags&SCAN_BOOTING) != 0)) {
6047                        // If this is a system app, we can at least delete its
6048                        // current data so the application will still work.
6049                        int ret = removeDataDirsLI(pkgName);
6050                        if (ret >= 0) {
6051                            // TODO: Kill the processes first
6052                            // Old data gone!
6053                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6054                                    ? "System package " : "Third party package ";
6055                            String msg = prefix + pkg.packageName
6056                                    + " has changed from uid: "
6057                                    + currentUid + " to "
6058                                    + pkg.applicationInfo.uid + "; old data erased";
6059                            reportSettingsProblem(Log.WARN, msg);
6060                            recovered = true;
6061
6062                            // And now re-install the app.
6063                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
6064                                                   pkg.applicationInfo.seinfo);
6065                            if (ret == -1) {
6066                                // Ack should not happen!
6067                                msg = prefix + pkg.packageName
6068                                        + " could not have data directory re-created after delete.";
6069                                reportSettingsProblem(Log.WARN, msg);
6070                                throw new PackageManagerException(
6071                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6072                            }
6073                        }
6074                        if (!recovered) {
6075                            mHasSystemUidErrors = true;
6076                        }
6077                    } else if (!recovered) {
6078                        // If we allow this install to proceed, we will be broken.
6079                        // Abort, abort!
6080                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6081                                "scanPackageLI");
6082                    }
6083                    if (!recovered) {
6084                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6085                            + pkg.applicationInfo.uid + "/fs_"
6086                            + currentUid;
6087                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6088                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6089                        String msg = "Package " + pkg.packageName
6090                                + " has mismatched uid: "
6091                                + currentUid + " on disk, "
6092                                + pkg.applicationInfo.uid + " in settings";
6093                        // writer
6094                        synchronized (mPackages) {
6095                            mSettings.mReadMessages.append(msg);
6096                            mSettings.mReadMessages.append('\n');
6097                            uidError = true;
6098                            if (!pkgSetting.uidError) {
6099                                reportSettingsProblem(Log.ERROR, msg);
6100                            }
6101                        }
6102                    }
6103                }
6104                pkg.applicationInfo.dataDir = dataPath.getPath();
6105                if (mShouldRestoreconData) {
6106                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6107                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
6108                                pkg.applicationInfo.uid);
6109                }
6110            } else {
6111                if (DEBUG_PACKAGE_SCANNING) {
6112                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6113                        Log.v(TAG, "Want this data dir: " + dataPath);
6114                }
6115                //invoke installer to do the actual installation
6116                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
6117                                           pkg.applicationInfo.seinfo);
6118                if (ret < 0) {
6119                    // Error from installer
6120                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6121                            "Unable to create data dirs [errorCode=" + ret + "]");
6122                }
6123
6124                if (dataPath.exists()) {
6125                    pkg.applicationInfo.dataDir = dataPath.getPath();
6126                } else {
6127                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6128                    pkg.applicationInfo.dataDir = null;
6129                }
6130            }
6131
6132            pkgSetting.uidError = uidError;
6133        }
6134
6135        final String path = scanFile.getPath();
6136        final String codePath = pkg.applicationInfo.getCodePath();
6137        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6138        if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6139            setBundledAppAbisAndRoots(pkg, pkgSetting);
6140
6141            // If we haven't found any native libraries for the app, check if it has
6142            // renderscript code. We'll need to force the app to 32 bit if it has
6143            // renderscript bitcode.
6144            if (pkg.applicationInfo.primaryCpuAbi == null
6145                    && pkg.applicationInfo.secondaryCpuAbi == null
6146                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
6147                NativeLibraryHelper.Handle handle = null;
6148                try {
6149                    handle = NativeLibraryHelper.Handle.create(scanFile);
6150                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6151                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6152                    }
6153                } catch (IOException ioe) {
6154                    Slog.w(TAG, "Error scanning system app : " + ioe);
6155                } finally {
6156                    IoUtils.closeQuietly(handle);
6157                }
6158            }
6159
6160            setNativeLibraryPaths(pkg);
6161        } else {
6162            // TODO: We can probably be smarter about this stuff. For installed apps,
6163            // we can calculate this information at install time once and for all. For
6164            // system apps, we can probably assume that this information doesn't change
6165            // after the first boot scan. As things stand, we do lots of unnecessary work.
6166
6167            // Give ourselves some initial paths; we'll come back for another
6168            // pass once we've determined ABI below.
6169            setNativeLibraryPaths(pkg);
6170
6171            final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg);
6172            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6173            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6174
6175            NativeLibraryHelper.Handle handle = null;
6176            try {
6177                handle = NativeLibraryHelper.Handle.create(scanFile);
6178                // TODO(multiArch): This can be null for apps that didn't go through the
6179                // usual installation process. We can calculate it again, like we
6180                // do during install time.
6181                //
6182                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6183                // unnecessary.
6184                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6185
6186                // Null out the abis so that they can be recalculated.
6187                pkg.applicationInfo.primaryCpuAbi = null;
6188                pkg.applicationInfo.secondaryCpuAbi = null;
6189                if (isMultiArch(pkg.applicationInfo)) {
6190                    // Warn if we've set an abiOverride for multi-lib packages..
6191                    // By definition, we need to copy both 32 and 64 bit libraries for
6192                    // such packages.
6193                    if (pkg.cpuAbiOverride != null
6194                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
6195                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
6196                    }
6197
6198                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
6199                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
6200                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
6201                        if (isAsec) {
6202                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
6203                        } else {
6204                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6205                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
6206                                    useIsaSpecificSubdirs);
6207                        }
6208                    }
6209
6210                    maybeThrowExceptionForMultiArchCopy(
6211                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
6212
6213                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
6214                        if (isAsec) {
6215                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
6216                        } else {
6217                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6218                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
6219                                    useIsaSpecificSubdirs);
6220                        }
6221                    }
6222
6223                    maybeThrowExceptionForMultiArchCopy(
6224                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
6225
6226                    if (abi64 >= 0) {
6227                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
6228                    }
6229
6230                    if (abi32 >= 0) {
6231                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
6232                        if (abi64 >= 0) {
6233                            pkg.applicationInfo.secondaryCpuAbi = abi;
6234                        } else {
6235                            pkg.applicationInfo.primaryCpuAbi = abi;
6236                        }
6237                    }
6238                } else {
6239                    String[] abiList = (cpuAbiOverride != null) ?
6240                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
6241
6242                    // Enable gross and lame hacks for apps that are built with old
6243                    // SDK tools. We must scan their APKs for renderscript bitcode and
6244                    // not launch them if it's present. Don't bother checking on devices
6245                    // that don't have 64 bit support.
6246                    boolean needsRenderScriptOverride = false;
6247                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
6248                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6249                        abiList = Build.SUPPORTED_32_BIT_ABIS;
6250                        needsRenderScriptOverride = true;
6251                    }
6252
6253                    final int copyRet;
6254                    if (isAsec) {
6255                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6256                    } else {
6257                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6258                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
6259                    }
6260
6261                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
6262                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6263                                "Error unpackaging native libs for app, errorCode=" + copyRet);
6264                    }
6265
6266                    if (copyRet >= 0) {
6267                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
6268                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
6269                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
6270                    } else if (needsRenderScriptOverride) {
6271                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
6272                    }
6273                }
6274            } catch (IOException ioe) {
6275                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
6276            } finally {
6277                IoUtils.closeQuietly(handle);
6278            }
6279
6280            // Now that we've calculated the ABIs and determined if it's an internal app,
6281            // we will go ahead and populate the nativeLibraryPath.
6282            setNativeLibraryPaths(pkg);
6283
6284            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6285            final int[] userIds = sUserManager.getUserIds();
6286            synchronized (mInstallLock) {
6287                // Create a native library symlink only if we have native libraries
6288                // and if the native libraries are 32 bit libraries. We do not provide
6289                // this symlink for 64 bit libraries.
6290                if (pkg.applicationInfo.primaryCpuAbi != null &&
6291                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6292                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6293                    for (int userId : userIds) {
6294                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
6295                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6296                                    "Failed linking native library dir (user=" + userId + ")");
6297                        }
6298                    }
6299                }
6300            }
6301        }
6302
6303        // This is a special case for the "system" package, where the ABI is
6304        // dictated by the zygote configuration (and init.rc). We should keep track
6305        // of this ABI so that we can deal with "normal" applications that run under
6306        // the same UID correctly.
6307        if (mPlatformPackage == pkg) {
6308            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6309                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6310        }
6311
6312        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6313        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6314        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6315        // Copy the derived override back to the parsed package, so that we can
6316        // update the package settings accordingly.
6317        pkg.cpuAbiOverride = cpuAbiOverride;
6318
6319        if (DEBUG_ABI_SELECTION) {
6320            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6321                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6322                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6323        }
6324
6325        // Push the derived path down into PackageSettings so we know what to
6326        // clean up at uninstall time.
6327        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6328
6329        if (DEBUG_ABI_SELECTION) {
6330            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6331                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6332                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6333        }
6334
6335        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6336            // We don't do this here during boot because we can do it all
6337            // at once after scanning all existing packages.
6338            //
6339            // We also do this *before* we perform dexopt on this package, so that
6340            // we can avoid redundant dexopts, and also to make sure we've got the
6341            // code and package path correct.
6342            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6343                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6344        }
6345
6346        if ((scanFlags & SCAN_NO_DEX) == 0) {
6347            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6348                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6349            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6350                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6351            }
6352        }
6353        if (mFactoryTest && pkg.requestedPermissions.contains(
6354                android.Manifest.permission.FACTORY_TEST)) {
6355            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6356        }
6357
6358        ArrayList<PackageParser.Package> clientLibPkgs = null;
6359
6360        // writer
6361        synchronized (mPackages) {
6362            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6363                // Only system apps can add new shared libraries.
6364                if (pkg.libraryNames != null) {
6365                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6366                        String name = pkg.libraryNames.get(i);
6367                        boolean allowed = false;
6368                        if (pkg.isUpdatedSystemApp()) {
6369                            // New library entries can only be added through the
6370                            // system image.  This is important to get rid of a lot
6371                            // of nasty edge cases: for example if we allowed a non-
6372                            // system update of the app to add a library, then uninstalling
6373                            // the update would make the library go away, and assumptions
6374                            // we made such as through app install filtering would now
6375                            // have allowed apps on the device which aren't compatible
6376                            // with it.  Better to just have the restriction here, be
6377                            // conservative, and create many fewer cases that can negatively
6378                            // impact the user experience.
6379                            final PackageSetting sysPs = mSettings
6380                                    .getDisabledSystemPkgLPr(pkg.packageName);
6381                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6382                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6383                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6384                                        allowed = true;
6385                                        allowed = true;
6386                                        break;
6387                                    }
6388                                }
6389                            }
6390                        } else {
6391                            allowed = true;
6392                        }
6393                        if (allowed) {
6394                            if (!mSharedLibraries.containsKey(name)) {
6395                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6396                            } else if (!name.equals(pkg.packageName)) {
6397                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6398                                        + name + " already exists; skipping");
6399                            }
6400                        } else {
6401                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6402                                    + name + " that is not declared on system image; skipping");
6403                        }
6404                    }
6405                    if ((scanFlags&SCAN_BOOTING) == 0) {
6406                        // If we are not booting, we need to update any applications
6407                        // that are clients of our shared library.  If we are booting,
6408                        // this will all be done once the scan is complete.
6409                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6410                    }
6411                }
6412            }
6413        }
6414
6415        // We also need to dexopt any apps that are dependent on this library.  Note that
6416        // if these fail, we should abort the install since installing the library will
6417        // result in some apps being broken.
6418        if (clientLibPkgs != null) {
6419            if ((scanFlags & SCAN_NO_DEX) == 0) {
6420                for (int i = 0; i < clientLibPkgs.size(); i++) {
6421                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6422                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6423                            null /* instruction sets */, forceDex,
6424                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6425                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6426                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6427                                "scanPackageLI failed to dexopt clientLibPkgs");
6428                    }
6429                }
6430            }
6431        }
6432
6433        // Request the ActivityManager to kill the process(only for existing packages)
6434        // so that we do not end up in a confused state while the user is still using the older
6435        // version of the application while the new one gets installed.
6436        if ((scanFlags & SCAN_REPLACING) != 0) {
6437            killApplication(pkg.applicationInfo.packageName,
6438                        pkg.applicationInfo.uid, "update pkg");
6439        }
6440
6441        // Also need to kill any apps that are dependent on the library.
6442        if (clientLibPkgs != null) {
6443            for (int i=0; i<clientLibPkgs.size(); i++) {
6444                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6445                killApplication(clientPkg.applicationInfo.packageName,
6446                        clientPkg.applicationInfo.uid, "update lib");
6447            }
6448        }
6449
6450        // writer
6451        synchronized (mPackages) {
6452            // We don't expect installation to fail beyond this point
6453
6454            // Add the new setting to mSettings
6455            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6456            // Add the new setting to mPackages
6457            mPackages.put(pkg.applicationInfo.packageName, pkg);
6458            // Make sure we don't accidentally delete its data.
6459            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6460            while (iter.hasNext()) {
6461                PackageCleanItem item = iter.next();
6462                if (pkgName.equals(item.packageName)) {
6463                    iter.remove();
6464                }
6465            }
6466
6467            // Take care of first install / last update times.
6468            if (currentTime != 0) {
6469                if (pkgSetting.firstInstallTime == 0) {
6470                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6471                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6472                    pkgSetting.lastUpdateTime = currentTime;
6473                }
6474            } else if (pkgSetting.firstInstallTime == 0) {
6475                // We need *something*.  Take time time stamp of the file.
6476                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6477            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6478                if (scanFileTime != pkgSetting.timeStamp) {
6479                    // A package on the system image has changed; consider this
6480                    // to be an update.
6481                    pkgSetting.lastUpdateTime = scanFileTime;
6482                }
6483            }
6484
6485            // Add the package's KeySets to the global KeySetManagerService
6486            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6487            try {
6488                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6489                if (pkg.mKeySetMapping != null) {
6490                    ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping);
6491                    if (pkg.mUpgradeKeySets != null) {
6492                        ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets);
6493                    }
6494                }
6495            } catch (NullPointerException e) {
6496                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6497            } catch (IllegalArgumentException e) {
6498                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6499            }
6500
6501            int N = pkg.providers.size();
6502            StringBuilder r = null;
6503            int i;
6504            for (i=0; i<N; i++) {
6505                PackageParser.Provider p = pkg.providers.get(i);
6506                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6507                        p.info.processName, pkg.applicationInfo.uid);
6508                mProviders.addProvider(p);
6509                p.syncable = p.info.isSyncable;
6510                if (p.info.authority != null) {
6511                    String names[] = p.info.authority.split(";");
6512                    p.info.authority = null;
6513                    for (int j = 0; j < names.length; j++) {
6514                        if (j == 1 && p.syncable) {
6515                            // We only want the first authority for a provider to possibly be
6516                            // syncable, so if we already added this provider using a different
6517                            // authority clear the syncable flag. We copy the provider before
6518                            // changing it because the mProviders object contains a reference
6519                            // to a provider that we don't want to change.
6520                            // Only do this for the second authority since the resulting provider
6521                            // object can be the same for all future authorities for this provider.
6522                            p = new PackageParser.Provider(p);
6523                            p.syncable = false;
6524                        }
6525                        if (!mProvidersByAuthority.containsKey(names[j])) {
6526                            mProvidersByAuthority.put(names[j], p);
6527                            if (p.info.authority == null) {
6528                                p.info.authority = names[j];
6529                            } else {
6530                                p.info.authority = p.info.authority + ";" + names[j];
6531                            }
6532                            if (DEBUG_PACKAGE_SCANNING) {
6533                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6534                                    Log.d(TAG, "Registered content provider: " + names[j]
6535                                            + ", className = " + p.info.name + ", isSyncable = "
6536                                            + p.info.isSyncable);
6537                            }
6538                        } else {
6539                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6540                            Slog.w(TAG, "Skipping provider name " + names[j] +
6541                                    " (in package " + pkg.applicationInfo.packageName +
6542                                    "): name already used by "
6543                                    + ((other != null && other.getComponentName() != null)
6544                                            ? other.getComponentName().getPackageName() : "?"));
6545                        }
6546                    }
6547                }
6548                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6549                    if (r == null) {
6550                        r = new StringBuilder(256);
6551                    } else {
6552                        r.append(' ');
6553                    }
6554                    r.append(p.info.name);
6555                }
6556            }
6557            if (r != null) {
6558                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6559            }
6560
6561            N = pkg.services.size();
6562            r = null;
6563            for (i=0; i<N; i++) {
6564                PackageParser.Service s = pkg.services.get(i);
6565                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6566                        s.info.processName, pkg.applicationInfo.uid);
6567                mServices.addService(s);
6568                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6569                    if (r == null) {
6570                        r = new StringBuilder(256);
6571                    } else {
6572                        r.append(' ');
6573                    }
6574                    r.append(s.info.name);
6575                }
6576            }
6577            if (r != null) {
6578                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6579            }
6580
6581            N = pkg.receivers.size();
6582            r = null;
6583            for (i=0; i<N; i++) {
6584                PackageParser.Activity a = pkg.receivers.get(i);
6585                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6586                        a.info.processName, pkg.applicationInfo.uid);
6587                mReceivers.addActivity(a, "receiver");
6588                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6589                    if (r == null) {
6590                        r = new StringBuilder(256);
6591                    } else {
6592                        r.append(' ');
6593                    }
6594                    r.append(a.info.name);
6595                }
6596            }
6597            if (r != null) {
6598                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6599            }
6600
6601            N = pkg.activities.size();
6602            r = null;
6603            for (i=0; i<N; i++) {
6604                PackageParser.Activity a = pkg.activities.get(i);
6605                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6606                        a.info.processName, pkg.applicationInfo.uid);
6607                mActivities.addActivity(a, "activity");
6608                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6609                    if (r == null) {
6610                        r = new StringBuilder(256);
6611                    } else {
6612                        r.append(' ');
6613                    }
6614                    r.append(a.info.name);
6615                }
6616            }
6617            if (r != null) {
6618                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6619            }
6620
6621            N = pkg.permissionGroups.size();
6622            r = null;
6623            for (i=0; i<N; i++) {
6624                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6625                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6626                if (cur == null) {
6627                    mPermissionGroups.put(pg.info.name, pg);
6628                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6629                        if (r == null) {
6630                            r = new StringBuilder(256);
6631                        } else {
6632                            r.append(' ');
6633                        }
6634                        r.append(pg.info.name);
6635                    }
6636                } else {
6637                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6638                            + pg.info.packageName + " ignored: original from "
6639                            + cur.info.packageName);
6640                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6641                        if (r == null) {
6642                            r = new StringBuilder(256);
6643                        } else {
6644                            r.append(' ');
6645                        }
6646                        r.append("DUP:");
6647                        r.append(pg.info.name);
6648                    }
6649                }
6650            }
6651            if (r != null) {
6652                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6653            }
6654
6655            N = pkg.permissions.size();
6656            r = null;
6657            for (i=0; i<N; i++) {
6658                PackageParser.Permission p = pkg.permissions.get(i);
6659                ArrayMap<String, BasePermission> permissionMap =
6660                        p.tree ? mSettings.mPermissionTrees
6661                        : mSettings.mPermissions;
6662                p.group = mPermissionGroups.get(p.info.group);
6663                if (p.info.group == null || p.group != null) {
6664                    BasePermission bp = permissionMap.get(p.info.name);
6665
6666                    // Allow system apps to redefine non-system permissions
6667                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6668                        final boolean currentOwnerIsSystem = (bp.perm != null
6669                                && isSystemApp(bp.perm.owner));
6670                        if (isSystemApp(p.owner)) {
6671                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6672                                // It's a built-in permission and no owner, take ownership now
6673                                bp.packageSetting = pkgSetting;
6674                                bp.perm = p;
6675                                bp.uid = pkg.applicationInfo.uid;
6676                                bp.sourcePackage = p.info.packageName;
6677                            } else if (!currentOwnerIsSystem) {
6678                                String msg = "New decl " + p.owner + " of permission  "
6679                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6680                                reportSettingsProblem(Log.WARN, msg);
6681                                bp = null;
6682                            }
6683                        }
6684                    }
6685
6686                    if (bp == null) {
6687                        bp = new BasePermission(p.info.name, p.info.packageName,
6688                                BasePermission.TYPE_NORMAL);
6689                        permissionMap.put(p.info.name, bp);
6690                    }
6691
6692                    if (bp.perm == null) {
6693                        if (bp.sourcePackage == null
6694                                || bp.sourcePackage.equals(p.info.packageName)) {
6695                            BasePermission tree = findPermissionTreeLP(p.info.name);
6696                            if (tree == null
6697                                    || tree.sourcePackage.equals(p.info.packageName)) {
6698                                bp.packageSetting = pkgSetting;
6699                                bp.perm = p;
6700                                bp.uid = pkg.applicationInfo.uid;
6701                                bp.sourcePackage = p.info.packageName;
6702                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6703                                    if (r == null) {
6704                                        r = new StringBuilder(256);
6705                                    } else {
6706                                        r.append(' ');
6707                                    }
6708                                    r.append(p.info.name);
6709                                }
6710                            } else {
6711                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6712                                        + p.info.packageName + " ignored: base tree "
6713                                        + tree.name + " is from package "
6714                                        + tree.sourcePackage);
6715                            }
6716                        } else {
6717                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6718                                    + p.info.packageName + " ignored: original from "
6719                                    + bp.sourcePackage);
6720                        }
6721                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6722                        if (r == null) {
6723                            r = new StringBuilder(256);
6724                        } else {
6725                            r.append(' ');
6726                        }
6727                        r.append("DUP:");
6728                        r.append(p.info.name);
6729                    }
6730                    if (bp.perm == p) {
6731                        bp.protectionLevel = p.info.protectionLevel;
6732                    }
6733                } else {
6734                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6735                            + p.info.packageName + " ignored: no group "
6736                            + p.group);
6737                }
6738            }
6739            if (r != null) {
6740                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6741            }
6742
6743            N = pkg.instrumentation.size();
6744            r = null;
6745            for (i=0; i<N; i++) {
6746                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6747                a.info.packageName = pkg.applicationInfo.packageName;
6748                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6749                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6750                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6751                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6752                a.info.dataDir = pkg.applicationInfo.dataDir;
6753
6754                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6755                // need other information about the application, like the ABI and what not ?
6756                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6757                mInstrumentation.put(a.getComponentName(), a);
6758                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6759                    if (r == null) {
6760                        r = new StringBuilder(256);
6761                    } else {
6762                        r.append(' ');
6763                    }
6764                    r.append(a.info.name);
6765                }
6766            }
6767            if (r != null) {
6768                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6769            }
6770
6771            if (pkg.protectedBroadcasts != null) {
6772                N = pkg.protectedBroadcasts.size();
6773                for (i=0; i<N; i++) {
6774                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6775                }
6776            }
6777
6778            pkgSetting.setTimeStamp(scanFileTime);
6779
6780            // Create idmap files for pairs of (packages, overlay packages).
6781            // Note: "android", ie framework-res.apk, is handled by native layers.
6782            if (pkg.mOverlayTarget != null) {
6783                // This is an overlay package.
6784                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6785                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6786                        mOverlays.put(pkg.mOverlayTarget,
6787                                new ArrayMap<String, PackageParser.Package>());
6788                    }
6789                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6790                    map.put(pkg.packageName, pkg);
6791                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6792                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6793                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6794                                "scanPackageLI failed to createIdmap");
6795                    }
6796                }
6797            } else if (mOverlays.containsKey(pkg.packageName) &&
6798                    !pkg.packageName.equals("android")) {
6799                // This is a regular package, with one or more known overlay packages.
6800                createIdmapsForPackageLI(pkg);
6801            }
6802        }
6803
6804        return pkg;
6805    }
6806
6807    /**
6808     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6809     * i.e, so that all packages can be run inside a single process if required.
6810     *
6811     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6812     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6813     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6814     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6815     * updating a package that belongs to a shared user.
6816     *
6817     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6818     * adds unnecessary complexity.
6819     */
6820    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6821            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6822        String requiredInstructionSet = null;
6823        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6824            requiredInstructionSet = VMRuntime.getInstructionSet(
6825                     scannedPackage.applicationInfo.primaryCpuAbi);
6826        }
6827
6828        PackageSetting requirer = null;
6829        for (PackageSetting ps : packagesForUser) {
6830            // If packagesForUser contains scannedPackage, we skip it. This will happen
6831            // when scannedPackage is an update of an existing package. Without this check,
6832            // we will never be able to change the ABI of any package belonging to a shared
6833            // user, even if it's compatible with other packages.
6834            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6835                if (ps.primaryCpuAbiString == null) {
6836                    continue;
6837                }
6838
6839                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6840                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6841                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6842                    // this but there's not much we can do.
6843                    String errorMessage = "Instruction set mismatch, "
6844                            + ((requirer == null) ? "[caller]" : requirer)
6845                            + " requires " + requiredInstructionSet + " whereas " + ps
6846                            + " requires " + instructionSet;
6847                    Slog.w(TAG, errorMessage);
6848                }
6849
6850                if (requiredInstructionSet == null) {
6851                    requiredInstructionSet = instructionSet;
6852                    requirer = ps;
6853                }
6854            }
6855        }
6856
6857        if (requiredInstructionSet != null) {
6858            String adjustedAbi;
6859            if (requirer != null) {
6860                // requirer != null implies that either scannedPackage was null or that scannedPackage
6861                // did not require an ABI, in which case we have to adjust scannedPackage to match
6862                // the ABI of the set (which is the same as requirer's ABI)
6863                adjustedAbi = requirer.primaryCpuAbiString;
6864                if (scannedPackage != null) {
6865                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6866                }
6867            } else {
6868                // requirer == null implies that we're updating all ABIs in the set to
6869                // match scannedPackage.
6870                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6871            }
6872
6873            for (PackageSetting ps : packagesForUser) {
6874                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6875                    if (ps.primaryCpuAbiString != null) {
6876                        continue;
6877                    }
6878
6879                    ps.primaryCpuAbiString = adjustedAbi;
6880                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6881                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6882                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6883
6884                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
6885                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
6886                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6887                            ps.primaryCpuAbiString = null;
6888                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6889                            return;
6890                        } else {
6891                            mInstaller.rmdex(ps.codePathString,
6892                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
6893                        }
6894                    }
6895                }
6896            }
6897        }
6898    }
6899
6900    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6901        synchronized (mPackages) {
6902            mResolverReplaced = true;
6903            // Set up information for custom user intent resolution activity.
6904            mResolveActivity.applicationInfo = pkg.applicationInfo;
6905            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6906            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6907            mResolveActivity.processName = pkg.applicationInfo.packageName;
6908            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6909            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6910                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6911            mResolveActivity.theme = 0;
6912            mResolveActivity.exported = true;
6913            mResolveActivity.enabled = true;
6914            mResolveInfo.activityInfo = mResolveActivity;
6915            mResolveInfo.priority = 0;
6916            mResolveInfo.preferredOrder = 0;
6917            mResolveInfo.match = 0;
6918            mResolveComponentName = mCustomResolverComponentName;
6919            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6920                    mResolveComponentName);
6921        }
6922    }
6923
6924    private static String calculateBundledApkRoot(final String codePathString) {
6925        final File codePath = new File(codePathString);
6926        final File codeRoot;
6927        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6928            codeRoot = Environment.getRootDirectory();
6929        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6930            codeRoot = Environment.getOemDirectory();
6931        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6932            codeRoot = Environment.getVendorDirectory();
6933        } else {
6934            // Unrecognized code path; take its top real segment as the apk root:
6935            // e.g. /something/app/blah.apk => /something
6936            try {
6937                File f = codePath.getCanonicalFile();
6938                File parent = f.getParentFile();    // non-null because codePath is a file
6939                File tmp;
6940                while ((tmp = parent.getParentFile()) != null) {
6941                    f = parent;
6942                    parent = tmp;
6943                }
6944                codeRoot = f;
6945                Slog.w(TAG, "Unrecognized code path "
6946                        + codePath + " - using " + codeRoot);
6947            } catch (IOException e) {
6948                // Can't canonicalize the code path -- shenanigans?
6949                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6950                return Environment.getRootDirectory().getPath();
6951            }
6952        }
6953        return codeRoot.getPath();
6954    }
6955
6956    /**
6957     * Derive and set the location of native libraries for the given package,
6958     * which varies depending on where and how the package was installed.
6959     */
6960    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6961        final ApplicationInfo info = pkg.applicationInfo;
6962        final String codePath = pkg.codePath;
6963        final File codeFile = new File(codePath);
6964        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
6965        final boolean asecApp = info.isForwardLocked() || isExternal(info);
6966
6967        info.nativeLibraryRootDir = null;
6968        info.nativeLibraryRootRequiresIsa = false;
6969        info.nativeLibraryDir = null;
6970        info.secondaryNativeLibraryDir = null;
6971
6972        if (isApkFile(codeFile)) {
6973            // Monolithic install
6974            if (bundledApp) {
6975                // If "/system/lib64/apkname" exists, assume that is the per-package
6976                // native library directory to use; otherwise use "/system/lib/apkname".
6977                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6978                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6979                        getPrimaryInstructionSet(info));
6980
6981                // This is a bundled system app so choose the path based on the ABI.
6982                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6983                // is just the default path.
6984                final String apkName = deriveCodePathName(codePath);
6985                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6986                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6987                        apkName).getAbsolutePath();
6988
6989                if (info.secondaryCpuAbi != null) {
6990                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6991                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6992                            secondaryLibDir, apkName).getAbsolutePath();
6993                }
6994            } else if (asecApp) {
6995                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6996                        .getAbsolutePath();
6997            } else {
6998                final String apkName = deriveCodePathName(codePath);
6999                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7000                        .getAbsolutePath();
7001            }
7002
7003            info.nativeLibraryRootRequiresIsa = false;
7004            info.nativeLibraryDir = info.nativeLibraryRootDir;
7005        } else {
7006            // Cluster install
7007            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7008            info.nativeLibraryRootRequiresIsa = true;
7009
7010            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7011                    getPrimaryInstructionSet(info)).getAbsolutePath();
7012
7013            if (info.secondaryCpuAbi != null) {
7014                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7015                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7016            }
7017        }
7018    }
7019
7020    /**
7021     * Calculate the abis and roots for a bundled app. These can uniquely
7022     * be determined from the contents of the system partition, i.e whether
7023     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7024     * of this information, and instead assume that the system was built
7025     * sensibly.
7026     */
7027    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7028                                           PackageSetting pkgSetting) {
7029        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7030
7031        // If "/system/lib64/apkname" exists, assume that is the per-package
7032        // native library directory to use; otherwise use "/system/lib/apkname".
7033        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7034        setBundledAppAbi(pkg, apkRoot, apkName);
7035        // pkgSetting might be null during rescan following uninstall of updates
7036        // to a bundled app, so accommodate that possibility.  The settings in
7037        // that case will be established later from the parsed package.
7038        //
7039        // If the settings aren't null, sync them up with what we've just derived.
7040        // note that apkRoot isn't stored in the package settings.
7041        if (pkgSetting != null) {
7042            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7043            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7044        }
7045    }
7046
7047    /**
7048     * Deduces the ABI of a bundled app and sets the relevant fields on the
7049     * parsed pkg object.
7050     *
7051     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7052     *        under which system libraries are installed.
7053     * @param apkName the name of the installed package.
7054     */
7055    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7056        final File codeFile = new File(pkg.codePath);
7057
7058        final boolean has64BitLibs;
7059        final boolean has32BitLibs;
7060        if (isApkFile(codeFile)) {
7061            // Monolithic install
7062            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7063            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7064        } else {
7065            // Cluster install
7066            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7067            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7068                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7069                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7070                has64BitLibs = (new File(rootDir, isa)).exists();
7071            } else {
7072                has64BitLibs = false;
7073            }
7074            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7075                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7076                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7077                has32BitLibs = (new File(rootDir, isa)).exists();
7078            } else {
7079                has32BitLibs = false;
7080            }
7081        }
7082
7083        if (has64BitLibs && !has32BitLibs) {
7084            // The package has 64 bit libs, but not 32 bit libs. Its primary
7085            // ABI should be 64 bit. We can safely assume here that the bundled
7086            // native libraries correspond to the most preferred ABI in the list.
7087
7088            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7089            pkg.applicationInfo.secondaryCpuAbi = null;
7090        } else if (has32BitLibs && !has64BitLibs) {
7091            // The package has 32 bit libs but not 64 bit libs. Its primary
7092            // ABI should be 32 bit.
7093
7094            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7095            pkg.applicationInfo.secondaryCpuAbi = null;
7096        } else if (has32BitLibs && has64BitLibs) {
7097            // The application has both 64 and 32 bit bundled libraries. We check
7098            // here that the app declares multiArch support, and warn if it doesn't.
7099            //
7100            // We will be lenient here and record both ABIs. The primary will be the
7101            // ABI that's higher on the list, i.e, a device that's configured to prefer
7102            // 64 bit apps will see a 64 bit primary ABI,
7103
7104            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7105                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7106            }
7107
7108            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7109                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7110                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7111            } else {
7112                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7113                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7114            }
7115        } else {
7116            pkg.applicationInfo.primaryCpuAbi = null;
7117            pkg.applicationInfo.secondaryCpuAbi = null;
7118        }
7119    }
7120
7121    private void killApplication(String pkgName, int appId, String reason) {
7122        // Request the ActivityManager to kill the process(only for existing packages)
7123        // so that we do not end up in a confused state while the user is still using the older
7124        // version of the application while the new one gets installed.
7125        IActivityManager am = ActivityManagerNative.getDefault();
7126        if (am != null) {
7127            try {
7128                am.killApplicationWithAppId(pkgName, appId, reason);
7129            } catch (RemoteException e) {
7130            }
7131        }
7132    }
7133
7134    void removePackageLI(PackageSetting ps, boolean chatty) {
7135        if (DEBUG_INSTALL) {
7136            if (chatty)
7137                Log.d(TAG, "Removing package " + ps.name);
7138        }
7139
7140        // writer
7141        synchronized (mPackages) {
7142            mPackages.remove(ps.name);
7143            final PackageParser.Package pkg = ps.pkg;
7144            if (pkg != null) {
7145                cleanPackageDataStructuresLILPw(pkg, chatty);
7146            }
7147        }
7148    }
7149
7150    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7151        if (DEBUG_INSTALL) {
7152            if (chatty)
7153                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7154        }
7155
7156        // writer
7157        synchronized (mPackages) {
7158            mPackages.remove(pkg.applicationInfo.packageName);
7159            cleanPackageDataStructuresLILPw(pkg, chatty);
7160        }
7161    }
7162
7163    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7164        int N = pkg.providers.size();
7165        StringBuilder r = null;
7166        int i;
7167        for (i=0; i<N; i++) {
7168            PackageParser.Provider p = pkg.providers.get(i);
7169            mProviders.removeProvider(p);
7170            if (p.info.authority == null) {
7171
7172                /* There was another ContentProvider with this authority when
7173                 * this app was installed so this authority is null,
7174                 * Ignore it as we don't have to unregister the provider.
7175                 */
7176                continue;
7177            }
7178            String names[] = p.info.authority.split(";");
7179            for (int j = 0; j < names.length; j++) {
7180                if (mProvidersByAuthority.get(names[j]) == p) {
7181                    mProvidersByAuthority.remove(names[j]);
7182                    if (DEBUG_REMOVE) {
7183                        if (chatty)
7184                            Log.d(TAG, "Unregistered content provider: " + names[j]
7185                                    + ", className = " + p.info.name + ", isSyncable = "
7186                                    + p.info.isSyncable);
7187                    }
7188                }
7189            }
7190            if (DEBUG_REMOVE && chatty) {
7191                if (r == null) {
7192                    r = new StringBuilder(256);
7193                } else {
7194                    r.append(' ');
7195                }
7196                r.append(p.info.name);
7197            }
7198        }
7199        if (r != null) {
7200            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7201        }
7202
7203        N = pkg.services.size();
7204        r = null;
7205        for (i=0; i<N; i++) {
7206            PackageParser.Service s = pkg.services.get(i);
7207            mServices.removeService(s);
7208            if (chatty) {
7209                if (r == null) {
7210                    r = new StringBuilder(256);
7211                } else {
7212                    r.append(' ');
7213                }
7214                r.append(s.info.name);
7215            }
7216        }
7217        if (r != null) {
7218            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7219        }
7220
7221        N = pkg.receivers.size();
7222        r = null;
7223        for (i=0; i<N; i++) {
7224            PackageParser.Activity a = pkg.receivers.get(i);
7225            mReceivers.removeActivity(a, "receiver");
7226            if (DEBUG_REMOVE && chatty) {
7227                if (r == null) {
7228                    r = new StringBuilder(256);
7229                } else {
7230                    r.append(' ');
7231                }
7232                r.append(a.info.name);
7233            }
7234        }
7235        if (r != null) {
7236            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7237        }
7238
7239        N = pkg.activities.size();
7240        r = null;
7241        for (i=0; i<N; i++) {
7242            PackageParser.Activity a = pkg.activities.get(i);
7243            mActivities.removeActivity(a, "activity");
7244            if (DEBUG_REMOVE && chatty) {
7245                if (r == null) {
7246                    r = new StringBuilder(256);
7247                } else {
7248                    r.append(' ');
7249                }
7250                r.append(a.info.name);
7251            }
7252        }
7253        if (r != null) {
7254            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7255        }
7256
7257        N = pkg.permissions.size();
7258        r = null;
7259        for (i=0; i<N; i++) {
7260            PackageParser.Permission p = pkg.permissions.get(i);
7261            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7262            if (bp == null) {
7263                bp = mSettings.mPermissionTrees.get(p.info.name);
7264            }
7265            if (bp != null && bp.perm == p) {
7266                bp.perm = null;
7267                if (DEBUG_REMOVE && chatty) {
7268                    if (r == null) {
7269                        r = new StringBuilder(256);
7270                    } else {
7271                        r.append(' ');
7272                    }
7273                    r.append(p.info.name);
7274                }
7275            }
7276            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7277                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7278                if (appOpPerms != null) {
7279                    appOpPerms.remove(pkg.packageName);
7280                }
7281            }
7282        }
7283        if (r != null) {
7284            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7285        }
7286
7287        N = pkg.requestedPermissions.size();
7288        r = null;
7289        for (i=0; i<N; i++) {
7290            String perm = pkg.requestedPermissions.get(i);
7291            BasePermission bp = mSettings.mPermissions.get(perm);
7292            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7293                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7294                if (appOpPerms != null) {
7295                    appOpPerms.remove(pkg.packageName);
7296                    if (appOpPerms.isEmpty()) {
7297                        mAppOpPermissionPackages.remove(perm);
7298                    }
7299                }
7300            }
7301        }
7302        if (r != null) {
7303            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7304        }
7305
7306        N = pkg.instrumentation.size();
7307        r = null;
7308        for (i=0; i<N; i++) {
7309            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7310            mInstrumentation.remove(a.getComponentName());
7311            if (DEBUG_REMOVE && chatty) {
7312                if (r == null) {
7313                    r = new StringBuilder(256);
7314                } else {
7315                    r.append(' ');
7316                }
7317                r.append(a.info.name);
7318            }
7319        }
7320        if (r != null) {
7321            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7322        }
7323
7324        r = null;
7325        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7326            // Only system apps can hold shared libraries.
7327            if (pkg.libraryNames != null) {
7328                for (i=0; i<pkg.libraryNames.size(); i++) {
7329                    String name = pkg.libraryNames.get(i);
7330                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7331                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7332                        mSharedLibraries.remove(name);
7333                        if (DEBUG_REMOVE && chatty) {
7334                            if (r == null) {
7335                                r = new StringBuilder(256);
7336                            } else {
7337                                r.append(' ');
7338                            }
7339                            r.append(name);
7340                        }
7341                    }
7342                }
7343            }
7344        }
7345        if (r != null) {
7346            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7347        }
7348    }
7349
7350    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7351        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7352            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7353                return true;
7354            }
7355        }
7356        return false;
7357    }
7358
7359    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7360    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7361    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7362
7363    private void updatePermissionsLPw(String changingPkg,
7364            PackageParser.Package pkgInfo, int flags) {
7365        // Make sure there are no dangling permission trees.
7366        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7367        while (it.hasNext()) {
7368            final BasePermission bp = it.next();
7369            if (bp.packageSetting == null) {
7370                // We may not yet have parsed the package, so just see if
7371                // we still know about its settings.
7372                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7373            }
7374            if (bp.packageSetting == null) {
7375                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7376                        + " from package " + bp.sourcePackage);
7377                it.remove();
7378            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7379                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7380                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7381                            + " from package " + bp.sourcePackage);
7382                    flags |= UPDATE_PERMISSIONS_ALL;
7383                    it.remove();
7384                }
7385            }
7386        }
7387
7388        // Make sure all dynamic permissions have been assigned to a package,
7389        // and make sure there are no dangling permissions.
7390        it = mSettings.mPermissions.values().iterator();
7391        while (it.hasNext()) {
7392            final BasePermission bp = it.next();
7393            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7394                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7395                        + bp.name + " pkg=" + bp.sourcePackage
7396                        + " info=" + bp.pendingInfo);
7397                if (bp.packageSetting == null && bp.pendingInfo != null) {
7398                    final BasePermission tree = findPermissionTreeLP(bp.name);
7399                    if (tree != null && tree.perm != null) {
7400                        bp.packageSetting = tree.packageSetting;
7401                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7402                                new PermissionInfo(bp.pendingInfo));
7403                        bp.perm.info.packageName = tree.perm.info.packageName;
7404                        bp.perm.info.name = bp.name;
7405                        bp.uid = tree.uid;
7406                    }
7407                }
7408            }
7409            if (bp.packageSetting == null) {
7410                // We may not yet have parsed the package, so just see if
7411                // we still know about its settings.
7412                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7413            }
7414            if (bp.packageSetting == null) {
7415                Slog.w(TAG, "Removing dangling permission: " + bp.name
7416                        + " from package " + bp.sourcePackage);
7417                it.remove();
7418            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7419                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7420                    Slog.i(TAG, "Removing old permission: " + bp.name
7421                            + " from package " + bp.sourcePackage);
7422                    flags |= UPDATE_PERMISSIONS_ALL;
7423                    it.remove();
7424                }
7425            }
7426        }
7427
7428        // Now update the permissions for all packages, in particular
7429        // replace the granted permissions of the system packages.
7430        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7431            for (PackageParser.Package pkg : mPackages.values()) {
7432                if (pkg != pkgInfo) {
7433                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7434                            changingPkg);
7435                }
7436            }
7437        }
7438
7439        if (pkgInfo != null) {
7440            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7441        }
7442    }
7443
7444    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7445            String packageOfInterest) {
7446        // IMPORTANT: There are two types of permissions: install and runtime.
7447        // Install time permissions are granted when the app is installed to
7448        // all device users and users added in the future. Runtime permissions
7449        // are granted at runtime explicitly to specific users. Normal and signature
7450        // protected permissions are install time permissions. Dangerous permissions
7451        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7452        // otherwise they are runtime permissions. This function does not manage
7453        // runtime permissions except for the case an app targeting Lollipop MR1
7454        // being upgraded to target a newer SDK, in which case dangerous permissions
7455        // are transformed from install time to runtime ones.
7456
7457        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7458        if (ps == null) {
7459            return;
7460        }
7461
7462        PermissionsState permissionsState = ps.getPermissionsState();
7463        PermissionsState origPermissions = permissionsState;
7464
7465        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7466
7467        int[] upgradeUserIds = PermissionsState.USERS_NONE;
7468        int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE;
7469
7470        boolean changedInstallPermission = false;
7471
7472        if (replace) {
7473            ps.installPermissionsFixed = false;
7474            if (!ps.isSharedUser()) {
7475                origPermissions = new PermissionsState(permissionsState);
7476                permissionsState.reset();
7477            }
7478        }
7479
7480        permissionsState.setGlobalGids(mGlobalGids);
7481
7482        final int N = pkg.requestedPermissions.size();
7483        for (int i=0; i<N; i++) {
7484            final String name = pkg.requestedPermissions.get(i);
7485            final BasePermission bp = mSettings.mPermissions.get(name);
7486
7487            if (DEBUG_INSTALL) {
7488                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7489            }
7490
7491            if (bp == null || bp.packageSetting == null) {
7492                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7493                    Slog.w(TAG, "Unknown permission " + name
7494                            + " in package " + pkg.packageName);
7495                }
7496                continue;
7497            }
7498
7499            final String perm = bp.name;
7500            boolean allowedSig = false;
7501            int grant = GRANT_DENIED;
7502
7503            // Keep track of app op permissions.
7504            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7505                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7506                if (pkgs == null) {
7507                    pkgs = new ArraySet<>();
7508                    mAppOpPermissionPackages.put(bp.name, pkgs);
7509                }
7510                pkgs.add(pkg.packageName);
7511            }
7512
7513            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7514            switch (level) {
7515                case PermissionInfo.PROTECTION_NORMAL: {
7516                    // For all apps normal permissions are install time ones.
7517                    grant = GRANT_INSTALL;
7518                } break;
7519
7520                case PermissionInfo.PROTECTION_DANGEROUS: {
7521                    if (!RUNTIME_PERMISSIONS_ENABLED
7522                            || pkg.applicationInfo.targetSdkVersion
7523                                    <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7524                        // For legacy apps dangerous permissions are install time ones.
7525                        grant = GRANT_INSTALL;
7526                    } else if (ps.isSystem()) {
7527                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7528                        if (origPermissions.hasInstallPermission(bp.name)) {
7529                            // If a system app had an install permission, then the app was
7530                            // upgraded and we grant the permissions as runtime to all users.
7531                            grant = GRANT_UPGRADE;
7532                            upgradeUserIds = currentUserIds;
7533                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7534                            // If users changed since the last permissions update for a
7535                            // system app, we grant the permission as runtime to the new users.
7536                            grant = GRANT_UPGRADE;
7537                            upgradeUserIds = currentUserIds;
7538                            for (int userId : updatedUserIds) {
7539                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7540                            }
7541                        } else {
7542                            // Otherwise, we grant the permission as runtime if the app
7543                            // already had it, i.e. we preserve runtime permissions.
7544                            grant = GRANT_RUNTIME;
7545                        }
7546                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7547                        // For legacy apps that became modern, install becomes runtime.
7548                        grant = GRANT_UPGRADE;
7549                        upgradeUserIds = currentUserIds;
7550                    } else if (replace) {
7551                        // For upgraded modern apps keep runtime permissions unchanged.
7552                        grant = GRANT_RUNTIME;
7553                    }
7554                } break;
7555
7556                case PermissionInfo.PROTECTION_SIGNATURE: {
7557                    // For all apps signature permissions are install time ones.
7558                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7559                    if (allowedSig) {
7560                        grant = GRANT_INSTALL;
7561                    }
7562                } break;
7563            }
7564
7565            if (DEBUG_INSTALL) {
7566                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7567            }
7568
7569            if (grant != GRANT_DENIED) {
7570                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7571                    // If this is an existing, non-system package, then
7572                    // we can't add any new permissions to it.
7573                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7574                        // Except...  if this is a permission that was added
7575                        // to the platform (note: need to only do this when
7576                        // updating the platform).
7577                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7578                            grant = GRANT_DENIED;
7579                        }
7580                    }
7581                }
7582
7583                switch (grant) {
7584                    case GRANT_INSTALL: {
7585                        // Grant an install permission.
7586                        if (permissionsState.grantInstallPermission(bp) !=
7587                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7588                            changedInstallPermission = true;
7589                        }
7590                    } break;
7591
7592                    case GRANT_RUNTIME: {
7593                        // Grant previously granted runtime permissions.
7594                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7595                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7596                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7597                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7598                                    // If we cannot put the permission as it was, we have to write.
7599                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7600                                            changedRuntimePermissionUserIds, userId);
7601                                }
7602                            }
7603                        }
7604                    } break;
7605
7606                    case GRANT_UPGRADE: {
7607                        // Grant runtime permissions for a previously held install permission.
7608                        permissionsState.revokeInstallPermission(bp);
7609                        for (int userId : upgradeUserIds) {
7610                            if (permissionsState.grantRuntimePermission(bp, userId) !=
7611                                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
7612                                // If we granted the permission, we have to write.
7613                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7614                                        changedRuntimePermissionUserIds, userId);
7615                            }
7616                        }
7617                    } break;
7618
7619                    default: {
7620                        if (packageOfInterest == null
7621                                || packageOfInterest.equals(pkg.packageName)) {
7622                            Slog.w(TAG, "Not granting permission " + perm
7623                                    + " to package " + pkg.packageName
7624                                    + " because it was previously installed without");
7625                        }
7626                    } break;
7627                }
7628            } else {
7629                if (permissionsState.revokeInstallPermission(bp) !=
7630                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7631                    changedInstallPermission = true;
7632                    Slog.i(TAG, "Un-granting permission " + perm
7633                            + " from package " + pkg.packageName
7634                            + " (protectionLevel=" + bp.protectionLevel
7635                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7636                            + ")");
7637                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7638                    // Don't print warning for app op permissions, since it is fine for them
7639                    // not to be granted, there is a UI for the user to decide.
7640                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7641                        Slog.w(TAG, "Not granting permission " + perm
7642                                + " to package " + pkg.packageName
7643                                + " (protectionLevel=" + bp.protectionLevel
7644                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7645                                + ")");
7646                    }
7647                }
7648            }
7649        }
7650
7651        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7652                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7653            // This is the first that we have heard about this package, so the
7654            // permissions we have now selected are fixed until explicitly
7655            // changed.
7656            ps.installPermissionsFixed = true;
7657        }
7658
7659        ps.setPermissionsUpdatedForUserIds(currentUserIds);
7660
7661        // Persist the runtime permissions state for users with changes.
7662        if (RUNTIME_PERMISSIONS_ENABLED) {
7663            for (int userId : changedRuntimePermissionUserIds) {
7664                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
7665            }
7666        }
7667    }
7668
7669    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7670        boolean allowed = false;
7671        final int NP = PackageParser.NEW_PERMISSIONS.length;
7672        for (int ip=0; ip<NP; ip++) {
7673            final PackageParser.NewPermissionInfo npi
7674                    = PackageParser.NEW_PERMISSIONS[ip];
7675            if (npi.name.equals(perm)
7676                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7677                allowed = true;
7678                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7679                        + pkg.packageName);
7680                break;
7681            }
7682        }
7683        return allowed;
7684    }
7685
7686    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7687            BasePermission bp, PermissionsState origPermissions) {
7688        boolean allowed;
7689        allowed = (compareSignatures(
7690                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7691                        == PackageManager.SIGNATURE_MATCH)
7692                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7693                        == PackageManager.SIGNATURE_MATCH);
7694        if (!allowed && (bp.protectionLevel
7695                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7696            if (isSystemApp(pkg)) {
7697                // For updated system applications, a system permission
7698                // is granted only if it had been defined by the original application.
7699                if (pkg.isUpdatedSystemApp()) {
7700                    final PackageSetting sysPs = mSettings
7701                            .getDisabledSystemPkgLPr(pkg.packageName);
7702                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
7703                        // If the original was granted this permission, we take
7704                        // that grant decision as read and propagate it to the
7705                        // update.
7706                        if (sysPs.isPrivileged()) {
7707                            allowed = true;
7708                        }
7709                    } else {
7710                        // The system apk may have been updated with an older
7711                        // version of the one on the data partition, but which
7712                        // granted a new system permission that it didn't have
7713                        // before.  In this case we do want to allow the app to
7714                        // now get the new permission if the ancestral apk is
7715                        // privileged to get it.
7716                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7717                            for (int j=0;
7718                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7719                                if (perm.equals(
7720                                        sysPs.pkg.requestedPermissions.get(j))) {
7721                                    allowed = true;
7722                                    break;
7723                                }
7724                            }
7725                        }
7726                    }
7727                } else {
7728                    allowed = isPrivilegedApp(pkg);
7729                }
7730            }
7731        }
7732        if (!allowed && (bp.protectionLevel
7733                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7734            // For development permissions, a development permission
7735            // is granted only if it was already granted.
7736            allowed = origPermissions.hasInstallPermission(perm);
7737        }
7738        return allowed;
7739    }
7740
7741    final class ActivityIntentResolver
7742            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7743        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7744                boolean defaultOnly, int userId) {
7745            if (!sUserManager.exists(userId)) return null;
7746            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7747            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7748        }
7749
7750        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7751                int userId) {
7752            if (!sUserManager.exists(userId)) return null;
7753            mFlags = flags;
7754            return super.queryIntent(intent, resolvedType,
7755                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7756        }
7757
7758        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7759                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7760            if (!sUserManager.exists(userId)) return null;
7761            if (packageActivities == null) {
7762                return null;
7763            }
7764            mFlags = flags;
7765            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7766            final int N = packageActivities.size();
7767            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7768                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7769
7770            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7771            for (int i = 0; i < N; ++i) {
7772                intentFilters = packageActivities.get(i).intents;
7773                if (intentFilters != null && intentFilters.size() > 0) {
7774                    PackageParser.ActivityIntentInfo[] array =
7775                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7776                    intentFilters.toArray(array);
7777                    listCut.add(array);
7778                }
7779            }
7780            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7781        }
7782
7783        public final void addActivity(PackageParser.Activity a, String type) {
7784            final boolean systemApp = a.info.applicationInfo.isSystemApp();
7785            mActivities.put(a.getComponentName(), a);
7786            if (DEBUG_SHOW_INFO)
7787                Log.v(
7788                TAG, "  " + type + " " +
7789                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7790            if (DEBUG_SHOW_INFO)
7791                Log.v(TAG, "    Class=" + a.info.name);
7792            final int NI = a.intents.size();
7793            for (int j=0; j<NI; j++) {
7794                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7795                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7796                    intent.setPriority(0);
7797                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7798                            + a.className + " with priority > 0, forcing to 0");
7799                }
7800                if (DEBUG_SHOW_INFO) {
7801                    Log.v(TAG, "    IntentFilter:");
7802                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7803                }
7804                if (!intent.debugCheck()) {
7805                    Log.w(TAG, "==> For Activity " + a.info.name);
7806                }
7807                addFilter(intent);
7808            }
7809        }
7810
7811        public final void removeActivity(PackageParser.Activity a, String type) {
7812            mActivities.remove(a.getComponentName());
7813            if (DEBUG_SHOW_INFO) {
7814                Log.v(TAG, "  " + type + " "
7815                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7816                                : a.info.name) + ":");
7817                Log.v(TAG, "    Class=" + a.info.name);
7818            }
7819            final int NI = a.intents.size();
7820            for (int j=0; j<NI; j++) {
7821                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7822                if (DEBUG_SHOW_INFO) {
7823                    Log.v(TAG, "    IntentFilter:");
7824                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7825                }
7826                removeFilter(intent);
7827            }
7828        }
7829
7830        @Override
7831        protected boolean allowFilterResult(
7832                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7833            ActivityInfo filterAi = filter.activity.info;
7834            for (int i=dest.size()-1; i>=0; i--) {
7835                ActivityInfo destAi = dest.get(i).activityInfo;
7836                if (destAi.name == filterAi.name
7837                        && destAi.packageName == filterAi.packageName) {
7838                    return false;
7839                }
7840            }
7841            return true;
7842        }
7843
7844        @Override
7845        protected ActivityIntentInfo[] newArray(int size) {
7846            return new ActivityIntentInfo[size];
7847        }
7848
7849        @Override
7850        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7851            if (!sUserManager.exists(userId)) return true;
7852            PackageParser.Package p = filter.activity.owner;
7853            if (p != null) {
7854                PackageSetting ps = (PackageSetting)p.mExtras;
7855                if (ps != null) {
7856                    // System apps are never considered stopped for purposes of
7857                    // filtering, because there may be no way for the user to
7858                    // actually re-launch them.
7859                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7860                            && ps.getStopped(userId);
7861                }
7862            }
7863            return false;
7864        }
7865
7866        @Override
7867        protected boolean isPackageForFilter(String packageName,
7868                PackageParser.ActivityIntentInfo info) {
7869            return packageName.equals(info.activity.owner.packageName);
7870        }
7871
7872        @Override
7873        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7874                int match, int userId) {
7875            if (!sUserManager.exists(userId)) return null;
7876            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7877                return null;
7878            }
7879            final PackageParser.Activity activity = info.activity;
7880            if (mSafeMode && (activity.info.applicationInfo.flags
7881                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7882                return null;
7883            }
7884            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7885            if (ps == null) {
7886                return null;
7887            }
7888            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7889                    ps.readUserState(userId), userId);
7890            if (ai == null) {
7891                return null;
7892            }
7893            final ResolveInfo res = new ResolveInfo();
7894            res.activityInfo = ai;
7895            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7896                res.filter = info;
7897            }
7898            if (info != null) {
7899                res.handleAllWebDataURI = info.handleAllWebDataURI();
7900            }
7901            res.priority = info.getPriority();
7902            res.preferredOrder = activity.owner.mPreferredOrder;
7903            //System.out.println("Result: " + res.activityInfo.className +
7904            //                   " = " + res.priority);
7905            res.match = match;
7906            res.isDefault = info.hasDefault;
7907            res.labelRes = info.labelRes;
7908            res.nonLocalizedLabel = info.nonLocalizedLabel;
7909            if (userNeedsBadging(userId)) {
7910                res.noResourceId = true;
7911            } else {
7912                res.icon = info.icon;
7913            }
7914            res.system = res.activityInfo.applicationInfo.isSystemApp();
7915            return res;
7916        }
7917
7918        @Override
7919        protected void sortResults(List<ResolveInfo> results) {
7920            Collections.sort(results, mResolvePrioritySorter);
7921        }
7922
7923        @Override
7924        protected void dumpFilter(PrintWriter out, String prefix,
7925                PackageParser.ActivityIntentInfo filter) {
7926            out.print(prefix); out.print(
7927                    Integer.toHexString(System.identityHashCode(filter.activity)));
7928                    out.print(' ');
7929                    filter.activity.printComponentShortName(out);
7930                    out.print(" filter ");
7931                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7932        }
7933
7934        @Override
7935        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
7936            return filter.activity;
7937        }
7938
7939        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7940            PackageParser.Activity activity = (PackageParser.Activity)label;
7941            out.print(prefix); out.print(
7942                    Integer.toHexString(System.identityHashCode(activity)));
7943                    out.print(' ');
7944                    activity.printComponentShortName(out);
7945            if (count > 1) {
7946                out.print(" ("); out.print(count); out.print(" filters)");
7947            }
7948            out.println();
7949        }
7950
7951//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7952//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7953//            final List<ResolveInfo> retList = Lists.newArrayList();
7954//            while (i.hasNext()) {
7955//                final ResolveInfo resolveInfo = i.next();
7956//                if (isEnabledLP(resolveInfo.activityInfo)) {
7957//                    retList.add(resolveInfo);
7958//                }
7959//            }
7960//            return retList;
7961//        }
7962
7963        // Keys are String (activity class name), values are Activity.
7964        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
7965                = new ArrayMap<ComponentName, PackageParser.Activity>();
7966        private int mFlags;
7967    }
7968
7969    private final class ServiceIntentResolver
7970            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7971        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7972                boolean defaultOnly, int userId) {
7973            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7974            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7975        }
7976
7977        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7978                int userId) {
7979            if (!sUserManager.exists(userId)) return null;
7980            mFlags = flags;
7981            return super.queryIntent(intent, resolvedType,
7982                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7983        }
7984
7985        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7986                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7987            if (!sUserManager.exists(userId)) return null;
7988            if (packageServices == null) {
7989                return null;
7990            }
7991            mFlags = flags;
7992            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7993            final int N = packageServices.size();
7994            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7995                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7996
7997            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7998            for (int i = 0; i < N; ++i) {
7999                intentFilters = packageServices.get(i).intents;
8000                if (intentFilters != null && intentFilters.size() > 0) {
8001                    PackageParser.ServiceIntentInfo[] array =
8002                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8003                    intentFilters.toArray(array);
8004                    listCut.add(array);
8005                }
8006            }
8007            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8008        }
8009
8010        public final void addService(PackageParser.Service s) {
8011            mServices.put(s.getComponentName(), s);
8012            if (DEBUG_SHOW_INFO) {
8013                Log.v(TAG, "  "
8014                        + (s.info.nonLocalizedLabel != null
8015                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8016                Log.v(TAG, "    Class=" + s.info.name);
8017            }
8018            final int NI = s.intents.size();
8019            int j;
8020            for (j=0; j<NI; j++) {
8021                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8022                if (DEBUG_SHOW_INFO) {
8023                    Log.v(TAG, "    IntentFilter:");
8024                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8025                }
8026                if (!intent.debugCheck()) {
8027                    Log.w(TAG, "==> For Service " + s.info.name);
8028                }
8029                addFilter(intent);
8030            }
8031        }
8032
8033        public final void removeService(PackageParser.Service s) {
8034            mServices.remove(s.getComponentName());
8035            if (DEBUG_SHOW_INFO) {
8036                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8037                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8038                Log.v(TAG, "    Class=" + s.info.name);
8039            }
8040            final int NI = s.intents.size();
8041            int j;
8042            for (j=0; j<NI; j++) {
8043                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8044                if (DEBUG_SHOW_INFO) {
8045                    Log.v(TAG, "    IntentFilter:");
8046                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8047                }
8048                removeFilter(intent);
8049            }
8050        }
8051
8052        @Override
8053        protected boolean allowFilterResult(
8054                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8055            ServiceInfo filterSi = filter.service.info;
8056            for (int i=dest.size()-1; i>=0; i--) {
8057                ServiceInfo destAi = dest.get(i).serviceInfo;
8058                if (destAi.name == filterSi.name
8059                        && destAi.packageName == filterSi.packageName) {
8060                    return false;
8061                }
8062            }
8063            return true;
8064        }
8065
8066        @Override
8067        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8068            return new PackageParser.ServiceIntentInfo[size];
8069        }
8070
8071        @Override
8072        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8073            if (!sUserManager.exists(userId)) return true;
8074            PackageParser.Package p = filter.service.owner;
8075            if (p != null) {
8076                PackageSetting ps = (PackageSetting)p.mExtras;
8077                if (ps != null) {
8078                    // System apps are never considered stopped for purposes of
8079                    // filtering, because there may be no way for the user to
8080                    // actually re-launch them.
8081                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8082                            && ps.getStopped(userId);
8083                }
8084            }
8085            return false;
8086        }
8087
8088        @Override
8089        protected boolean isPackageForFilter(String packageName,
8090                PackageParser.ServiceIntentInfo info) {
8091            return packageName.equals(info.service.owner.packageName);
8092        }
8093
8094        @Override
8095        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8096                int match, int userId) {
8097            if (!sUserManager.exists(userId)) return null;
8098            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8099            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8100                return null;
8101            }
8102            final PackageParser.Service service = info.service;
8103            if (mSafeMode && (service.info.applicationInfo.flags
8104                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8105                return null;
8106            }
8107            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8108            if (ps == null) {
8109                return null;
8110            }
8111            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8112                    ps.readUserState(userId), userId);
8113            if (si == null) {
8114                return null;
8115            }
8116            final ResolveInfo res = new ResolveInfo();
8117            res.serviceInfo = si;
8118            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8119                res.filter = filter;
8120            }
8121            res.priority = info.getPriority();
8122            res.preferredOrder = service.owner.mPreferredOrder;
8123            res.match = match;
8124            res.isDefault = info.hasDefault;
8125            res.labelRes = info.labelRes;
8126            res.nonLocalizedLabel = info.nonLocalizedLabel;
8127            res.icon = info.icon;
8128            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8129            return res;
8130        }
8131
8132        @Override
8133        protected void sortResults(List<ResolveInfo> results) {
8134            Collections.sort(results, mResolvePrioritySorter);
8135        }
8136
8137        @Override
8138        protected void dumpFilter(PrintWriter out, String prefix,
8139                PackageParser.ServiceIntentInfo filter) {
8140            out.print(prefix); out.print(
8141                    Integer.toHexString(System.identityHashCode(filter.service)));
8142                    out.print(' ');
8143                    filter.service.printComponentShortName(out);
8144                    out.print(" filter ");
8145                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8146        }
8147
8148        @Override
8149        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8150            return filter.service;
8151        }
8152
8153        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8154            PackageParser.Service service = (PackageParser.Service)label;
8155            out.print(prefix); out.print(
8156                    Integer.toHexString(System.identityHashCode(service)));
8157                    out.print(' ');
8158                    service.printComponentShortName(out);
8159            if (count > 1) {
8160                out.print(" ("); out.print(count); out.print(" filters)");
8161            }
8162            out.println();
8163        }
8164
8165//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8166//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8167//            final List<ResolveInfo> retList = Lists.newArrayList();
8168//            while (i.hasNext()) {
8169//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8170//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8171//                    retList.add(resolveInfo);
8172//                }
8173//            }
8174//            return retList;
8175//        }
8176
8177        // Keys are String (activity class name), values are Activity.
8178        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8179                = new ArrayMap<ComponentName, PackageParser.Service>();
8180        private int mFlags;
8181    };
8182
8183    private final class ProviderIntentResolver
8184            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8185        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8186                boolean defaultOnly, int userId) {
8187            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8188            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8189        }
8190
8191        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8192                int userId) {
8193            if (!sUserManager.exists(userId))
8194                return null;
8195            mFlags = flags;
8196            return super.queryIntent(intent, resolvedType,
8197                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8198        }
8199
8200        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8201                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8202            if (!sUserManager.exists(userId))
8203                return null;
8204            if (packageProviders == null) {
8205                return null;
8206            }
8207            mFlags = flags;
8208            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8209            final int N = packageProviders.size();
8210            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8211                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8212
8213            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8214            for (int i = 0; i < N; ++i) {
8215                intentFilters = packageProviders.get(i).intents;
8216                if (intentFilters != null && intentFilters.size() > 0) {
8217                    PackageParser.ProviderIntentInfo[] array =
8218                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8219                    intentFilters.toArray(array);
8220                    listCut.add(array);
8221                }
8222            }
8223            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8224        }
8225
8226        public final void addProvider(PackageParser.Provider p) {
8227            if (mProviders.containsKey(p.getComponentName())) {
8228                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8229                return;
8230            }
8231
8232            mProviders.put(p.getComponentName(), p);
8233            if (DEBUG_SHOW_INFO) {
8234                Log.v(TAG, "  "
8235                        + (p.info.nonLocalizedLabel != null
8236                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8237                Log.v(TAG, "    Class=" + p.info.name);
8238            }
8239            final int NI = p.intents.size();
8240            int j;
8241            for (j = 0; j < NI; j++) {
8242                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8243                if (DEBUG_SHOW_INFO) {
8244                    Log.v(TAG, "    IntentFilter:");
8245                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8246                }
8247                if (!intent.debugCheck()) {
8248                    Log.w(TAG, "==> For Provider " + p.info.name);
8249                }
8250                addFilter(intent);
8251            }
8252        }
8253
8254        public final void removeProvider(PackageParser.Provider p) {
8255            mProviders.remove(p.getComponentName());
8256            if (DEBUG_SHOW_INFO) {
8257                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8258                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8259                Log.v(TAG, "    Class=" + p.info.name);
8260            }
8261            final int NI = p.intents.size();
8262            int j;
8263            for (j = 0; j < NI; j++) {
8264                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8265                if (DEBUG_SHOW_INFO) {
8266                    Log.v(TAG, "    IntentFilter:");
8267                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8268                }
8269                removeFilter(intent);
8270            }
8271        }
8272
8273        @Override
8274        protected boolean allowFilterResult(
8275                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8276            ProviderInfo filterPi = filter.provider.info;
8277            for (int i = dest.size() - 1; i >= 0; i--) {
8278                ProviderInfo destPi = dest.get(i).providerInfo;
8279                if (destPi.name == filterPi.name
8280                        && destPi.packageName == filterPi.packageName) {
8281                    return false;
8282                }
8283            }
8284            return true;
8285        }
8286
8287        @Override
8288        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8289            return new PackageParser.ProviderIntentInfo[size];
8290        }
8291
8292        @Override
8293        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8294            if (!sUserManager.exists(userId))
8295                return true;
8296            PackageParser.Package p = filter.provider.owner;
8297            if (p != null) {
8298                PackageSetting ps = (PackageSetting) p.mExtras;
8299                if (ps != null) {
8300                    // System apps are never considered stopped for purposes of
8301                    // filtering, because there may be no way for the user to
8302                    // actually re-launch them.
8303                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8304                            && ps.getStopped(userId);
8305                }
8306            }
8307            return false;
8308        }
8309
8310        @Override
8311        protected boolean isPackageForFilter(String packageName,
8312                PackageParser.ProviderIntentInfo info) {
8313            return packageName.equals(info.provider.owner.packageName);
8314        }
8315
8316        @Override
8317        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8318                int match, int userId) {
8319            if (!sUserManager.exists(userId))
8320                return null;
8321            final PackageParser.ProviderIntentInfo info = filter;
8322            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8323                return null;
8324            }
8325            final PackageParser.Provider provider = info.provider;
8326            if (mSafeMode && (provider.info.applicationInfo.flags
8327                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8328                return null;
8329            }
8330            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8331            if (ps == null) {
8332                return null;
8333            }
8334            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8335                    ps.readUserState(userId), userId);
8336            if (pi == null) {
8337                return null;
8338            }
8339            final ResolveInfo res = new ResolveInfo();
8340            res.providerInfo = pi;
8341            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8342                res.filter = filter;
8343            }
8344            res.priority = info.getPriority();
8345            res.preferredOrder = provider.owner.mPreferredOrder;
8346            res.match = match;
8347            res.isDefault = info.hasDefault;
8348            res.labelRes = info.labelRes;
8349            res.nonLocalizedLabel = info.nonLocalizedLabel;
8350            res.icon = info.icon;
8351            res.system = res.providerInfo.applicationInfo.isSystemApp();
8352            return res;
8353        }
8354
8355        @Override
8356        protected void sortResults(List<ResolveInfo> results) {
8357            Collections.sort(results, mResolvePrioritySorter);
8358        }
8359
8360        @Override
8361        protected void dumpFilter(PrintWriter out, String prefix,
8362                PackageParser.ProviderIntentInfo filter) {
8363            out.print(prefix);
8364            out.print(
8365                    Integer.toHexString(System.identityHashCode(filter.provider)));
8366            out.print(' ');
8367            filter.provider.printComponentShortName(out);
8368            out.print(" filter ");
8369            out.println(Integer.toHexString(System.identityHashCode(filter)));
8370        }
8371
8372        @Override
8373        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8374            return filter.provider;
8375        }
8376
8377        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8378            PackageParser.Provider provider = (PackageParser.Provider)label;
8379            out.print(prefix); out.print(
8380                    Integer.toHexString(System.identityHashCode(provider)));
8381                    out.print(' ');
8382                    provider.printComponentShortName(out);
8383            if (count > 1) {
8384                out.print(" ("); out.print(count); out.print(" filters)");
8385            }
8386            out.println();
8387        }
8388
8389        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8390                = new ArrayMap<ComponentName, PackageParser.Provider>();
8391        private int mFlags;
8392    };
8393
8394    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8395            new Comparator<ResolveInfo>() {
8396        public int compare(ResolveInfo r1, ResolveInfo r2) {
8397            int v1 = r1.priority;
8398            int v2 = r2.priority;
8399            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8400            if (v1 != v2) {
8401                return (v1 > v2) ? -1 : 1;
8402            }
8403            v1 = r1.preferredOrder;
8404            v2 = r2.preferredOrder;
8405            if (v1 != v2) {
8406                return (v1 > v2) ? -1 : 1;
8407            }
8408            if (r1.isDefault != r2.isDefault) {
8409                return r1.isDefault ? -1 : 1;
8410            }
8411            v1 = r1.match;
8412            v2 = r2.match;
8413            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8414            if (v1 != v2) {
8415                return (v1 > v2) ? -1 : 1;
8416            }
8417            if (r1.system != r2.system) {
8418                return r1.system ? -1 : 1;
8419            }
8420            return 0;
8421        }
8422    };
8423
8424    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8425            new Comparator<ProviderInfo>() {
8426        public int compare(ProviderInfo p1, ProviderInfo p2) {
8427            final int v1 = p1.initOrder;
8428            final int v2 = p2.initOrder;
8429            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8430        }
8431    };
8432
8433    static final void sendPackageBroadcast(String action, String pkg,
8434            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
8435            int[] userIds) {
8436        IActivityManager am = ActivityManagerNative.getDefault();
8437        if (am != null) {
8438            try {
8439                if (userIds == null) {
8440                    userIds = am.getRunningUserIds();
8441                }
8442                for (int id : userIds) {
8443                    final Intent intent = new Intent(action,
8444                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
8445                    if (extras != null) {
8446                        intent.putExtras(extras);
8447                    }
8448                    if (targetPkg != null) {
8449                        intent.setPackage(targetPkg);
8450                    }
8451                    // Modify the UID when posting to other users
8452                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8453                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
8454                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8455                        intent.putExtra(Intent.EXTRA_UID, uid);
8456                    }
8457                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8458                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8459                    if (DEBUG_BROADCASTS) {
8460                        RuntimeException here = new RuntimeException("here");
8461                        here.fillInStackTrace();
8462                        Slog.d(TAG, "Sending to user " + id + ": "
8463                                + intent.toShortString(false, true, false, false)
8464                                + " " + intent.getExtras(), here);
8465                    }
8466                    am.broadcastIntent(null, intent, null, finishedReceiver,
8467                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
8468                            finishedReceiver != null, false, id);
8469                }
8470            } catch (RemoteException ex) {
8471            }
8472        }
8473    }
8474
8475    /**
8476     * Check if the external storage media is available. This is true if there
8477     * is a mounted external storage medium or if the external storage is
8478     * emulated.
8479     */
8480    private boolean isExternalMediaAvailable() {
8481        return mMediaMounted || Environment.isExternalStorageEmulated();
8482    }
8483
8484    @Override
8485    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8486        // writer
8487        synchronized (mPackages) {
8488            if (!isExternalMediaAvailable()) {
8489                // If the external storage is no longer mounted at this point,
8490                // the caller may not have been able to delete all of this
8491                // packages files and can not delete any more.  Bail.
8492                return null;
8493            }
8494            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8495            if (lastPackage != null) {
8496                pkgs.remove(lastPackage);
8497            }
8498            if (pkgs.size() > 0) {
8499                return pkgs.get(0);
8500            }
8501        }
8502        return null;
8503    }
8504
8505    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8506        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8507                userId, andCode ? 1 : 0, packageName);
8508        if (mSystemReady) {
8509            msg.sendToTarget();
8510        } else {
8511            if (mPostSystemReadyMessages == null) {
8512                mPostSystemReadyMessages = new ArrayList<>();
8513            }
8514            mPostSystemReadyMessages.add(msg);
8515        }
8516    }
8517
8518    void startCleaningPackages() {
8519        // reader
8520        synchronized (mPackages) {
8521            if (!isExternalMediaAvailable()) {
8522                return;
8523            }
8524            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8525                return;
8526            }
8527        }
8528        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8529        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8530        IActivityManager am = ActivityManagerNative.getDefault();
8531        if (am != null) {
8532            try {
8533                am.startService(null, intent, null, UserHandle.USER_OWNER);
8534            } catch (RemoteException e) {
8535            }
8536        }
8537    }
8538
8539    @Override
8540    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8541            int installFlags, String installerPackageName, VerificationParams verificationParams,
8542            String packageAbiOverride) {
8543        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8544                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8545    }
8546
8547    @Override
8548    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8549            int installFlags, String installerPackageName, VerificationParams verificationParams,
8550            String packageAbiOverride, int userId) {
8551        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8552
8553        final int callingUid = Binder.getCallingUid();
8554        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8555
8556        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8557            try {
8558                if (observer != null) {
8559                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8560                }
8561            } catch (RemoteException re) {
8562            }
8563            return;
8564        }
8565
8566        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8567            installFlags |= PackageManager.INSTALL_FROM_ADB;
8568
8569        } else {
8570            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8571            // about installerPackageName.
8572
8573            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8574            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8575        }
8576
8577        UserHandle user;
8578        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8579            user = UserHandle.ALL;
8580        } else {
8581            user = new UserHandle(userId);
8582        }
8583
8584        // Only system components can circumvent runtime permissions when installing.
8585        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
8586                && mContext.checkCallingOrSelfPermission(Manifest.permission
8587                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
8588            throw new SecurityException("You need the "
8589                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
8590                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
8591        }
8592
8593        verificationParams.setInstallerUid(callingUid);
8594
8595        final File originFile = new File(originPath);
8596        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8597
8598        final Message msg = mHandler.obtainMessage(INIT_COPY);
8599        msg.obj = new InstallParams(origin, observer, installFlags,
8600                installerPackageName, null, verificationParams, user, packageAbiOverride);
8601        mHandler.sendMessage(msg);
8602    }
8603
8604    void installStage(String packageName, File stagedDir, String stagedCid,
8605            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8606            String installerPackageName, int installerUid, UserHandle user) {
8607        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8608                params.referrerUri, installerUid, null);
8609
8610        final OriginInfo origin;
8611        if (stagedDir != null) {
8612            origin = OriginInfo.fromStagedFile(stagedDir);
8613        } else {
8614            origin = OriginInfo.fromStagedContainer(stagedCid);
8615        }
8616
8617        final Message msg = mHandler.obtainMessage(INIT_COPY);
8618        msg.obj = new InstallParams(origin, observer, params.installFlags,
8619                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8620        mHandler.sendMessage(msg);
8621    }
8622
8623    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8624        Bundle extras = new Bundle(1);
8625        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8626
8627        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8628                packageName, extras, null, null, new int[] {userId});
8629        try {
8630            IActivityManager am = ActivityManagerNative.getDefault();
8631            final boolean isSystem =
8632                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8633            if (isSystem && am.isUserRunning(userId, false)) {
8634                // The just-installed/enabled app is bundled on the system, so presumed
8635                // to be able to run automatically without needing an explicit launch.
8636                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8637                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8638                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8639                        .setPackage(packageName);
8640                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8641                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8642            }
8643        } catch (RemoteException e) {
8644            // shouldn't happen
8645            Slog.w(TAG, "Unable to bootstrap installed package", e);
8646        }
8647    }
8648
8649    @Override
8650    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8651            int userId) {
8652        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8653        PackageSetting pkgSetting;
8654        final int uid = Binder.getCallingUid();
8655        enforceCrossUserPermission(uid, userId, true, true,
8656                "setApplicationHiddenSetting for user " + userId);
8657
8658        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8659            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8660            return false;
8661        }
8662
8663        long callingId = Binder.clearCallingIdentity();
8664        try {
8665            boolean sendAdded = false;
8666            boolean sendRemoved = false;
8667            // writer
8668            synchronized (mPackages) {
8669                pkgSetting = mSettings.mPackages.get(packageName);
8670                if (pkgSetting == null) {
8671                    return false;
8672                }
8673                if (pkgSetting.getHidden(userId) != hidden) {
8674                    pkgSetting.setHidden(hidden, userId);
8675                    mSettings.writePackageRestrictionsLPr(userId);
8676                    if (hidden) {
8677                        sendRemoved = true;
8678                    } else {
8679                        sendAdded = true;
8680                    }
8681                }
8682            }
8683            if (sendAdded) {
8684                sendPackageAddedForUser(packageName, pkgSetting, userId);
8685                return true;
8686            }
8687            if (sendRemoved) {
8688                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8689                        "hiding pkg");
8690                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8691            }
8692        } finally {
8693            Binder.restoreCallingIdentity(callingId);
8694        }
8695        return false;
8696    }
8697
8698    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8699            int userId) {
8700        final PackageRemovedInfo info = new PackageRemovedInfo();
8701        info.removedPackage = packageName;
8702        info.removedUsers = new int[] {userId};
8703        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8704        info.sendBroadcast(false, false, false);
8705    }
8706
8707    /**
8708     * Returns true if application is not found or there was an error. Otherwise it returns
8709     * the hidden state of the package for the given user.
8710     */
8711    @Override
8712    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8713        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8714        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8715                false, "getApplicationHidden for user " + userId);
8716        PackageSetting pkgSetting;
8717        long callingId = Binder.clearCallingIdentity();
8718        try {
8719            // writer
8720            synchronized (mPackages) {
8721                pkgSetting = mSettings.mPackages.get(packageName);
8722                if (pkgSetting == null) {
8723                    return true;
8724                }
8725                return pkgSetting.getHidden(userId);
8726            }
8727        } finally {
8728            Binder.restoreCallingIdentity(callingId);
8729        }
8730    }
8731
8732    /**
8733     * @hide
8734     */
8735    @Override
8736    public int installExistingPackageAsUser(String packageName, int userId) {
8737        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8738                null);
8739        PackageSetting pkgSetting;
8740        final int uid = Binder.getCallingUid();
8741        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8742                + userId);
8743        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8744            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8745        }
8746
8747        long callingId = Binder.clearCallingIdentity();
8748        try {
8749            boolean sendAdded = false;
8750
8751            // writer
8752            synchronized (mPackages) {
8753                pkgSetting = mSettings.mPackages.get(packageName);
8754                if (pkgSetting == null) {
8755                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8756                }
8757                if (!pkgSetting.getInstalled(userId)) {
8758                    pkgSetting.setInstalled(true, userId);
8759                    pkgSetting.setHidden(false, userId);
8760                    mSettings.writePackageRestrictionsLPr(userId);
8761                    sendAdded = true;
8762                }
8763            }
8764
8765            if (sendAdded) {
8766                sendPackageAddedForUser(packageName, pkgSetting, userId);
8767            }
8768        } finally {
8769            Binder.restoreCallingIdentity(callingId);
8770        }
8771
8772        return PackageManager.INSTALL_SUCCEEDED;
8773    }
8774
8775    boolean isUserRestricted(int userId, String restrictionKey) {
8776        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8777        if (restrictions.getBoolean(restrictionKey, false)) {
8778            Log.w(TAG, "User is restricted: " + restrictionKey);
8779            return true;
8780        }
8781        return false;
8782    }
8783
8784    @Override
8785    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8786        mContext.enforceCallingOrSelfPermission(
8787                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8788                "Only package verification agents can verify applications");
8789
8790        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8791        final PackageVerificationResponse response = new PackageVerificationResponse(
8792                verificationCode, Binder.getCallingUid());
8793        msg.arg1 = id;
8794        msg.obj = response;
8795        mHandler.sendMessage(msg);
8796    }
8797
8798    @Override
8799    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8800            long millisecondsToDelay) {
8801        mContext.enforceCallingOrSelfPermission(
8802                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8803                "Only package verification agents can extend verification timeouts");
8804
8805        final PackageVerificationState state = mPendingVerification.get(id);
8806        final PackageVerificationResponse response = new PackageVerificationResponse(
8807                verificationCodeAtTimeout, Binder.getCallingUid());
8808
8809        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8810            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8811        }
8812        if (millisecondsToDelay < 0) {
8813            millisecondsToDelay = 0;
8814        }
8815        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8816                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8817            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8818        }
8819
8820        if ((state != null) && !state.timeoutExtended()) {
8821            state.extendTimeout();
8822
8823            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8824            msg.arg1 = id;
8825            msg.obj = response;
8826            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8827        }
8828    }
8829
8830    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8831            int verificationCode, UserHandle user) {
8832        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8833        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8834        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8835        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8836        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8837
8838        mContext.sendBroadcastAsUser(intent, user,
8839                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8840    }
8841
8842    private ComponentName matchComponentForVerifier(String packageName,
8843            List<ResolveInfo> receivers) {
8844        ActivityInfo targetReceiver = null;
8845
8846        final int NR = receivers.size();
8847        for (int i = 0; i < NR; i++) {
8848            final ResolveInfo info = receivers.get(i);
8849            if (info.activityInfo == null) {
8850                continue;
8851            }
8852
8853            if (packageName.equals(info.activityInfo.packageName)) {
8854                targetReceiver = info.activityInfo;
8855                break;
8856            }
8857        }
8858
8859        if (targetReceiver == null) {
8860            return null;
8861        }
8862
8863        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8864    }
8865
8866    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8867            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8868        if (pkgInfo.verifiers.length == 0) {
8869            return null;
8870        }
8871
8872        final int N = pkgInfo.verifiers.length;
8873        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8874        for (int i = 0; i < N; i++) {
8875            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8876
8877            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8878                    receivers);
8879            if (comp == null) {
8880                continue;
8881            }
8882
8883            final int verifierUid = getUidForVerifier(verifierInfo);
8884            if (verifierUid == -1) {
8885                continue;
8886            }
8887
8888            if (DEBUG_VERIFY) {
8889                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8890                        + " with the correct signature");
8891            }
8892            sufficientVerifiers.add(comp);
8893            verificationState.addSufficientVerifier(verifierUid);
8894        }
8895
8896        return sufficientVerifiers;
8897    }
8898
8899    private int getUidForVerifier(VerifierInfo verifierInfo) {
8900        synchronized (mPackages) {
8901            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8902            if (pkg == null) {
8903                return -1;
8904            } else if (pkg.mSignatures.length != 1) {
8905                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8906                        + " has more than one signature; ignoring");
8907                return -1;
8908            }
8909
8910            /*
8911             * If the public key of the package's signature does not match
8912             * our expected public key, then this is a different package and
8913             * we should skip.
8914             */
8915
8916            final byte[] expectedPublicKey;
8917            try {
8918                final Signature verifierSig = pkg.mSignatures[0];
8919                final PublicKey publicKey = verifierSig.getPublicKey();
8920                expectedPublicKey = publicKey.getEncoded();
8921            } catch (CertificateException e) {
8922                return -1;
8923            }
8924
8925            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8926
8927            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8928                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8929                        + " does not have the expected public key; ignoring");
8930                return -1;
8931            }
8932
8933            return pkg.applicationInfo.uid;
8934        }
8935    }
8936
8937    @Override
8938    public void finishPackageInstall(int token) {
8939        enforceSystemOrRoot("Only the system is allowed to finish installs");
8940
8941        if (DEBUG_INSTALL) {
8942            Slog.v(TAG, "BM finishing package install for " + token);
8943        }
8944
8945        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8946        mHandler.sendMessage(msg);
8947    }
8948
8949    /**
8950     * Get the verification agent timeout.
8951     *
8952     * @return verification timeout in milliseconds
8953     */
8954    private long getVerificationTimeout() {
8955        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8956                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8957                DEFAULT_VERIFICATION_TIMEOUT);
8958    }
8959
8960    /**
8961     * Get the default verification agent response code.
8962     *
8963     * @return default verification response code
8964     */
8965    private int getDefaultVerificationResponse() {
8966        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8967                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8968                DEFAULT_VERIFICATION_RESPONSE);
8969    }
8970
8971    /**
8972     * Check whether or not package verification has been enabled.
8973     *
8974     * @return true if verification should be performed
8975     */
8976    private boolean isVerificationEnabled(int userId, int installFlags) {
8977        if (!DEFAULT_VERIFY_ENABLE) {
8978            return false;
8979        }
8980
8981        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8982
8983        // Check if installing from ADB
8984        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8985            // Do not run verification in a test harness environment
8986            if (ActivityManager.isRunningInTestHarness()) {
8987                return false;
8988            }
8989            if (ensureVerifyAppsEnabled) {
8990                return true;
8991            }
8992            // Check if the developer does not want package verification for ADB installs
8993            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8994                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8995                return false;
8996            }
8997        }
8998
8999        if (ensureVerifyAppsEnabled) {
9000            return true;
9001        }
9002
9003        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9004                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9005    }
9006
9007    @Override
9008    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9009            throws RemoteException {
9010        mContext.enforceCallingOrSelfPermission(
9011                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9012                "Only intentfilter verification agents can verify applications");
9013
9014        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9015        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9016                Binder.getCallingUid(), verificationCode, failedDomains);
9017        msg.arg1 = id;
9018        msg.obj = response;
9019        mHandler.sendMessage(msg);
9020    }
9021
9022    @Override
9023    public int getIntentVerificationStatus(String packageName, int userId) {
9024        synchronized (mPackages) {
9025            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9026        }
9027    }
9028
9029    @Override
9030    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9031        boolean result = false;
9032        synchronized (mPackages) {
9033            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9034        }
9035        scheduleWritePackageRestrictionsLocked(userId);
9036        return result;
9037    }
9038
9039    @Override
9040    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9041        synchronized (mPackages) {
9042            return mSettings.getIntentFilterVerificationsLPr(packageName);
9043        }
9044    }
9045
9046    @Override
9047    public List<IntentFilter> getAllIntentFilters(String packageName) {
9048        if (TextUtils.isEmpty(packageName)) {
9049            return Collections.<IntentFilter>emptyList();
9050        }
9051        synchronized (mPackages) {
9052            PackageParser.Package pkg = mPackages.get(packageName);
9053            if (pkg == null || pkg.activities == null) {
9054                return Collections.<IntentFilter>emptyList();
9055            }
9056            final int count = pkg.activities.size();
9057            ArrayList<IntentFilter> result = new ArrayList<>();
9058            for (int n=0; n<count; n++) {
9059                PackageParser.Activity activity = pkg.activities.get(n);
9060                if (activity.intents != null || activity.intents.size() > 0) {
9061                    result.addAll(activity.intents);
9062                }
9063            }
9064            return result;
9065        }
9066    }
9067
9068    @Override
9069    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9070        synchronized (mPackages) {
9071            return mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9072        }
9073    }
9074
9075    @Override
9076    public String getDefaultBrowserPackageName(int userId) {
9077        synchronized (mPackages) {
9078            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9079        }
9080    }
9081
9082    /**
9083     * Get the "allow unknown sources" setting.
9084     *
9085     * @return the current "allow unknown sources" setting
9086     */
9087    private int getUnknownSourcesSettings() {
9088        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9089                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9090                -1);
9091    }
9092
9093    @Override
9094    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9095        final int uid = Binder.getCallingUid();
9096        // writer
9097        synchronized (mPackages) {
9098            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9099            if (targetPackageSetting == null) {
9100                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9101            }
9102
9103            PackageSetting installerPackageSetting;
9104            if (installerPackageName != null) {
9105                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9106                if (installerPackageSetting == null) {
9107                    throw new IllegalArgumentException("Unknown installer package: "
9108                            + installerPackageName);
9109                }
9110            } else {
9111                installerPackageSetting = null;
9112            }
9113
9114            Signature[] callerSignature;
9115            Object obj = mSettings.getUserIdLPr(uid);
9116            if (obj != null) {
9117                if (obj instanceof SharedUserSetting) {
9118                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9119                } else if (obj instanceof PackageSetting) {
9120                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9121                } else {
9122                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9123                }
9124            } else {
9125                throw new SecurityException("Unknown calling uid " + uid);
9126            }
9127
9128            // Verify: can't set installerPackageName to a package that is
9129            // not signed with the same cert as the caller.
9130            if (installerPackageSetting != null) {
9131                if (compareSignatures(callerSignature,
9132                        installerPackageSetting.signatures.mSignatures)
9133                        != PackageManager.SIGNATURE_MATCH) {
9134                    throw new SecurityException(
9135                            "Caller does not have same cert as new installer package "
9136                            + installerPackageName);
9137                }
9138            }
9139
9140            // Verify: if target already has an installer package, it must
9141            // be signed with the same cert as the caller.
9142            if (targetPackageSetting.installerPackageName != null) {
9143                PackageSetting setting = mSettings.mPackages.get(
9144                        targetPackageSetting.installerPackageName);
9145                // If the currently set package isn't valid, then it's always
9146                // okay to change it.
9147                if (setting != null) {
9148                    if (compareSignatures(callerSignature,
9149                            setting.signatures.mSignatures)
9150                            != PackageManager.SIGNATURE_MATCH) {
9151                        throw new SecurityException(
9152                                "Caller does not have same cert as old installer package "
9153                                + targetPackageSetting.installerPackageName);
9154                    }
9155                }
9156            }
9157
9158            // Okay!
9159            targetPackageSetting.installerPackageName = installerPackageName;
9160            scheduleWriteSettingsLocked();
9161        }
9162    }
9163
9164    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9165        // Queue up an async operation since the package installation may take a little while.
9166        mHandler.post(new Runnable() {
9167            public void run() {
9168                mHandler.removeCallbacks(this);
9169                 // Result object to be returned
9170                PackageInstalledInfo res = new PackageInstalledInfo();
9171                res.returnCode = currentStatus;
9172                res.uid = -1;
9173                res.pkg = null;
9174                res.removedInfo = new PackageRemovedInfo();
9175                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9176                    args.doPreInstall(res.returnCode);
9177                    synchronized (mInstallLock) {
9178                        installPackageLI(args, res);
9179                    }
9180                    args.doPostInstall(res.returnCode, res.uid);
9181                }
9182
9183                // A restore should be performed at this point if (a) the install
9184                // succeeded, (b) the operation is not an update, and (c) the new
9185                // package has not opted out of backup participation.
9186                final boolean update = res.removedInfo.removedPackage != null;
9187                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9188                boolean doRestore = !update
9189                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9190
9191                // Set up the post-install work request bookkeeping.  This will be used
9192                // and cleaned up by the post-install event handling regardless of whether
9193                // there's a restore pass performed.  Token values are >= 1.
9194                int token;
9195                if (mNextInstallToken < 0) mNextInstallToken = 1;
9196                token = mNextInstallToken++;
9197
9198                PostInstallData data = new PostInstallData(args, res);
9199                mRunningInstalls.put(token, data);
9200                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9201
9202                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9203                    // Pass responsibility to the Backup Manager.  It will perform a
9204                    // restore if appropriate, then pass responsibility back to the
9205                    // Package Manager to run the post-install observer callbacks
9206                    // and broadcasts.
9207                    IBackupManager bm = IBackupManager.Stub.asInterface(
9208                            ServiceManager.getService(Context.BACKUP_SERVICE));
9209                    if (bm != null) {
9210                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9211                                + " to BM for possible restore");
9212                        try {
9213                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9214                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9215                            } else {
9216                                doRestore = false;
9217                            }
9218                        } catch (RemoteException e) {
9219                            // can't happen; the backup manager is local
9220                        } catch (Exception e) {
9221                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9222                            doRestore = false;
9223                        }
9224                    } else {
9225                        Slog.e(TAG, "Backup Manager not found!");
9226                        doRestore = false;
9227                    }
9228                }
9229
9230                if (!doRestore) {
9231                    // No restore possible, or the Backup Manager was mysteriously not
9232                    // available -- just fire the post-install work request directly.
9233                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9234                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9235                    mHandler.sendMessage(msg);
9236                }
9237            }
9238        });
9239    }
9240
9241    private abstract class HandlerParams {
9242        private static final int MAX_RETRIES = 4;
9243
9244        /**
9245         * Number of times startCopy() has been attempted and had a non-fatal
9246         * error.
9247         */
9248        private int mRetries = 0;
9249
9250        /** User handle for the user requesting the information or installation. */
9251        private final UserHandle mUser;
9252
9253        HandlerParams(UserHandle user) {
9254            mUser = user;
9255        }
9256
9257        UserHandle getUser() {
9258            return mUser;
9259        }
9260
9261        final boolean startCopy() {
9262            boolean res;
9263            try {
9264                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9265
9266                if (++mRetries > MAX_RETRIES) {
9267                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9268                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9269                    handleServiceError();
9270                    return false;
9271                } else {
9272                    handleStartCopy();
9273                    res = true;
9274                }
9275            } catch (RemoteException e) {
9276                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9277                mHandler.sendEmptyMessage(MCS_RECONNECT);
9278                res = false;
9279            }
9280            handleReturnCode();
9281            return res;
9282        }
9283
9284        final void serviceError() {
9285            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9286            handleServiceError();
9287            handleReturnCode();
9288        }
9289
9290        abstract void handleStartCopy() throws RemoteException;
9291        abstract void handleServiceError();
9292        abstract void handleReturnCode();
9293    }
9294
9295    class MeasureParams extends HandlerParams {
9296        private final PackageStats mStats;
9297        private boolean mSuccess;
9298
9299        private final IPackageStatsObserver mObserver;
9300
9301        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9302            super(new UserHandle(stats.userHandle));
9303            mObserver = observer;
9304            mStats = stats;
9305        }
9306
9307        @Override
9308        public String toString() {
9309            return "MeasureParams{"
9310                + Integer.toHexString(System.identityHashCode(this))
9311                + " " + mStats.packageName + "}";
9312        }
9313
9314        @Override
9315        void handleStartCopy() throws RemoteException {
9316            synchronized (mInstallLock) {
9317                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9318            }
9319
9320            if (mSuccess) {
9321                final boolean mounted;
9322                if (Environment.isExternalStorageEmulated()) {
9323                    mounted = true;
9324                } else {
9325                    final String status = Environment.getExternalStorageState();
9326                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9327                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9328                }
9329
9330                if (mounted) {
9331                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9332
9333                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9334                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9335
9336                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9337                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9338
9339                    // Always subtract cache size, since it's a subdirectory
9340                    mStats.externalDataSize -= mStats.externalCacheSize;
9341
9342                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9343                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9344
9345                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9346                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9347                }
9348            }
9349        }
9350
9351        @Override
9352        void handleReturnCode() {
9353            if (mObserver != null) {
9354                try {
9355                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9356                } catch (RemoteException e) {
9357                    Slog.i(TAG, "Observer no longer exists.");
9358                }
9359            }
9360        }
9361
9362        @Override
9363        void handleServiceError() {
9364            Slog.e(TAG, "Could not measure application " + mStats.packageName
9365                            + " external storage");
9366        }
9367    }
9368
9369    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9370            throws RemoteException {
9371        long result = 0;
9372        for (File path : paths) {
9373            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9374        }
9375        return result;
9376    }
9377
9378    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9379        for (File path : paths) {
9380            try {
9381                mcs.clearDirectory(path.getAbsolutePath());
9382            } catch (RemoteException e) {
9383            }
9384        }
9385    }
9386
9387    static class OriginInfo {
9388        /**
9389         * Location where install is coming from, before it has been
9390         * copied/renamed into place. This could be a single monolithic APK
9391         * file, or a cluster directory. This location may be untrusted.
9392         */
9393        final File file;
9394        final String cid;
9395
9396        /**
9397         * Flag indicating that {@link #file} or {@link #cid} has already been
9398         * staged, meaning downstream users don't need to defensively copy the
9399         * contents.
9400         */
9401        final boolean staged;
9402
9403        /**
9404         * Flag indicating that {@link #file} or {@link #cid} is an already
9405         * installed app that is being moved.
9406         */
9407        final boolean existing;
9408
9409        final String resolvedPath;
9410        final File resolvedFile;
9411
9412        static OriginInfo fromNothing() {
9413            return new OriginInfo(null, null, false, false);
9414        }
9415
9416        static OriginInfo fromUntrustedFile(File file) {
9417            return new OriginInfo(file, null, false, false);
9418        }
9419
9420        static OriginInfo fromExistingFile(File file) {
9421            return new OriginInfo(file, null, false, true);
9422        }
9423
9424        static OriginInfo fromStagedFile(File file) {
9425            return new OriginInfo(file, null, true, false);
9426        }
9427
9428        static OriginInfo fromStagedContainer(String cid) {
9429            return new OriginInfo(null, cid, true, false);
9430        }
9431
9432        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9433            this.file = file;
9434            this.cid = cid;
9435            this.staged = staged;
9436            this.existing = existing;
9437
9438            if (cid != null) {
9439                resolvedPath = PackageHelper.getSdDir(cid);
9440                resolvedFile = new File(resolvedPath);
9441            } else if (file != null) {
9442                resolvedPath = file.getAbsolutePath();
9443                resolvedFile = file;
9444            } else {
9445                resolvedPath = null;
9446                resolvedFile = null;
9447            }
9448        }
9449    }
9450
9451    class InstallParams extends HandlerParams {
9452        final OriginInfo origin;
9453        final IPackageInstallObserver2 observer;
9454        int installFlags;
9455        final String installerPackageName;
9456        final String volumeUuid;
9457        final VerificationParams verificationParams;
9458        private InstallArgs mArgs;
9459        private int mRet;
9460        final String packageAbiOverride;
9461
9462        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9463                String installerPackageName, String volumeUuid,
9464                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9465            super(user);
9466            this.origin = origin;
9467            this.observer = observer;
9468            this.installFlags = installFlags;
9469            this.installerPackageName = installerPackageName;
9470            this.volumeUuid = volumeUuid;
9471            this.verificationParams = verificationParams;
9472            this.packageAbiOverride = packageAbiOverride;
9473        }
9474
9475        @Override
9476        public String toString() {
9477            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9478                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9479        }
9480
9481        public ManifestDigest getManifestDigest() {
9482            if (verificationParams == null) {
9483                return null;
9484            }
9485            return verificationParams.getManifestDigest();
9486        }
9487
9488        private int installLocationPolicy(PackageInfoLite pkgLite) {
9489            String packageName = pkgLite.packageName;
9490            int installLocation = pkgLite.installLocation;
9491            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9492            // reader
9493            synchronized (mPackages) {
9494                PackageParser.Package pkg = mPackages.get(packageName);
9495                if (pkg != null) {
9496                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9497                        // Check for downgrading.
9498                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9499                            try {
9500                                checkDowngrade(pkg, pkgLite);
9501                            } catch (PackageManagerException e) {
9502                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9503                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9504                            }
9505                        }
9506                        // Check for updated system application.
9507                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9508                            if (onSd) {
9509                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9510                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9511                            }
9512                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9513                        } else {
9514                            if (onSd) {
9515                                // Install flag overrides everything.
9516                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9517                            }
9518                            // If current upgrade specifies particular preference
9519                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9520                                // Application explicitly specified internal.
9521                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9522                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9523                                // App explictly prefers external. Let policy decide
9524                            } else {
9525                                // Prefer previous location
9526                                if (isExternal(pkg)) {
9527                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9528                                }
9529                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9530                            }
9531                        }
9532                    } else {
9533                        // Invalid install. Return error code
9534                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9535                    }
9536                }
9537            }
9538            // All the special cases have been taken care of.
9539            // Return result based on recommended install location.
9540            if (onSd) {
9541                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9542            }
9543            return pkgLite.recommendedInstallLocation;
9544        }
9545
9546        /*
9547         * Invoke remote method to get package information and install
9548         * location values. Override install location based on default
9549         * policy if needed and then create install arguments based
9550         * on the install location.
9551         */
9552        public void handleStartCopy() throws RemoteException {
9553            int ret = PackageManager.INSTALL_SUCCEEDED;
9554
9555            // If we're already staged, we've firmly committed to an install location
9556            if (origin.staged) {
9557                if (origin.file != null) {
9558                    installFlags |= PackageManager.INSTALL_INTERNAL;
9559                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9560                } else if (origin.cid != null) {
9561                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9562                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9563                } else {
9564                    throw new IllegalStateException("Invalid stage location");
9565                }
9566            }
9567
9568            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9569            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9570
9571            PackageInfoLite pkgLite = null;
9572
9573            if (onInt && onSd) {
9574                // Check if both bits are set.
9575                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9576                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9577            } else {
9578                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9579                        packageAbiOverride);
9580
9581                /*
9582                 * If we have too little free space, try to free cache
9583                 * before giving up.
9584                 */
9585                if (!origin.staged && pkgLite.recommendedInstallLocation
9586                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9587                    // TODO: focus freeing disk space on the target device
9588                    final StorageManager storage = StorageManager.from(mContext);
9589                    final long lowThreshold = storage.getStorageLowBytes(
9590                            Environment.getDataDirectory());
9591
9592                    final long sizeBytes = mContainerService.calculateInstalledSize(
9593                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9594
9595                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
9596                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9597                                installFlags, packageAbiOverride);
9598                    }
9599
9600                    /*
9601                     * The cache free must have deleted the file we
9602                     * downloaded to install.
9603                     *
9604                     * TODO: fix the "freeCache" call to not delete
9605                     *       the file we care about.
9606                     */
9607                    if (pkgLite.recommendedInstallLocation
9608                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9609                        pkgLite.recommendedInstallLocation
9610                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9611                    }
9612                }
9613            }
9614
9615            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9616                int loc = pkgLite.recommendedInstallLocation;
9617                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9618                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9619                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9620                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9621                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9622                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9623                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9624                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9625                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9626                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9627                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9628                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9629                } else {
9630                    // Override with defaults if needed.
9631                    loc = installLocationPolicy(pkgLite);
9632                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9633                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9634                    } else if (!onSd && !onInt) {
9635                        // Override install location with flags
9636                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9637                            // Set the flag to install on external media.
9638                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9639                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9640                        } else {
9641                            // Make sure the flag for installing on external
9642                            // media is unset
9643                            installFlags |= PackageManager.INSTALL_INTERNAL;
9644                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9645                        }
9646                    }
9647                }
9648            }
9649
9650            final InstallArgs args = createInstallArgs(this);
9651            mArgs = args;
9652
9653            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9654                 /*
9655                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9656                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9657                 */
9658                int userIdentifier = getUser().getIdentifier();
9659                if (userIdentifier == UserHandle.USER_ALL
9660                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9661                    userIdentifier = UserHandle.USER_OWNER;
9662                }
9663
9664                /*
9665                 * Determine if we have any installed package verifiers. If we
9666                 * do, then we'll defer to them to verify the packages.
9667                 */
9668                final int requiredUid = mRequiredVerifierPackage == null ? -1
9669                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9670                if (!origin.existing && requiredUid != -1
9671                        && isVerificationEnabled(userIdentifier, installFlags)) {
9672                    final Intent verification = new Intent(
9673                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9674                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9675                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9676                            PACKAGE_MIME_TYPE);
9677                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9678
9679                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9680                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9681                            0 /* TODO: Which userId? */);
9682
9683                    if (DEBUG_VERIFY) {
9684                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9685                                + verification.toString() + " with " + pkgLite.verifiers.length
9686                                + " optional verifiers");
9687                    }
9688
9689                    final int verificationId = mPendingVerificationToken++;
9690
9691                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9692
9693                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9694                            installerPackageName);
9695
9696                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9697                            installFlags);
9698
9699                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9700                            pkgLite.packageName);
9701
9702                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9703                            pkgLite.versionCode);
9704
9705                    if (verificationParams != null) {
9706                        if (verificationParams.getVerificationURI() != null) {
9707                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9708                                 verificationParams.getVerificationURI());
9709                        }
9710                        if (verificationParams.getOriginatingURI() != null) {
9711                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9712                                  verificationParams.getOriginatingURI());
9713                        }
9714                        if (verificationParams.getReferrer() != null) {
9715                            verification.putExtra(Intent.EXTRA_REFERRER,
9716                                  verificationParams.getReferrer());
9717                        }
9718                        if (verificationParams.getOriginatingUid() >= 0) {
9719                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9720                                  verificationParams.getOriginatingUid());
9721                        }
9722                        if (verificationParams.getInstallerUid() >= 0) {
9723                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9724                                  verificationParams.getInstallerUid());
9725                        }
9726                    }
9727
9728                    final PackageVerificationState verificationState = new PackageVerificationState(
9729                            requiredUid, args);
9730
9731                    mPendingVerification.append(verificationId, verificationState);
9732
9733                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9734                            receivers, verificationState);
9735
9736                    /*
9737                     * If any sufficient verifiers were listed in the package
9738                     * manifest, attempt to ask them.
9739                     */
9740                    if (sufficientVerifiers != null) {
9741                        final int N = sufficientVerifiers.size();
9742                        if (N == 0) {
9743                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9744                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9745                        } else {
9746                            for (int i = 0; i < N; i++) {
9747                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9748
9749                                final Intent sufficientIntent = new Intent(verification);
9750                                sufficientIntent.setComponent(verifierComponent);
9751
9752                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9753                            }
9754                        }
9755                    }
9756
9757                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9758                            mRequiredVerifierPackage, receivers);
9759                    if (ret == PackageManager.INSTALL_SUCCEEDED
9760                            && mRequiredVerifierPackage != null) {
9761                        /*
9762                         * Send the intent to the required verification agent,
9763                         * but only start the verification timeout after the
9764                         * target BroadcastReceivers have run.
9765                         */
9766                        verification.setComponent(requiredVerifierComponent);
9767                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9768                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9769                                new BroadcastReceiver() {
9770                                    @Override
9771                                    public void onReceive(Context context, Intent intent) {
9772                                        final Message msg = mHandler
9773                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9774                                        msg.arg1 = verificationId;
9775                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9776                                    }
9777                                }, null, 0, null, null);
9778
9779                        /*
9780                         * We don't want the copy to proceed until verification
9781                         * succeeds, so null out this field.
9782                         */
9783                        mArgs = null;
9784                    }
9785                } else {
9786                    /*
9787                     * No package verification is enabled, so immediately start
9788                     * the remote call to initiate copy using temporary file.
9789                     */
9790                    ret = args.copyApk(mContainerService, true);
9791                }
9792            }
9793
9794            mRet = ret;
9795        }
9796
9797        @Override
9798        void handleReturnCode() {
9799            // If mArgs is null, then MCS couldn't be reached. When it
9800            // reconnects, it will try again to install. At that point, this
9801            // will succeed.
9802            if (mArgs != null) {
9803                processPendingInstall(mArgs, mRet);
9804            }
9805        }
9806
9807        @Override
9808        void handleServiceError() {
9809            mArgs = createInstallArgs(this);
9810            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9811        }
9812
9813        public boolean isForwardLocked() {
9814            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9815        }
9816    }
9817
9818    /**
9819     * Used during creation of InstallArgs
9820     *
9821     * @param installFlags package installation flags
9822     * @return true if should be installed on external storage
9823     */
9824    private static boolean installOnExternalAsec(int installFlags) {
9825        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9826            return false;
9827        }
9828        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9829            return true;
9830        }
9831        return false;
9832    }
9833
9834    /**
9835     * Used during creation of InstallArgs
9836     *
9837     * @param installFlags package installation flags
9838     * @return true if should be installed as forward locked
9839     */
9840    private static boolean installForwardLocked(int installFlags) {
9841        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9842    }
9843
9844    private InstallArgs createInstallArgs(InstallParams params) {
9845        if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
9846            return new AsecInstallArgs(params);
9847        } else {
9848            return new FileInstallArgs(params);
9849        }
9850    }
9851
9852    /**
9853     * Create args that describe an existing installed package. Typically used
9854     * when cleaning up old installs, or used as a move source.
9855     */
9856    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9857            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9858        final boolean isInAsec;
9859        if (installOnExternalAsec(installFlags)) {
9860            /* Apps on SD card are always in ASEC containers. */
9861            isInAsec = true;
9862        } else if (installForwardLocked(installFlags)
9863                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9864            /*
9865             * Forward-locked apps are only in ASEC containers if they're the
9866             * new style
9867             */
9868            isInAsec = true;
9869        } else {
9870            isInAsec = false;
9871        }
9872
9873        if (isInAsec) {
9874            return new AsecInstallArgs(codePath, instructionSets,
9875                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
9876        } else {
9877            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9878                    instructionSets);
9879        }
9880    }
9881
9882    static abstract class InstallArgs {
9883        /** @see InstallParams#origin */
9884        final OriginInfo origin;
9885
9886        final IPackageInstallObserver2 observer;
9887        // Always refers to PackageManager flags only
9888        final int installFlags;
9889        final String installerPackageName;
9890        final String volumeUuid;
9891        final ManifestDigest manifestDigest;
9892        final UserHandle user;
9893        final String abiOverride;
9894
9895        // The list of instruction sets supported by this app. This is currently
9896        // only used during the rmdex() phase to clean up resources. We can get rid of this
9897        // if we move dex files under the common app path.
9898        /* nullable */ String[] instructionSets;
9899
9900        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9901                String installerPackageName, String volumeUuid, ManifestDigest manifestDigest,
9902                UserHandle user, String[] instructionSets, String abiOverride) {
9903            this.origin = origin;
9904            this.installFlags = installFlags;
9905            this.observer = observer;
9906            this.installerPackageName = installerPackageName;
9907            this.volumeUuid = volumeUuid;
9908            this.manifestDigest = manifestDigest;
9909            this.user = user;
9910            this.instructionSets = instructionSets;
9911            this.abiOverride = abiOverride;
9912        }
9913
9914        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9915        abstract int doPreInstall(int status);
9916
9917        /**
9918         * Rename package into final resting place. All paths on the given
9919         * scanned package should be updated to reflect the rename.
9920         */
9921        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9922        abstract int doPostInstall(int status, int uid);
9923
9924        /** @see PackageSettingBase#codePathString */
9925        abstract String getCodePath();
9926        /** @see PackageSettingBase#resourcePathString */
9927        abstract String getResourcePath();
9928        abstract String getLegacyNativeLibraryPath();
9929
9930        // Need installer lock especially for dex file removal.
9931        abstract void cleanUpResourcesLI();
9932        abstract boolean doPostDeleteLI(boolean delete);
9933        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9934
9935        /**
9936         * Called before the source arguments are copied. This is used mostly
9937         * for MoveParams when it needs to read the source file to put it in the
9938         * destination.
9939         */
9940        int doPreCopy() {
9941            return PackageManager.INSTALL_SUCCEEDED;
9942        }
9943
9944        /**
9945         * Called after the source arguments are copied. This is used mostly for
9946         * MoveParams when it needs to read the source file to put it in the
9947         * destination.
9948         *
9949         * @return
9950         */
9951        int doPostCopy(int uid) {
9952            return PackageManager.INSTALL_SUCCEEDED;
9953        }
9954
9955        protected boolean isFwdLocked() {
9956            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9957        }
9958
9959        protected boolean isExternalAsec() {
9960            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9961        }
9962
9963        UserHandle getUser() {
9964            return user;
9965        }
9966    }
9967
9968    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
9969        if (!allCodePaths.isEmpty()) {
9970            if (instructionSets == null) {
9971                throw new IllegalStateException("instructionSet == null");
9972            }
9973            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9974            for (String codePath : allCodePaths) {
9975                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9976                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9977                    if (retCode < 0) {
9978                        Slog.w(TAG, "Couldn't remove dex file for package: "
9979                                + " at location " + codePath + ", retcode=" + retCode);
9980                        // we don't consider this to be a failure of the core package deletion
9981                    }
9982                }
9983            }
9984        }
9985    }
9986
9987    /**
9988     * Logic to handle installation of non-ASEC applications, including copying
9989     * and renaming logic.
9990     */
9991    class FileInstallArgs extends InstallArgs {
9992        private File codeFile;
9993        private File resourceFile;
9994        private File legacyNativeLibraryPath;
9995
9996        // Example topology:
9997        // /data/app/com.example/base.apk
9998        // /data/app/com.example/split_foo.apk
9999        // /data/app/com.example/lib/arm/libfoo.so
10000        // /data/app/com.example/lib/arm64/libfoo.so
10001        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10002
10003        /** New install */
10004        FileInstallArgs(InstallParams params) {
10005            super(params.origin, params.observer, params.installFlags,
10006                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10007                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10008            if (isFwdLocked()) {
10009                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10010            }
10011        }
10012
10013        /** Existing install */
10014        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
10015                String[] instructionSets) {
10016            super(OriginInfo.fromNothing(), null, 0, null, null, null, null, instructionSets, null);
10017            this.codeFile = (codePath != null) ? new File(codePath) : null;
10018            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10019            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
10020                    new File(legacyNativeLibraryPath) : null;
10021        }
10022
10023        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
10024            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
10025                    isFwdLocked(), abiOverride);
10026
10027            final StorageManager storage = StorageManager.from(mContext);
10028            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
10029        }
10030
10031        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10032            if (origin.staged) {
10033                Slog.d(TAG, origin.file + " already staged; skipping copy");
10034                codeFile = origin.file;
10035                resourceFile = origin.file;
10036                return PackageManager.INSTALL_SUCCEEDED;
10037            }
10038
10039            try {
10040                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10041                codeFile = tempDir;
10042                resourceFile = tempDir;
10043            } catch (IOException e) {
10044                Slog.w(TAG, "Failed to create copy file: " + e);
10045                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10046            }
10047
10048            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10049                @Override
10050                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10051                    if (!FileUtils.isValidExtFilename(name)) {
10052                        throw new IllegalArgumentException("Invalid filename: " + name);
10053                    }
10054                    try {
10055                        final File file = new File(codeFile, name);
10056                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10057                                O_RDWR | O_CREAT, 0644);
10058                        Os.chmod(file.getAbsolutePath(), 0644);
10059                        return new ParcelFileDescriptor(fd);
10060                    } catch (ErrnoException e) {
10061                        throw new RemoteException("Failed to open: " + e.getMessage());
10062                    }
10063                }
10064            };
10065
10066            int ret = PackageManager.INSTALL_SUCCEEDED;
10067            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10068            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10069                Slog.e(TAG, "Failed to copy package");
10070                return ret;
10071            }
10072
10073            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10074            NativeLibraryHelper.Handle handle = null;
10075            try {
10076                handle = NativeLibraryHelper.Handle.create(codeFile);
10077                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10078                        abiOverride);
10079            } catch (IOException e) {
10080                Slog.e(TAG, "Copying native libraries failed", e);
10081                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10082            } finally {
10083                IoUtils.closeQuietly(handle);
10084            }
10085
10086            return ret;
10087        }
10088
10089        int doPreInstall(int status) {
10090            if (status != PackageManager.INSTALL_SUCCEEDED) {
10091                cleanUp();
10092            }
10093            return status;
10094        }
10095
10096        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10097            if (status != PackageManager.INSTALL_SUCCEEDED) {
10098                cleanUp();
10099                return false;
10100            } else {
10101                final File targetDir = codeFile.getParentFile();
10102                final File beforeCodeFile = codeFile;
10103                final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10104
10105                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10106                try {
10107                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10108                } catch (ErrnoException e) {
10109                    Slog.d(TAG, "Failed to rename", e);
10110                    return false;
10111                }
10112
10113                if (!SELinux.restoreconRecursive(afterCodeFile)) {
10114                    Slog.d(TAG, "Failed to restorecon");
10115                    return false;
10116                }
10117
10118                // Reflect the rename internally
10119                codeFile = afterCodeFile;
10120                resourceFile = afterCodeFile;
10121
10122                // Reflect the rename in scanned details
10123                pkg.codePath = afterCodeFile.getAbsolutePath();
10124                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10125                        pkg.baseCodePath);
10126                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10127                        pkg.splitCodePaths);
10128
10129                // Reflect the rename in app info
10130                pkg.applicationInfo.setCodePath(pkg.codePath);
10131                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10132                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10133                pkg.applicationInfo.setResourcePath(pkg.codePath);
10134                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10135                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10136
10137                return true;
10138            }
10139        }
10140
10141        int doPostInstall(int status, int uid) {
10142            if (status != PackageManager.INSTALL_SUCCEEDED) {
10143                cleanUp();
10144            }
10145            return status;
10146        }
10147
10148        @Override
10149        String getCodePath() {
10150            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10151        }
10152
10153        @Override
10154        String getResourcePath() {
10155            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10156        }
10157
10158        @Override
10159        String getLegacyNativeLibraryPath() {
10160            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
10161        }
10162
10163        private boolean cleanUp() {
10164            if (codeFile == null || !codeFile.exists()) {
10165                return false;
10166            }
10167
10168            if (codeFile.isDirectory()) {
10169                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10170            } else {
10171                codeFile.delete();
10172            }
10173
10174            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10175                resourceFile.delete();
10176            }
10177
10178            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
10179                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
10180                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
10181                }
10182                legacyNativeLibraryPath.delete();
10183            }
10184
10185            return true;
10186        }
10187
10188        void cleanUpResourcesLI() {
10189            // Try enumerating all code paths before deleting
10190            List<String> allCodePaths = Collections.EMPTY_LIST;
10191            if (codeFile != null && codeFile.exists()) {
10192                try {
10193                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10194                    allCodePaths = pkg.getAllCodePaths();
10195                } catch (PackageParserException e) {
10196                    // Ignored; we tried our best
10197                }
10198            }
10199
10200            cleanUp();
10201            removeDexFiles(allCodePaths, instructionSets);
10202        }
10203
10204        boolean doPostDeleteLI(boolean delete) {
10205            // XXX err, shouldn't we respect the delete flag?
10206            cleanUpResourcesLI();
10207            return true;
10208        }
10209    }
10210
10211    private boolean isAsecExternal(String cid) {
10212        final String asecPath = PackageHelper.getSdFilesystem(cid);
10213        return !asecPath.startsWith(mAsecInternalPath);
10214    }
10215
10216    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10217            PackageManagerException {
10218        if (copyRet < 0) {
10219            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10220                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10221                throw new PackageManagerException(copyRet, message);
10222            }
10223        }
10224    }
10225
10226    /**
10227     * Extract the MountService "container ID" from the full code path of an
10228     * .apk.
10229     */
10230    static String cidFromCodePath(String fullCodePath) {
10231        int eidx = fullCodePath.lastIndexOf("/");
10232        String subStr1 = fullCodePath.substring(0, eidx);
10233        int sidx = subStr1.lastIndexOf("/");
10234        return subStr1.substring(sidx+1, eidx);
10235    }
10236
10237    /**
10238     * Logic to handle installation of ASEC applications, including copying and
10239     * renaming logic.
10240     */
10241    class AsecInstallArgs extends InstallArgs {
10242        static final String RES_FILE_NAME = "pkg.apk";
10243        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10244
10245        String cid;
10246        String packagePath;
10247        String resourcePath;
10248        String legacyNativeLibraryDir;
10249
10250        /** New install */
10251        AsecInstallArgs(InstallParams params) {
10252            super(params.origin, params.observer, params.installFlags,
10253                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10254                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10255        }
10256
10257        /** Existing install */
10258        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10259                        boolean isExternal, boolean isForwardLocked) {
10260            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
10261                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10262                    instructionSets, null);
10263            // Hackily pretend we're still looking at a full code path
10264            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10265                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10266            }
10267
10268            // Extract cid from fullCodePath
10269            int eidx = fullCodePath.lastIndexOf("/");
10270            String subStr1 = fullCodePath.substring(0, eidx);
10271            int sidx = subStr1.lastIndexOf("/");
10272            cid = subStr1.substring(sidx+1, eidx);
10273            setMountPath(subStr1);
10274        }
10275
10276        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10277            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10278                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10279                    instructionSets, null);
10280            this.cid = cid;
10281            setMountPath(PackageHelper.getSdDir(cid));
10282        }
10283
10284        void createCopyFile() {
10285            cid = mInstallerService.allocateExternalStageCidLegacy();
10286        }
10287
10288        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
10289            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
10290                    abiOverride);
10291
10292            final File target;
10293            if (isExternalAsec()) {
10294                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
10295            } else {
10296                target = Environment.getDataDirectory();
10297            }
10298
10299            final StorageManager storage = StorageManager.from(mContext);
10300            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
10301        }
10302
10303        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10304            if (origin.staged) {
10305                Slog.d(TAG, origin.cid + " already staged; skipping copy");
10306                cid = origin.cid;
10307                setMountPath(PackageHelper.getSdDir(cid));
10308                return PackageManager.INSTALL_SUCCEEDED;
10309            }
10310
10311            if (temp) {
10312                createCopyFile();
10313            } else {
10314                /*
10315                 * Pre-emptively destroy the container since it's destroyed if
10316                 * copying fails due to it existing anyway.
10317                 */
10318                PackageHelper.destroySdDir(cid);
10319            }
10320
10321            final String newMountPath = imcs.copyPackageToContainer(
10322                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10323                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10324
10325            if (newMountPath != null) {
10326                setMountPath(newMountPath);
10327                return PackageManager.INSTALL_SUCCEEDED;
10328            } else {
10329                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10330            }
10331        }
10332
10333        @Override
10334        String getCodePath() {
10335            return packagePath;
10336        }
10337
10338        @Override
10339        String getResourcePath() {
10340            return resourcePath;
10341        }
10342
10343        @Override
10344        String getLegacyNativeLibraryPath() {
10345            return legacyNativeLibraryDir;
10346        }
10347
10348        int doPreInstall(int status) {
10349            if (status != PackageManager.INSTALL_SUCCEEDED) {
10350                // Destroy container
10351                PackageHelper.destroySdDir(cid);
10352            } else {
10353                boolean mounted = PackageHelper.isContainerMounted(cid);
10354                if (!mounted) {
10355                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10356                            Process.SYSTEM_UID);
10357                    if (newMountPath != null) {
10358                        setMountPath(newMountPath);
10359                    } else {
10360                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10361                    }
10362                }
10363            }
10364            return status;
10365        }
10366
10367        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10368            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10369            String newMountPath = null;
10370            if (PackageHelper.isContainerMounted(cid)) {
10371                // Unmount the container
10372                if (!PackageHelper.unMountSdDir(cid)) {
10373                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10374                    return false;
10375                }
10376            }
10377            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10378                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10379                        " which might be stale. Will try to clean up.");
10380                // Clean up the stale container and proceed to recreate.
10381                if (!PackageHelper.destroySdDir(newCacheId)) {
10382                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10383                    return false;
10384                }
10385                // Successfully cleaned up stale container. Try to rename again.
10386                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10387                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10388                            + " inspite of cleaning it up.");
10389                    return false;
10390                }
10391            }
10392            if (!PackageHelper.isContainerMounted(newCacheId)) {
10393                Slog.w(TAG, "Mounting container " + newCacheId);
10394                newMountPath = PackageHelper.mountSdDir(newCacheId,
10395                        getEncryptKey(), Process.SYSTEM_UID);
10396            } else {
10397                newMountPath = PackageHelper.getSdDir(newCacheId);
10398            }
10399            if (newMountPath == null) {
10400                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10401                return false;
10402            }
10403            Log.i(TAG, "Succesfully renamed " + cid +
10404                    " to " + newCacheId +
10405                    " at new path: " + newMountPath);
10406            cid = newCacheId;
10407
10408            final File beforeCodeFile = new File(packagePath);
10409            setMountPath(newMountPath);
10410            final File afterCodeFile = new File(packagePath);
10411
10412            // Reflect the rename in scanned details
10413            pkg.codePath = afterCodeFile.getAbsolutePath();
10414            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10415                    pkg.baseCodePath);
10416            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10417                    pkg.splitCodePaths);
10418
10419            // Reflect the rename in app info
10420            pkg.applicationInfo.setCodePath(pkg.codePath);
10421            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10422            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10423            pkg.applicationInfo.setResourcePath(pkg.codePath);
10424            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10425            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10426
10427            return true;
10428        }
10429
10430        private void setMountPath(String mountPath) {
10431            final File mountFile = new File(mountPath);
10432
10433            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10434            if (monolithicFile.exists()) {
10435                packagePath = monolithicFile.getAbsolutePath();
10436                if (isFwdLocked()) {
10437                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10438                } else {
10439                    resourcePath = packagePath;
10440                }
10441            } else {
10442                packagePath = mountFile.getAbsolutePath();
10443                resourcePath = packagePath;
10444            }
10445
10446            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
10447        }
10448
10449        int doPostInstall(int status, int uid) {
10450            if (status != PackageManager.INSTALL_SUCCEEDED) {
10451                cleanUp();
10452            } else {
10453                final int groupOwner;
10454                final String protectedFile;
10455                if (isFwdLocked()) {
10456                    groupOwner = UserHandle.getSharedAppGid(uid);
10457                    protectedFile = RES_FILE_NAME;
10458                } else {
10459                    groupOwner = -1;
10460                    protectedFile = null;
10461                }
10462
10463                if (uid < Process.FIRST_APPLICATION_UID
10464                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10465                    Slog.e(TAG, "Failed to finalize " + cid);
10466                    PackageHelper.destroySdDir(cid);
10467                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10468                }
10469
10470                boolean mounted = PackageHelper.isContainerMounted(cid);
10471                if (!mounted) {
10472                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10473                }
10474            }
10475            return status;
10476        }
10477
10478        private void cleanUp() {
10479            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10480
10481            // Destroy secure container
10482            PackageHelper.destroySdDir(cid);
10483        }
10484
10485        private List<String> getAllCodePaths() {
10486            final File codeFile = new File(getCodePath());
10487            if (codeFile != null && codeFile.exists()) {
10488                try {
10489                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10490                    return pkg.getAllCodePaths();
10491                } catch (PackageParserException e) {
10492                    // Ignored; we tried our best
10493                }
10494            }
10495            return Collections.EMPTY_LIST;
10496        }
10497
10498        void cleanUpResourcesLI() {
10499            // Enumerate all code paths before deleting
10500            cleanUpResourcesLI(getAllCodePaths());
10501        }
10502
10503        private void cleanUpResourcesLI(List<String> allCodePaths) {
10504            cleanUp();
10505            removeDexFiles(allCodePaths, instructionSets);
10506        }
10507
10508
10509
10510        String getPackageName() {
10511            return getAsecPackageName(cid);
10512        }
10513
10514        boolean doPostDeleteLI(boolean delete) {
10515            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10516            final List<String> allCodePaths = getAllCodePaths();
10517            boolean mounted = PackageHelper.isContainerMounted(cid);
10518            if (mounted) {
10519                // Unmount first
10520                if (PackageHelper.unMountSdDir(cid)) {
10521                    mounted = false;
10522                }
10523            }
10524            if (!mounted && delete) {
10525                cleanUpResourcesLI(allCodePaths);
10526            }
10527            return !mounted;
10528        }
10529
10530        @Override
10531        int doPreCopy() {
10532            if (isFwdLocked()) {
10533                if (!PackageHelper.fixSdPermissions(cid,
10534                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10535                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10536                }
10537            }
10538
10539            return PackageManager.INSTALL_SUCCEEDED;
10540        }
10541
10542        @Override
10543        int doPostCopy(int uid) {
10544            if (isFwdLocked()) {
10545                if (uid < Process.FIRST_APPLICATION_UID
10546                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10547                                RES_FILE_NAME)) {
10548                    Slog.e(TAG, "Failed to finalize " + cid);
10549                    PackageHelper.destroySdDir(cid);
10550                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10551                }
10552            }
10553
10554            return PackageManager.INSTALL_SUCCEEDED;
10555        }
10556    }
10557
10558    static String getAsecPackageName(String packageCid) {
10559        int idx = packageCid.lastIndexOf("-");
10560        if (idx == -1) {
10561            return packageCid;
10562        }
10563        return packageCid.substring(0, idx);
10564    }
10565
10566    // Utility method used to create code paths based on package name and available index.
10567    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
10568        String idxStr = "";
10569        int idx = 1;
10570        // Fall back to default value of idx=1 if prefix is not
10571        // part of oldCodePath
10572        if (oldCodePath != null) {
10573            String subStr = oldCodePath;
10574            // Drop the suffix right away
10575            if (suffix != null && subStr.endsWith(suffix)) {
10576                subStr = subStr.substring(0, subStr.length() - suffix.length());
10577            }
10578            // If oldCodePath already contains prefix find out the
10579            // ending index to either increment or decrement.
10580            int sidx = subStr.lastIndexOf(prefix);
10581            if (sidx != -1) {
10582                subStr = subStr.substring(sidx + prefix.length());
10583                if (subStr != null) {
10584                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10585                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10586                    }
10587                    try {
10588                        idx = Integer.parseInt(subStr);
10589                        if (idx <= 1) {
10590                            idx++;
10591                        } else {
10592                            idx--;
10593                        }
10594                    } catch(NumberFormatException e) {
10595                    }
10596                }
10597            }
10598        }
10599        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10600        return prefix + idxStr;
10601    }
10602
10603    private File getNextCodePath(File targetDir, String packageName) {
10604        int suffix = 1;
10605        File result;
10606        do {
10607            result = new File(targetDir, packageName + "-" + suffix);
10608            suffix++;
10609        } while (result.exists());
10610        return result;
10611    }
10612
10613    // Utility method that returns the relative package path with respect
10614    // to the installation directory. Like say for /data/data/com.test-1.apk
10615    // string com.test-1 is returned.
10616    static String deriveCodePathName(String codePath) {
10617        if (codePath == null) {
10618            return null;
10619        }
10620        final File codeFile = new File(codePath);
10621        final String name = codeFile.getName();
10622        if (codeFile.isDirectory()) {
10623            return name;
10624        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10625            final int lastDot = name.lastIndexOf('.');
10626            return name.substring(0, lastDot);
10627        } else {
10628            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10629            return null;
10630        }
10631    }
10632
10633    class PackageInstalledInfo {
10634        String name;
10635        int uid;
10636        // The set of users that originally had this package installed.
10637        int[] origUsers;
10638        // The set of users that now have this package installed.
10639        int[] newUsers;
10640        PackageParser.Package pkg;
10641        int returnCode;
10642        String returnMsg;
10643        PackageRemovedInfo removedInfo;
10644
10645        public void setError(int code, String msg) {
10646            returnCode = code;
10647            returnMsg = msg;
10648            Slog.w(TAG, msg);
10649        }
10650
10651        public void setError(String msg, PackageParserException e) {
10652            returnCode = e.error;
10653            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10654            Slog.w(TAG, msg, e);
10655        }
10656
10657        public void setError(String msg, PackageManagerException e) {
10658            returnCode = e.error;
10659            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10660            Slog.w(TAG, msg, e);
10661        }
10662
10663        // In some error cases we want to convey more info back to the observer
10664        String origPackage;
10665        String origPermission;
10666    }
10667
10668    /*
10669     * Install a non-existing package.
10670     */
10671    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
10672            UserHandle user, String installerPackageName, String volumeUuid,
10673            PackageInstalledInfo res) {
10674        // Remember this for later, in case we need to rollback this install
10675        String pkgName = pkg.packageName;
10676
10677        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10678        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
10679        synchronized(mPackages) {
10680            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10681                // A package with the same name is already installed, though
10682                // it has been renamed to an older name.  The package we
10683                // are trying to install should be installed as an update to
10684                // the existing one, but that has not been requested, so bail.
10685                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10686                        + " without first uninstalling package running as "
10687                        + mSettings.mRenamedPackages.get(pkgName));
10688                return;
10689            }
10690            if (mPackages.containsKey(pkgName)) {
10691                // Don't allow installation over an existing package with the same name.
10692                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10693                        + " without first uninstalling.");
10694                return;
10695            }
10696        }
10697
10698        try {
10699            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10700                    System.currentTimeMillis(), user);
10701
10702            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
10703            // delete the partially installed application. the data directory will have to be
10704            // restored if it was already existing
10705            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10706                // remove package from internal structures.  Note that we want deletePackageX to
10707                // delete the package data and cache directories that it created in
10708                // scanPackageLocked, unless those directories existed before we even tried to
10709                // install.
10710                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10711                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10712                                res.removedInfo, true);
10713            }
10714
10715        } catch (PackageManagerException e) {
10716            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10717        }
10718    }
10719
10720    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10721        // Upgrade keysets are being used.  Determine if new package has a superset of the
10722        // required keys.
10723        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10724        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10725        for (int i = 0; i < upgradeKeySets.length; i++) {
10726            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10727            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10728                return true;
10729            }
10730        }
10731        return false;
10732    }
10733
10734    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
10735            UserHandle user, String installerPackageName, String volumeUuid,
10736            PackageInstalledInfo res) {
10737        PackageParser.Package oldPackage;
10738        String pkgName = pkg.packageName;
10739        int[] allUsers;
10740        boolean[] perUserInstalled;
10741
10742        // First find the old package info and check signatures
10743        synchronized(mPackages) {
10744            oldPackage = mPackages.get(pkgName);
10745            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10746            PackageSetting ps = mSettings.mPackages.get(pkgName);
10747            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10748                // default to original signature matching
10749                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10750                    != PackageManager.SIGNATURE_MATCH) {
10751                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10752                            "New package has a different signature: " + pkgName);
10753                    return;
10754                }
10755            } else {
10756                if(!checkUpgradeKeySetLP(ps, pkg)) {
10757                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10758                            "New package not signed by keys specified by upgrade-keysets: "
10759                            + pkgName);
10760                    return;
10761                }
10762            }
10763
10764            // In case of rollback, remember per-user/profile install state
10765            allUsers = sUserManager.getUserIds();
10766            perUserInstalled = new boolean[allUsers.length];
10767            for (int i = 0; i < allUsers.length; i++) {
10768                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10769            }
10770        }
10771
10772        boolean sysPkg = (isSystemApp(oldPackage));
10773        if (sysPkg) {
10774            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10775                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
10776        } else {
10777            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10778                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
10779        }
10780    }
10781
10782    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10783            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10784            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
10785            String volumeUuid, PackageInstalledInfo res) {
10786        String pkgName = deletedPackage.packageName;
10787        boolean deletedPkg = true;
10788        boolean updatedSettings = false;
10789
10790        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10791                + deletedPackage);
10792        long origUpdateTime;
10793        if (pkg.mExtras != null) {
10794            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10795        } else {
10796            origUpdateTime = 0;
10797        }
10798
10799        // First delete the existing package while retaining the data directory
10800        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10801                res.removedInfo, true)) {
10802            // If the existing package wasn't successfully deleted
10803            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10804            deletedPkg = false;
10805        } else {
10806            // Successfully deleted the old package; proceed with replace.
10807
10808            // If deleted package lived in a container, give users a chance to
10809            // relinquish resources before killing.
10810            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
10811                if (DEBUG_INSTALL) {
10812                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10813                }
10814                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10815                final ArrayList<String> pkgList = new ArrayList<String>(1);
10816                pkgList.add(deletedPackage.applicationInfo.packageName);
10817                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10818            }
10819
10820            deleteCodeCacheDirsLI(pkgName);
10821            try {
10822                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10823                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10824                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
10825                        perUserInstalled, res, user);
10826                updatedSettings = true;
10827            } catch (PackageManagerException e) {
10828                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10829            }
10830        }
10831
10832        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10833            // remove package from internal structures.  Note that we want deletePackageX to
10834            // delete the package data and cache directories that it created in
10835            // scanPackageLocked, unless those directories existed before we even tried to
10836            // install.
10837            if(updatedSettings) {
10838                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10839                deletePackageLI(
10840                        pkgName, null, true, allUsers, perUserInstalled,
10841                        PackageManager.DELETE_KEEP_DATA,
10842                                res.removedInfo, true);
10843            }
10844            // Since we failed to install the new package we need to restore the old
10845            // package that we deleted.
10846            if (deletedPkg) {
10847                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10848                File restoreFile = new File(deletedPackage.codePath);
10849                // Parse old package
10850                boolean oldExternal = isExternal(deletedPackage);
10851                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10852                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10853                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
10854                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10855                try {
10856                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10857                } catch (PackageManagerException e) {
10858                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10859                            + e.getMessage());
10860                    return;
10861                }
10862                // Restore of old package succeeded. Update permissions.
10863                // writer
10864                synchronized (mPackages) {
10865                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10866                            UPDATE_PERMISSIONS_ALL);
10867                    // can downgrade to reader
10868                    mSettings.writeLPr();
10869                }
10870                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10871            }
10872        }
10873    }
10874
10875    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10876            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10877            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
10878            String volumeUuid, PackageInstalledInfo res) {
10879        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10880                + ", old=" + deletedPackage);
10881        boolean disabledSystem = false;
10882        boolean updatedSettings = false;
10883        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10884        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
10885                != 0) {
10886            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10887        }
10888        String packageName = deletedPackage.packageName;
10889        if (packageName == null) {
10890            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10891                    "Attempt to delete null packageName.");
10892            return;
10893        }
10894        PackageParser.Package oldPkg;
10895        PackageSetting oldPkgSetting;
10896        // reader
10897        synchronized (mPackages) {
10898            oldPkg = mPackages.get(packageName);
10899            oldPkgSetting = mSettings.mPackages.get(packageName);
10900            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10901                    (oldPkgSetting == null)) {
10902                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10903                        "Couldn't find package:" + packageName + " information");
10904                return;
10905            }
10906        }
10907
10908        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10909
10910        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10911        res.removedInfo.removedPackage = packageName;
10912        // Remove existing system package
10913        removePackageLI(oldPkgSetting, true);
10914        // writer
10915        synchronized (mPackages) {
10916            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10917            if (!disabledSystem && deletedPackage != null) {
10918                // We didn't need to disable the .apk as a current system package,
10919                // which means we are replacing another update that is already
10920                // installed.  We need to make sure to delete the older one's .apk.
10921                res.removedInfo.args = createInstallArgsForExisting(0,
10922                        deletedPackage.applicationInfo.getCodePath(),
10923                        deletedPackage.applicationInfo.getResourcePath(),
10924                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10925                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10926            } else {
10927                res.removedInfo.args = null;
10928            }
10929        }
10930
10931        // Successfully disabled the old package. Now proceed with re-installation
10932        deleteCodeCacheDirsLI(packageName);
10933
10934        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10935        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10936
10937        PackageParser.Package newPackage = null;
10938        try {
10939            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10940            if (newPackage.mExtras != null) {
10941                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10942                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10943                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10944
10945                // is the update attempting to change shared user? that isn't going to work...
10946                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10947                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10948                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10949                            + " to " + newPkgSetting.sharedUser);
10950                    updatedSettings = true;
10951                }
10952            }
10953
10954            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10955                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
10956                        perUserInstalled, res, user);
10957                updatedSettings = true;
10958            }
10959
10960        } catch (PackageManagerException e) {
10961            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10962        }
10963
10964        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10965            // Re installation failed. Restore old information
10966            // Remove new pkg information
10967            if (newPackage != null) {
10968                removeInstalledPackageLI(newPackage, true);
10969            }
10970            // Add back the old system package
10971            try {
10972                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10973            } catch (PackageManagerException e) {
10974                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10975            }
10976            // Restore the old system information in Settings
10977            synchronized (mPackages) {
10978                if (disabledSystem) {
10979                    mSettings.enableSystemPackageLPw(packageName);
10980                }
10981                if (updatedSettings) {
10982                    mSettings.setInstallerPackageName(packageName,
10983                            oldPkgSetting.installerPackageName);
10984                }
10985                mSettings.writeLPr();
10986            }
10987        }
10988    }
10989
10990    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10991            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
10992            UserHandle user) {
10993        String pkgName = newPackage.packageName;
10994        synchronized (mPackages) {
10995            //write settings. the installStatus will be incomplete at this stage.
10996            //note that the new package setting would have already been
10997            //added to mPackages. It hasn't been persisted yet.
10998            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10999            mSettings.writeLPr();
11000        }
11001
11002        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11003
11004        synchronized (mPackages) {
11005            updatePermissionsLPw(newPackage.packageName, newPackage,
11006                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11007                            ? UPDATE_PERMISSIONS_ALL : 0));
11008            // For system-bundled packages, we assume that installing an upgraded version
11009            // of the package implies that the user actually wants to run that new code,
11010            // so we enable the package.
11011            PackageSetting ps = mSettings.mPackages.get(pkgName);
11012            if (ps != null) {
11013                if (isSystemApp(newPackage)) {
11014                    // NB: implicit assumption that system package upgrades apply to all users
11015                    if (DEBUG_INSTALL) {
11016                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11017                    }
11018                    if (res.origUsers != null) {
11019                        for (int userHandle : res.origUsers) {
11020                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11021                                    userHandle, installerPackageName);
11022                        }
11023                    }
11024                    // Also convey the prior install/uninstall state
11025                    if (allUsers != null && perUserInstalled != null) {
11026                        for (int i = 0; i < allUsers.length; i++) {
11027                            if (DEBUG_INSTALL) {
11028                                Slog.d(TAG, "    user " + allUsers[i]
11029                                        + " => " + perUserInstalled[i]);
11030                            }
11031                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11032                        }
11033                        // these install state changes will be persisted in the
11034                        // upcoming call to mSettings.writeLPr().
11035                    }
11036                }
11037                // It's implied that when a user requests installation, they want the app to be
11038                // installed and enabled.
11039                int userId = user.getIdentifier();
11040                if (userId != UserHandle.USER_ALL) {
11041                    ps.setInstalled(true, userId);
11042                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11043                }
11044            }
11045            res.name = pkgName;
11046            res.uid = newPackage.applicationInfo.uid;
11047            res.pkg = newPackage;
11048            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11049            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11050            mSettings.setVolumeUuid(pkgName, volumeUuid);
11051            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11052            //to update install status
11053            mSettings.writeLPr();
11054        }
11055    }
11056
11057    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11058        final int installFlags = args.installFlags;
11059        final String installerPackageName = args.installerPackageName;
11060        final String volumeUuid = args.volumeUuid;
11061        final File tmpPackageFile = new File(args.getCodePath());
11062        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11063        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11064                || (args.volumeUuid != null));
11065        boolean replace = false;
11066        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
11067        // Result object to be returned
11068        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11069
11070        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11071        // Retrieve PackageSettings and parse package
11072        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11073                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11074                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11075        PackageParser pp = new PackageParser();
11076        pp.setSeparateProcesses(mSeparateProcesses);
11077        pp.setDisplayMetrics(mMetrics);
11078
11079        final PackageParser.Package pkg;
11080        try {
11081            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11082        } catch (PackageParserException e) {
11083            res.setError("Failed parse during installPackageLI", e);
11084            return;
11085        }
11086
11087        // Mark that we have an install time CPU ABI override.
11088        pkg.cpuAbiOverride = args.abiOverride;
11089
11090        String pkgName = res.name = pkg.packageName;
11091        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11092            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11093                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11094                return;
11095            }
11096        }
11097
11098        try {
11099            pp.collectCertificates(pkg, parseFlags);
11100            pp.collectManifestDigest(pkg);
11101        } catch (PackageParserException e) {
11102            res.setError("Failed collect during installPackageLI", e);
11103            return;
11104        }
11105
11106        /* If the installer passed in a manifest digest, compare it now. */
11107        if (args.manifestDigest != null) {
11108            if (DEBUG_INSTALL) {
11109                final String parsedManifest = pkg.manifestDigest == null ? "null"
11110                        : pkg.manifestDigest.toString();
11111                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11112                        + parsedManifest);
11113            }
11114
11115            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11116                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11117                return;
11118            }
11119        } else if (DEBUG_INSTALL) {
11120            final String parsedManifest = pkg.manifestDigest == null
11121                    ? "null" : pkg.manifestDigest.toString();
11122            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11123        }
11124
11125        // Get rid of all references to package scan path via parser.
11126        pp = null;
11127        String oldCodePath = null;
11128        boolean systemApp = false;
11129        synchronized (mPackages) {
11130            // Check if installing already existing package
11131            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11132                String oldName = mSettings.mRenamedPackages.get(pkgName);
11133                if (pkg.mOriginalPackages != null
11134                        && pkg.mOriginalPackages.contains(oldName)
11135                        && mPackages.containsKey(oldName)) {
11136                    // This package is derived from an original package,
11137                    // and this device has been updating from that original
11138                    // name.  We must continue using the original name, so
11139                    // rename the new package here.
11140                    pkg.setPackageName(oldName);
11141                    pkgName = pkg.packageName;
11142                    replace = true;
11143                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11144                            + oldName + " pkgName=" + pkgName);
11145                } else if (mPackages.containsKey(pkgName)) {
11146                    // This package, under its official name, already exists
11147                    // on the device; we should replace it.
11148                    replace = true;
11149                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11150                }
11151            }
11152
11153            PackageSetting ps = mSettings.mPackages.get(pkgName);
11154            if (ps != null) {
11155                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11156
11157                // Quick sanity check that we're signed correctly if updating;
11158                // we'll check this again later when scanning, but we want to
11159                // bail early here before tripping over redefined permissions.
11160                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11161                    try {
11162                        verifySignaturesLP(ps, pkg);
11163                    } catch (PackageManagerException e) {
11164                        res.setError(e.error, e.getMessage());
11165                        return;
11166                    }
11167                } else {
11168                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11169                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11170                                + pkg.packageName + " upgrade keys do not match the "
11171                                + "previously installed version");
11172                        return;
11173                    }
11174                }
11175
11176                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11177                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11178                    systemApp = (ps.pkg.applicationInfo.flags &
11179                            ApplicationInfo.FLAG_SYSTEM) != 0;
11180                }
11181                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11182            }
11183
11184            // Check whether the newly-scanned package wants to define an already-defined perm
11185            int N = pkg.permissions.size();
11186            for (int i = N-1; i >= 0; i--) {
11187                PackageParser.Permission perm = pkg.permissions.get(i);
11188                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11189                if (bp != null) {
11190                    // If the defining package is signed with our cert, it's okay.  This
11191                    // also includes the "updating the same package" case, of course.
11192                    // "updating same package" could also involve key-rotation.
11193                    final boolean sigsOk;
11194                    if (!bp.sourcePackage.equals(pkg.packageName)
11195                            || !(bp.packageSetting instanceof PackageSetting)
11196                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
11197                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
11198                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11199                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11200                    } else {
11201                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11202                    }
11203                    if (!sigsOk) {
11204                        // If the owning package is the system itself, we log but allow
11205                        // install to proceed; we fail the install on all other permission
11206                        // redefinitions.
11207                        if (!bp.sourcePackage.equals("android")) {
11208                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11209                                    + pkg.packageName + " attempting to redeclare permission "
11210                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11211                            res.origPermission = perm.info.name;
11212                            res.origPackage = bp.sourcePackage;
11213                            return;
11214                        } else {
11215                            Slog.w(TAG, "Package " + pkg.packageName
11216                                    + " attempting to redeclare system permission "
11217                                    + perm.info.name + "; ignoring new declaration");
11218                            pkg.permissions.remove(i);
11219                        }
11220                    }
11221                }
11222            }
11223
11224        }
11225
11226        if (systemApp && onExternal) {
11227            // Disable updates to system apps on sdcard
11228            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11229                    "Cannot install updates to system apps on sdcard");
11230            return;
11231        }
11232
11233        // Run dexopt before old package gets removed, to minimize time when app is not available
11234        int result = mPackageDexOptimizer
11235                .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */,
11236                        false /* defer */, false /* inclDependencies */);
11237        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11238            res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11239            return;
11240        }
11241
11242        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11243            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11244            return;
11245        }
11246
11247        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11248
11249        // Call with SCAN_NO_DEX, since dexopt has already been made
11250        if (replace) {
11251            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING | SCAN_NO_DEX, args.user,
11252                    installerPackageName, volumeUuid, res);
11253        } else {
11254            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES
11255                    | SCAN_NO_DEX, args.user, installerPackageName, volumeUuid, res);
11256        }
11257        synchronized (mPackages) {
11258            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11259            if (ps != null) {
11260                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11261            }
11262        }
11263    }
11264
11265    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11266        if (mIntentFilterVerifierComponent == null) {
11267            Slog.d(TAG, "No IntentFilter verification will not be done as "
11268                    + "there is no IntentFilterVerifier available!");
11269            return;
11270        }
11271
11272        final int verifierUid = getPackageUid(
11273                mIntentFilterVerifierComponent.getPackageName(),
11274                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11275
11276        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11277        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11278        msg.obj = pkg;
11279        msg.arg1 = userId;
11280        msg.arg2 = verifierUid;
11281
11282        mHandler.sendMessage(msg);
11283    }
11284
11285    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11286            PackageParser.Package pkg) {
11287        int size = pkg.activities.size();
11288        if (size == 0) {
11289            Slog.d(TAG, "No activity, so no need to verify any IntentFilter!");
11290            return;
11291        }
11292
11293        final boolean hasDomainURLs = hasDomainURLs(pkg);
11294        if (!hasDomainURLs) {
11295            Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!");
11296            return;
11297        }
11298
11299        Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size
11300                + " Activities needs verification ...");
11301
11302        final int verificationId = mIntentFilterVerificationToken++;
11303        int count = 0;
11304        final String packageName = pkg.packageName;
11305        ArrayList<String> allHosts = new ArrayList<>();
11306
11307        synchronized (mPackages) {
11308            for (PackageParser.Activity a : pkg.activities) {
11309                for (ActivityIntentInfo filter : a.intents) {
11310                    boolean needsFilterVerification = filter.needsVerification();
11311                    if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11312                        Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString());
11313                        mIntentFilterVerifier.addOneIntentFilterVerification(
11314                                verifierUid, userId, verificationId, filter, packageName);
11315                        count++;
11316                    } else if (!needsFilterVerification) {
11317                        Slog.d(TAG, "No verification needed for IntentFilter:"
11318                                + filter.toString());
11319                        if (hasValidDomains(filter)) {
11320                            allHosts.addAll(filter.getHostsList());
11321                        }
11322                    } else {
11323                        Slog.d(TAG, "Verification already done for IntentFilter:"
11324                                + filter.toString());
11325                    }
11326                }
11327            }
11328        }
11329
11330        if (count > 0) {
11331            mIntentFilterVerifier.startVerifications(userId);
11332            Slog.d(TAG, "Started " + count + " IntentFilter verification"
11333                    + (count > 1 ? "s" : "") +  " for userId:" + userId + "!");
11334        } else {
11335            Slog.d(TAG, "No need to start any IntentFilter verification!");
11336            if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw(
11337                    packageName, allHosts) != null) {
11338                scheduleWriteSettingsLocked();
11339            }
11340        }
11341    }
11342
11343    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11344        final ComponentName cn  = filter.activity.getComponentName();
11345        final String packageName = cn.getPackageName();
11346
11347        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11348                packageName);
11349        if (ivi == null) {
11350            return true;
11351        }
11352        int status = ivi.getStatus();
11353        switch (status) {
11354            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11355            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11356                return true;
11357
11358            default:
11359                // Nothing to do
11360                return false;
11361        }
11362    }
11363
11364    private static boolean isMultiArch(PackageSetting ps) {
11365        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11366    }
11367
11368    private static boolean isMultiArch(ApplicationInfo info) {
11369        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11370    }
11371
11372    private static boolean isExternal(PackageParser.Package pkg) {
11373        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11374    }
11375
11376    private static boolean isExternal(PackageSetting ps) {
11377        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11378    }
11379
11380    private static boolean isExternal(ApplicationInfo info) {
11381        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11382    }
11383
11384    private static boolean isSystemApp(PackageParser.Package pkg) {
11385        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11386    }
11387
11388    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11389        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11390    }
11391
11392    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11393        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11394    }
11395
11396    private static boolean isSystemApp(PackageSetting ps) {
11397        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11398    }
11399
11400    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11401        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11402    }
11403
11404    private int packageFlagsToInstallFlags(PackageSetting ps) {
11405        int installFlags = 0;
11406        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11407            // This existing package was an external ASEC install when we have
11408            // the external flag without a UUID
11409            installFlags |= PackageManager.INSTALL_EXTERNAL;
11410        }
11411        if (ps.isForwardLocked()) {
11412            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11413        }
11414        return installFlags;
11415    }
11416
11417    private void deleteTempPackageFiles() {
11418        final FilenameFilter filter = new FilenameFilter() {
11419            public boolean accept(File dir, String name) {
11420                return name.startsWith("vmdl") && name.endsWith(".tmp");
11421            }
11422        };
11423        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11424            file.delete();
11425        }
11426    }
11427
11428    @Override
11429    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11430            int flags) {
11431        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11432                flags);
11433    }
11434
11435    @Override
11436    public void deletePackage(final String packageName,
11437            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11438        mContext.enforceCallingOrSelfPermission(
11439                android.Manifest.permission.DELETE_PACKAGES, null);
11440        final int uid = Binder.getCallingUid();
11441        if (UserHandle.getUserId(uid) != userId) {
11442            mContext.enforceCallingPermission(
11443                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11444                    "deletePackage for user " + userId);
11445        }
11446        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11447            try {
11448                observer.onPackageDeleted(packageName,
11449                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11450            } catch (RemoteException re) {
11451            }
11452            return;
11453        }
11454
11455        boolean uninstallBlocked = false;
11456        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11457            int[] users = sUserManager.getUserIds();
11458            for (int i = 0; i < users.length; ++i) {
11459                if (getBlockUninstallForUser(packageName, users[i])) {
11460                    uninstallBlocked = true;
11461                    break;
11462                }
11463            }
11464        } else {
11465            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11466        }
11467        if (uninstallBlocked) {
11468            try {
11469                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11470                        null);
11471            } catch (RemoteException re) {
11472            }
11473            return;
11474        }
11475
11476        if (DEBUG_REMOVE) {
11477            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
11478        }
11479        // Queue up an async operation since the package deletion may take a little while.
11480        mHandler.post(new Runnable() {
11481            public void run() {
11482                mHandler.removeCallbacks(this);
11483                final int returnCode = deletePackageX(packageName, userId, flags);
11484                if (observer != null) {
11485                    try {
11486                        observer.onPackageDeleted(packageName, returnCode, null);
11487                    } catch (RemoteException e) {
11488                        Log.i(TAG, "Observer no longer exists.");
11489                    } //end catch
11490                } //end if
11491            } //end run
11492        });
11493    }
11494
11495    private boolean isPackageDeviceAdmin(String packageName, int userId) {
11496        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
11497                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
11498        try {
11499            if (dpm != null) {
11500                if (dpm.isDeviceOwner(packageName)) {
11501                    return true;
11502                }
11503                int[] users;
11504                if (userId == UserHandle.USER_ALL) {
11505                    users = sUserManager.getUserIds();
11506                } else {
11507                    users = new int[]{userId};
11508                }
11509                for (int i = 0; i < users.length; ++i) {
11510                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
11511                        return true;
11512                    }
11513                }
11514            }
11515        } catch (RemoteException e) {
11516        }
11517        return false;
11518    }
11519
11520    /**
11521     *  This method is an internal method that could be get invoked either
11522     *  to delete an installed package or to clean up a failed installation.
11523     *  After deleting an installed package, a broadcast is sent to notify any
11524     *  listeners that the package has been installed. For cleaning up a failed
11525     *  installation, the broadcast is not necessary since the package's
11526     *  installation wouldn't have sent the initial broadcast either
11527     *  The key steps in deleting a package are
11528     *  deleting the package information in internal structures like mPackages,
11529     *  deleting the packages base directories through installd
11530     *  updating mSettings to reflect current status
11531     *  persisting settings for later use
11532     *  sending a broadcast if necessary
11533     */
11534    private int deletePackageX(String packageName, int userId, int flags) {
11535        final PackageRemovedInfo info = new PackageRemovedInfo();
11536        final boolean res;
11537
11538        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
11539                ? UserHandle.ALL : new UserHandle(userId);
11540
11541        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
11542            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
11543            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
11544        }
11545
11546        boolean removedForAllUsers = false;
11547        boolean systemUpdate = false;
11548
11549        // for the uninstall-updates case and restricted profiles, remember the per-
11550        // userhandle installed state
11551        int[] allUsers;
11552        boolean[] perUserInstalled;
11553        synchronized (mPackages) {
11554            PackageSetting ps = mSettings.mPackages.get(packageName);
11555            allUsers = sUserManager.getUserIds();
11556            perUserInstalled = new boolean[allUsers.length];
11557            for (int i = 0; i < allUsers.length; i++) {
11558                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11559            }
11560        }
11561
11562        synchronized (mInstallLock) {
11563            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
11564            res = deletePackageLI(packageName, removeForUser,
11565                    true, allUsers, perUserInstalled,
11566                    flags | REMOVE_CHATTY, info, true);
11567            systemUpdate = info.isRemovedPackageSystemUpdate;
11568            if (res && !systemUpdate && mPackages.get(packageName) == null) {
11569                removedForAllUsers = true;
11570            }
11571            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
11572                    + " removedForAllUsers=" + removedForAllUsers);
11573        }
11574
11575        if (res) {
11576            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
11577
11578            // If the removed package was a system update, the old system package
11579            // was re-enabled; we need to broadcast this information
11580            if (systemUpdate) {
11581                Bundle extras = new Bundle(1);
11582                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
11583                        ? info.removedAppId : info.uid);
11584                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11585
11586                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
11587                        extras, null, null, null);
11588                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
11589                        extras, null, null, null);
11590                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
11591                        null, packageName, null, null);
11592            }
11593        }
11594        // Force a gc here.
11595        Runtime.getRuntime().gc();
11596        // Delete the resources here after sending the broadcast to let
11597        // other processes clean up before deleting resources.
11598        if (info.args != null) {
11599            synchronized (mInstallLock) {
11600                info.args.doPostDeleteLI(true);
11601            }
11602        }
11603
11604        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
11605    }
11606
11607    static class PackageRemovedInfo {
11608        String removedPackage;
11609        int uid = -1;
11610        int removedAppId = -1;
11611        int[] removedUsers = null;
11612        boolean isRemovedPackageSystemUpdate = false;
11613        // Clean up resources deleted packages.
11614        InstallArgs args = null;
11615
11616        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
11617            Bundle extras = new Bundle(1);
11618            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
11619            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
11620            if (replacing) {
11621                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11622            }
11623            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
11624            if (removedPackage != null) {
11625                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
11626                        extras, null, null, removedUsers);
11627                if (fullRemove && !replacing) {
11628                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
11629                            extras, null, null, removedUsers);
11630                }
11631            }
11632            if (removedAppId >= 0) {
11633                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
11634                        removedUsers);
11635            }
11636        }
11637    }
11638
11639    /*
11640     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
11641     * flag is not set, the data directory is removed as well.
11642     * make sure this flag is set for partially installed apps. If not its meaningless to
11643     * delete a partially installed application.
11644     */
11645    private void removePackageDataLI(PackageSetting ps,
11646            int[] allUserHandles, boolean[] perUserInstalled,
11647            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
11648        String packageName = ps.name;
11649        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
11650        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
11651        // Retrieve object to delete permissions for shared user later on
11652        final PackageSetting deletedPs;
11653        // reader
11654        synchronized (mPackages) {
11655            deletedPs = mSettings.mPackages.get(packageName);
11656            if (outInfo != null) {
11657                outInfo.removedPackage = packageName;
11658                outInfo.removedUsers = deletedPs != null
11659                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
11660                        : null;
11661            }
11662        }
11663        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11664            removeDataDirsLI(packageName);
11665            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
11666        }
11667        // writer
11668        synchronized (mPackages) {
11669            if (deletedPs != null) {
11670                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11671                    if (outInfo != null) {
11672                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
11673                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
11674                    }
11675                    updatePermissionsLPw(deletedPs.name, null, 0);
11676                    if (deletedPs.sharedUser != null) {
11677                        // Remove permissions associated with package. Since runtime
11678                        // permissions are per user we have to kill the removed package
11679                        // or packages running under the shared user of the removed
11680                        // package if revoking the permissions requested only by the removed
11681                        // package is successful and this causes a change in gids.
11682                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11683                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
11684                                    userId);
11685                            if (userIdToKill == UserHandle.USER_ALL
11686                                    || userIdToKill >= UserHandle.USER_OWNER) {
11687                                // If gids changed for this user, kill all affected packages.
11688                                mHandler.post(new Runnable() {
11689                                    @Override
11690                                    public void run() {
11691                                        // This has to happen with no lock held.
11692                                        killSettingPackagesForUser(deletedPs, userIdToKill,
11693                                                KILL_APP_REASON_GIDS_CHANGED);
11694                                    }
11695                                });
11696                            break;
11697                            }
11698                        }
11699                    }
11700                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
11701                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
11702                }
11703                // make sure to preserve per-user disabled state if this removal was just
11704                // a downgrade of a system app to the factory package
11705                if (allUserHandles != null && perUserInstalled != null) {
11706                    if (DEBUG_REMOVE) {
11707                        Slog.d(TAG, "Propagating install state across downgrade");
11708                    }
11709                    for (int i = 0; i < allUserHandles.length; i++) {
11710                        if (DEBUG_REMOVE) {
11711                            Slog.d(TAG, "    user " + allUserHandles[i]
11712                                    + " => " + perUserInstalled[i]);
11713                        }
11714                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11715                    }
11716                }
11717            }
11718            // can downgrade to reader
11719            if (writeSettings) {
11720                // Save settings now
11721                mSettings.writeLPr();
11722            }
11723        }
11724        if (outInfo != null) {
11725            // A user ID was deleted here. Go through all users and remove it
11726            // from KeyStore.
11727            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
11728        }
11729    }
11730
11731    static boolean locationIsPrivileged(File path) {
11732        try {
11733            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
11734                    .getCanonicalPath();
11735            return path.getCanonicalPath().startsWith(privilegedAppDir);
11736        } catch (IOException e) {
11737            Slog.e(TAG, "Unable to access code path " + path);
11738        }
11739        return false;
11740    }
11741
11742    /*
11743     * Tries to delete system package.
11744     */
11745    private boolean deleteSystemPackageLI(PackageSetting newPs,
11746            int[] allUserHandles, boolean[] perUserInstalled,
11747            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
11748        final boolean applyUserRestrictions
11749                = (allUserHandles != null) && (perUserInstalled != null);
11750        PackageSetting disabledPs = null;
11751        // Confirm if the system package has been updated
11752        // An updated system app can be deleted. This will also have to restore
11753        // the system pkg from system partition
11754        // reader
11755        synchronized (mPackages) {
11756            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
11757        }
11758        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
11759                + " disabledPs=" + disabledPs);
11760        if (disabledPs == null) {
11761            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
11762            return false;
11763        } else if (DEBUG_REMOVE) {
11764            Slog.d(TAG, "Deleting system pkg from data partition");
11765        }
11766        if (DEBUG_REMOVE) {
11767            if (applyUserRestrictions) {
11768                Slog.d(TAG, "Remembering install states:");
11769                for (int i = 0; i < allUserHandles.length; i++) {
11770                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
11771                }
11772            }
11773        }
11774        // Delete the updated package
11775        outInfo.isRemovedPackageSystemUpdate = true;
11776        if (disabledPs.versionCode < newPs.versionCode) {
11777            // Delete data for downgrades
11778            flags &= ~PackageManager.DELETE_KEEP_DATA;
11779        } else {
11780            // Preserve data by setting flag
11781            flags |= PackageManager.DELETE_KEEP_DATA;
11782        }
11783        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
11784                allUserHandles, perUserInstalled, outInfo, writeSettings);
11785        if (!ret) {
11786            return false;
11787        }
11788        // writer
11789        synchronized (mPackages) {
11790            // Reinstate the old system package
11791            mSettings.enableSystemPackageLPw(newPs.name);
11792            // Remove any native libraries from the upgraded package.
11793            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
11794        }
11795        // Install the system package
11796        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
11797        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
11798        if (locationIsPrivileged(disabledPs.codePath)) {
11799            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11800        }
11801
11802        final PackageParser.Package newPkg;
11803        try {
11804            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
11805        } catch (PackageManagerException e) {
11806            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
11807            return false;
11808        }
11809
11810        // writer
11811        synchronized (mPackages) {
11812            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
11813            updatePermissionsLPw(newPkg.packageName, newPkg,
11814                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
11815            if (applyUserRestrictions) {
11816                if (DEBUG_REMOVE) {
11817                    Slog.d(TAG, "Propagating install state across reinstall");
11818                }
11819                for (int i = 0; i < allUserHandles.length; i++) {
11820                    if (DEBUG_REMOVE) {
11821                        Slog.d(TAG, "    user " + allUserHandles[i]
11822                                + " => " + perUserInstalled[i]);
11823                    }
11824                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11825                }
11826                // Regardless of writeSettings we need to ensure that this restriction
11827                // state propagation is persisted
11828                mSettings.writeAllUsersPackageRestrictionsLPr();
11829            }
11830            // can downgrade to reader here
11831            if (writeSettings) {
11832                mSettings.writeLPr();
11833            }
11834        }
11835        return true;
11836    }
11837
11838    private boolean deleteInstalledPackageLI(PackageSetting ps,
11839            boolean deleteCodeAndResources, int flags,
11840            int[] allUserHandles, boolean[] perUserInstalled,
11841            PackageRemovedInfo outInfo, boolean writeSettings) {
11842        if (outInfo != null) {
11843            outInfo.uid = ps.appId;
11844        }
11845
11846        // Delete package data from internal structures and also remove data if flag is set
11847        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
11848
11849        // Delete application code and resources
11850        if (deleteCodeAndResources && (outInfo != null)) {
11851            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
11852                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
11853                    getAppDexInstructionSets(ps));
11854            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
11855        }
11856        return true;
11857    }
11858
11859    @Override
11860    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
11861            int userId) {
11862        mContext.enforceCallingOrSelfPermission(
11863                android.Manifest.permission.DELETE_PACKAGES, null);
11864        synchronized (mPackages) {
11865            PackageSetting ps = mSettings.mPackages.get(packageName);
11866            if (ps == null) {
11867                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
11868                return false;
11869            }
11870            if (!ps.getInstalled(userId)) {
11871                // Can't block uninstall for an app that is not installed or enabled.
11872                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11873                return false;
11874            }
11875            ps.setBlockUninstall(blockUninstall, userId);
11876            mSettings.writePackageRestrictionsLPr(userId);
11877        }
11878        return true;
11879    }
11880
11881    @Override
11882    public boolean getBlockUninstallForUser(String packageName, int userId) {
11883        synchronized (mPackages) {
11884            PackageSetting ps = mSettings.mPackages.get(packageName);
11885            if (ps == null) {
11886                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11887                return false;
11888            }
11889            return ps.getBlockUninstall(userId);
11890        }
11891    }
11892
11893    /*
11894     * This method handles package deletion in general
11895     */
11896    private boolean deletePackageLI(String packageName, UserHandle user,
11897            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11898            int flags, PackageRemovedInfo outInfo,
11899            boolean writeSettings) {
11900        if (packageName == null) {
11901            Slog.w(TAG, "Attempt to delete null packageName.");
11902            return false;
11903        }
11904        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11905        PackageSetting ps;
11906        boolean dataOnly = false;
11907        int removeUser = -1;
11908        int appId = -1;
11909        synchronized (mPackages) {
11910            ps = mSettings.mPackages.get(packageName);
11911            if (ps == null) {
11912                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11913                return false;
11914            }
11915            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11916                    && user.getIdentifier() != UserHandle.USER_ALL) {
11917                // The caller is asking that the package only be deleted for a single
11918                // user.  To do this, we just mark its uninstalled state and delete
11919                // its data.  If this is a system app, we only allow this to happen if
11920                // they have set the special DELETE_SYSTEM_APP which requests different
11921                // semantics than normal for uninstalling system apps.
11922                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11923                ps.setUserState(user.getIdentifier(),
11924                        COMPONENT_ENABLED_STATE_DEFAULT,
11925                        false, //installed
11926                        true,  //stopped
11927                        true,  //notLaunched
11928                        false, //hidden
11929                        null, null, null,
11930                        false, // blockUninstall
11931                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
11932                if (!isSystemApp(ps)) {
11933                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11934                        // Other user still have this package installed, so all
11935                        // we need to do is clear this user's data and save that
11936                        // it is uninstalled.
11937                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11938                        removeUser = user.getIdentifier();
11939                        appId = ps.appId;
11940                        mSettings.writePackageRestrictionsLPr(removeUser);
11941                    } else {
11942                        // We need to set it back to 'installed' so the uninstall
11943                        // broadcasts will be sent correctly.
11944                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11945                        ps.setInstalled(true, user.getIdentifier());
11946                    }
11947                } else {
11948                    // This is a system app, so we assume that the
11949                    // other users still have this package installed, so all
11950                    // we need to do is clear this user's data and save that
11951                    // it is uninstalled.
11952                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11953                    removeUser = user.getIdentifier();
11954                    appId = ps.appId;
11955                    mSettings.writePackageRestrictionsLPr(removeUser);
11956                }
11957            }
11958        }
11959
11960        if (removeUser >= 0) {
11961            // From above, we determined that we are deleting this only
11962            // for a single user.  Continue the work here.
11963            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11964            if (outInfo != null) {
11965                outInfo.removedPackage = packageName;
11966                outInfo.removedAppId = appId;
11967                outInfo.removedUsers = new int[] {removeUser};
11968            }
11969            mInstaller.clearUserData(packageName, removeUser);
11970            removeKeystoreDataIfNeeded(removeUser, appId);
11971            schedulePackageCleaning(packageName, removeUser, false);
11972            return true;
11973        }
11974
11975        if (dataOnly) {
11976            // Delete application data first
11977            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11978            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11979            return true;
11980        }
11981
11982        boolean ret = false;
11983        if (isSystemApp(ps)) {
11984            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11985            // When an updated system application is deleted we delete the existing resources as well and
11986            // fall back to existing code in system partition
11987            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11988                    flags, outInfo, writeSettings);
11989        } else {
11990            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11991            // Kill application pre-emptively especially for apps on sd.
11992            killApplication(packageName, ps.appId, "uninstall pkg");
11993            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11994                    allUserHandles, perUserInstalled,
11995                    outInfo, writeSettings);
11996        }
11997
11998        return ret;
11999    }
12000
12001    private final class ClearStorageConnection implements ServiceConnection {
12002        IMediaContainerService mContainerService;
12003
12004        @Override
12005        public void onServiceConnected(ComponentName name, IBinder service) {
12006            synchronized (this) {
12007                mContainerService = IMediaContainerService.Stub.asInterface(service);
12008                notifyAll();
12009            }
12010        }
12011
12012        @Override
12013        public void onServiceDisconnected(ComponentName name) {
12014        }
12015    }
12016
12017    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12018        final boolean mounted;
12019        if (Environment.isExternalStorageEmulated()) {
12020            mounted = true;
12021        } else {
12022            final String status = Environment.getExternalStorageState();
12023
12024            mounted = status.equals(Environment.MEDIA_MOUNTED)
12025                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12026        }
12027
12028        if (!mounted) {
12029            return;
12030        }
12031
12032        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12033        int[] users;
12034        if (userId == UserHandle.USER_ALL) {
12035            users = sUserManager.getUserIds();
12036        } else {
12037            users = new int[] { userId };
12038        }
12039        final ClearStorageConnection conn = new ClearStorageConnection();
12040        if (mContext.bindServiceAsUser(
12041                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12042            try {
12043                for (int curUser : users) {
12044                    long timeout = SystemClock.uptimeMillis() + 5000;
12045                    synchronized (conn) {
12046                        long now = SystemClock.uptimeMillis();
12047                        while (conn.mContainerService == null && now < timeout) {
12048                            try {
12049                                conn.wait(timeout - now);
12050                            } catch (InterruptedException e) {
12051                            }
12052                        }
12053                    }
12054                    if (conn.mContainerService == null) {
12055                        return;
12056                    }
12057
12058                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12059                    clearDirectory(conn.mContainerService,
12060                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12061                    if (allData) {
12062                        clearDirectory(conn.mContainerService,
12063                                userEnv.buildExternalStorageAppDataDirs(packageName));
12064                        clearDirectory(conn.mContainerService,
12065                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12066                    }
12067                }
12068            } finally {
12069                mContext.unbindService(conn);
12070            }
12071        }
12072    }
12073
12074    @Override
12075    public void clearApplicationUserData(final String packageName,
12076            final IPackageDataObserver observer, final int userId) {
12077        mContext.enforceCallingOrSelfPermission(
12078                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12079        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12080        // Queue up an async operation since the package deletion may take a little while.
12081        mHandler.post(new Runnable() {
12082            public void run() {
12083                mHandler.removeCallbacks(this);
12084                final boolean succeeded;
12085                synchronized (mInstallLock) {
12086                    succeeded = clearApplicationUserDataLI(packageName, userId);
12087                }
12088                clearExternalStorageDataSync(packageName, userId, true);
12089                if (succeeded) {
12090                    // invoke DeviceStorageMonitor's update method to clear any notifications
12091                    DeviceStorageMonitorInternal
12092                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12093                    if (dsm != null) {
12094                        dsm.checkMemory();
12095                    }
12096                }
12097                if(observer != null) {
12098                    try {
12099                        observer.onRemoveCompleted(packageName, succeeded);
12100                    } catch (RemoteException e) {
12101                        Log.i(TAG, "Observer no longer exists.");
12102                    }
12103                } //end if observer
12104            } //end run
12105        });
12106    }
12107
12108    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12109        if (packageName == null) {
12110            Slog.w(TAG, "Attempt to delete null packageName.");
12111            return false;
12112        }
12113
12114        // Try finding details about the requested package
12115        PackageParser.Package pkg;
12116        synchronized (mPackages) {
12117            pkg = mPackages.get(packageName);
12118            if (pkg == null) {
12119                final PackageSetting ps = mSettings.mPackages.get(packageName);
12120                if (ps != null) {
12121                    pkg = ps.pkg;
12122                }
12123            }
12124        }
12125
12126        if (pkg == null) {
12127            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12128        }
12129
12130        // Always delete data directories for package, even if we found no other
12131        // record of app. This helps users recover from UID mismatches without
12132        // resorting to a full data wipe.
12133        int retCode = mInstaller.clearUserData(packageName, userId);
12134        if (retCode < 0) {
12135            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12136            return false;
12137        }
12138
12139        if (pkg == null) {
12140            return false;
12141        }
12142
12143        if (pkg != null && pkg.applicationInfo != null) {
12144            final int appId = pkg.applicationInfo.uid;
12145            removeKeystoreDataIfNeeded(userId, appId);
12146        }
12147
12148        // Create a native library symlink only if we have native libraries
12149        // and if the native libraries are 32 bit libraries. We do not provide
12150        // this symlink for 64 bit libraries.
12151        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
12152                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12153            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12154            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
12155                Slog.w(TAG, "Failed linking native library dir");
12156                return false;
12157            }
12158        }
12159
12160        return true;
12161    }
12162
12163    /**
12164     * Remove entries from the keystore daemon. Will only remove it if the
12165     * {@code appId} is valid.
12166     */
12167    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12168        if (appId < 0) {
12169            return;
12170        }
12171
12172        final KeyStore keyStore = KeyStore.getInstance();
12173        if (keyStore != null) {
12174            if (userId == UserHandle.USER_ALL) {
12175                for (final int individual : sUserManager.getUserIds()) {
12176                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12177                }
12178            } else {
12179                keyStore.clearUid(UserHandle.getUid(userId, appId));
12180            }
12181        } else {
12182            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12183        }
12184    }
12185
12186    @Override
12187    public void deleteApplicationCacheFiles(final String packageName,
12188            final IPackageDataObserver observer) {
12189        mContext.enforceCallingOrSelfPermission(
12190                android.Manifest.permission.DELETE_CACHE_FILES, null);
12191        // Queue up an async operation since the package deletion may take a little while.
12192        final int userId = UserHandle.getCallingUserId();
12193        mHandler.post(new Runnable() {
12194            public void run() {
12195                mHandler.removeCallbacks(this);
12196                final boolean succeded;
12197                synchronized (mInstallLock) {
12198                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12199                }
12200                clearExternalStorageDataSync(packageName, userId, false);
12201                if(observer != null) {
12202                    try {
12203                        observer.onRemoveCompleted(packageName, succeded);
12204                    } catch (RemoteException e) {
12205                        Log.i(TAG, "Observer no longer exists.");
12206                    }
12207                } //end if observer
12208            } //end run
12209        });
12210    }
12211
12212    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12213        if (packageName == null) {
12214            Slog.w(TAG, "Attempt to delete null packageName.");
12215            return false;
12216        }
12217        PackageParser.Package p;
12218        synchronized (mPackages) {
12219            p = mPackages.get(packageName);
12220        }
12221        if (p == null) {
12222            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12223            return false;
12224        }
12225        final ApplicationInfo applicationInfo = p.applicationInfo;
12226        if (applicationInfo == null) {
12227            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12228            return false;
12229        }
12230        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
12231        if (retCode < 0) {
12232            Slog.w(TAG, "Couldn't remove cache files for package: "
12233                       + packageName + " u" + userId);
12234            return false;
12235        }
12236        return true;
12237    }
12238
12239    @Override
12240    public void getPackageSizeInfo(final String packageName, int userHandle,
12241            final IPackageStatsObserver observer) {
12242        mContext.enforceCallingOrSelfPermission(
12243                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12244        if (packageName == null) {
12245            throw new IllegalArgumentException("Attempt to get size of null packageName");
12246        }
12247
12248        PackageStats stats = new PackageStats(packageName, userHandle);
12249
12250        /*
12251         * Queue up an async operation since the package measurement may take a
12252         * little while.
12253         */
12254        Message msg = mHandler.obtainMessage(INIT_COPY);
12255        msg.obj = new MeasureParams(stats, observer);
12256        mHandler.sendMessage(msg);
12257    }
12258
12259    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12260            PackageStats pStats) {
12261        if (packageName == null) {
12262            Slog.w(TAG, "Attempt to get size of null packageName.");
12263            return false;
12264        }
12265        PackageParser.Package p;
12266        boolean dataOnly = false;
12267        String libDirRoot = null;
12268        String asecPath = null;
12269        PackageSetting ps = null;
12270        synchronized (mPackages) {
12271            p = mPackages.get(packageName);
12272            ps = mSettings.mPackages.get(packageName);
12273            if(p == null) {
12274                dataOnly = true;
12275                if((ps == null) || (ps.pkg == null)) {
12276                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12277                    return false;
12278                }
12279                p = ps.pkg;
12280            }
12281            if (ps != null) {
12282                libDirRoot = ps.legacyNativeLibraryPathString;
12283            }
12284            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12285                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12286                if (secureContainerId != null) {
12287                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12288                }
12289            }
12290        }
12291        String publicSrcDir = null;
12292        if(!dataOnly) {
12293            final ApplicationInfo applicationInfo = p.applicationInfo;
12294            if (applicationInfo == null) {
12295                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12296                return false;
12297            }
12298            if (p.isForwardLocked()) {
12299                publicSrcDir = applicationInfo.getBaseResourcePath();
12300            }
12301        }
12302        // TODO: extend to measure size of split APKs
12303        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12304        // not just the first level.
12305        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12306        // just the primary.
12307        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12308        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
12309                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12310        if (res < 0) {
12311            return false;
12312        }
12313
12314        // Fix-up for forward-locked applications in ASEC containers.
12315        if (!isExternal(p)) {
12316            pStats.codeSize += pStats.externalCodeSize;
12317            pStats.externalCodeSize = 0L;
12318        }
12319
12320        return true;
12321    }
12322
12323
12324    @Override
12325    public void addPackageToPreferred(String packageName) {
12326        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12327    }
12328
12329    @Override
12330    public void removePackageFromPreferred(String packageName) {
12331        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12332    }
12333
12334    @Override
12335    public List<PackageInfo> getPreferredPackages(int flags) {
12336        return new ArrayList<PackageInfo>();
12337    }
12338
12339    private int getUidTargetSdkVersionLockedLPr(int uid) {
12340        Object obj = mSettings.getUserIdLPr(uid);
12341        if (obj instanceof SharedUserSetting) {
12342            final SharedUserSetting sus = (SharedUserSetting) obj;
12343            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12344            final Iterator<PackageSetting> it = sus.packages.iterator();
12345            while (it.hasNext()) {
12346                final PackageSetting ps = it.next();
12347                if (ps.pkg != null) {
12348                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12349                    if (v < vers) vers = v;
12350                }
12351            }
12352            return vers;
12353        } else if (obj instanceof PackageSetting) {
12354            final PackageSetting ps = (PackageSetting) obj;
12355            if (ps.pkg != null) {
12356                return ps.pkg.applicationInfo.targetSdkVersion;
12357            }
12358        }
12359        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12360    }
12361
12362    @Override
12363    public void addPreferredActivity(IntentFilter filter, int match,
12364            ComponentName[] set, ComponentName activity, int userId) {
12365        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12366                "Adding preferred");
12367    }
12368
12369    private void addPreferredActivityInternal(IntentFilter filter, int match,
12370            ComponentName[] set, ComponentName activity, boolean always, int userId,
12371            String opname) {
12372        // writer
12373        int callingUid = Binder.getCallingUid();
12374        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12375        if (filter.countActions() == 0) {
12376            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12377            return;
12378        }
12379        synchronized (mPackages) {
12380            if (mContext.checkCallingOrSelfPermission(
12381                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12382                    != PackageManager.PERMISSION_GRANTED) {
12383                if (getUidTargetSdkVersionLockedLPr(callingUid)
12384                        < Build.VERSION_CODES.FROYO) {
12385                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12386                            + callingUid);
12387                    return;
12388                }
12389                mContext.enforceCallingOrSelfPermission(
12390                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12391            }
12392
12393            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12394            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12395                    + userId + ":");
12396            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12397            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12398            scheduleWritePackageRestrictionsLocked(userId);
12399        }
12400    }
12401
12402    @Override
12403    public void replacePreferredActivity(IntentFilter filter, int match,
12404            ComponentName[] set, ComponentName activity, int userId) {
12405        if (filter.countActions() != 1) {
12406            throw new IllegalArgumentException(
12407                    "replacePreferredActivity expects filter to have only 1 action.");
12408        }
12409        if (filter.countDataAuthorities() != 0
12410                || filter.countDataPaths() != 0
12411                || filter.countDataSchemes() > 1
12412                || filter.countDataTypes() != 0) {
12413            throw new IllegalArgumentException(
12414                    "replacePreferredActivity expects filter to have no data authorities, " +
12415                    "paths, or types; and at most one scheme.");
12416        }
12417
12418        final int callingUid = Binder.getCallingUid();
12419        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12420        synchronized (mPackages) {
12421            if (mContext.checkCallingOrSelfPermission(
12422                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12423                    != PackageManager.PERMISSION_GRANTED) {
12424                if (getUidTargetSdkVersionLockedLPr(callingUid)
12425                        < Build.VERSION_CODES.FROYO) {
12426                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12427                            + Binder.getCallingUid());
12428                    return;
12429                }
12430                mContext.enforceCallingOrSelfPermission(
12431                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12432            }
12433
12434            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12435            if (pir != null) {
12436                // Get all of the existing entries that exactly match this filter.
12437                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
12438                if (existing != null && existing.size() == 1) {
12439                    PreferredActivity cur = existing.get(0);
12440                    if (DEBUG_PREFERRED) {
12441                        Slog.i(TAG, "Checking replace of preferred:");
12442                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12443                        if (!cur.mPref.mAlways) {
12444                            Slog.i(TAG, "  -- CUR; not mAlways!");
12445                        } else {
12446                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
12447                            Slog.i(TAG, "  -- CUR: mSet="
12448                                    + Arrays.toString(cur.mPref.mSetComponents));
12449                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
12450                            Slog.i(TAG, "  -- NEW: mMatch="
12451                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
12452                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
12453                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
12454                        }
12455                    }
12456                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
12457                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
12458                            && cur.mPref.sameSet(set)) {
12459                        // Setting the preferred activity to what it happens to be already
12460                        if (DEBUG_PREFERRED) {
12461                            Slog.i(TAG, "Replacing with same preferred activity "
12462                                    + cur.mPref.mShortComponent + " for user "
12463                                    + userId + ":");
12464                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12465                        }
12466                        return;
12467                    }
12468                }
12469
12470                if (existing != null) {
12471                    if (DEBUG_PREFERRED) {
12472                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
12473                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12474                    }
12475                    for (int i = 0; i < existing.size(); i++) {
12476                        PreferredActivity pa = existing.get(i);
12477                        if (DEBUG_PREFERRED) {
12478                            Slog.i(TAG, "Removing existing preferred activity "
12479                                    + pa.mPref.mComponent + ":");
12480                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
12481                        }
12482                        pir.removeFilter(pa);
12483                    }
12484                }
12485            }
12486            addPreferredActivityInternal(filter, match, set, activity, true, userId,
12487                    "Replacing preferred");
12488        }
12489    }
12490
12491    @Override
12492    public void clearPackagePreferredActivities(String packageName) {
12493        final int uid = Binder.getCallingUid();
12494        // writer
12495        synchronized (mPackages) {
12496            PackageParser.Package pkg = mPackages.get(packageName);
12497            if (pkg == null || pkg.applicationInfo.uid != uid) {
12498                if (mContext.checkCallingOrSelfPermission(
12499                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12500                        != PackageManager.PERMISSION_GRANTED) {
12501                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
12502                            < Build.VERSION_CODES.FROYO) {
12503                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
12504                                + Binder.getCallingUid());
12505                        return;
12506                    }
12507                    mContext.enforceCallingOrSelfPermission(
12508                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12509                }
12510            }
12511
12512            int user = UserHandle.getCallingUserId();
12513            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
12514                scheduleWritePackageRestrictionsLocked(user);
12515            }
12516        }
12517    }
12518
12519    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12520    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
12521        ArrayList<PreferredActivity> removed = null;
12522        boolean changed = false;
12523        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12524            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
12525            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12526            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
12527                continue;
12528            }
12529            Iterator<PreferredActivity> it = pir.filterIterator();
12530            while (it.hasNext()) {
12531                PreferredActivity pa = it.next();
12532                // Mark entry for removal only if it matches the package name
12533                // and the entry is of type "always".
12534                if (packageName == null ||
12535                        (pa.mPref.mComponent.getPackageName().equals(packageName)
12536                                && pa.mPref.mAlways)) {
12537                    if (removed == null) {
12538                        removed = new ArrayList<PreferredActivity>();
12539                    }
12540                    removed.add(pa);
12541                }
12542            }
12543            if (removed != null) {
12544                for (int j=0; j<removed.size(); j++) {
12545                    PreferredActivity pa = removed.get(j);
12546                    pir.removeFilter(pa);
12547                }
12548                changed = true;
12549            }
12550        }
12551        return changed;
12552    }
12553
12554    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12555    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
12556        if (userId == UserHandle.USER_ALL) {
12557            mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds());
12558            for (int oneUserId : sUserManager.getUserIds()) {
12559                scheduleWritePackageRestrictionsLocked(oneUserId);
12560            }
12561        } else {
12562            mSettings.removeIntentFilterVerificationLPw(packageName, userId);
12563            scheduleWritePackageRestrictionsLocked(userId);
12564        }
12565    }
12566
12567    @Override
12568    public void resetPreferredActivities(int userId) {
12569        /* TODO: Actually use userId. Why is it being passed in? */
12570        mContext.enforceCallingOrSelfPermission(
12571                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12572        // writer
12573        synchronized (mPackages) {
12574            int user = UserHandle.getCallingUserId();
12575            clearPackagePreferredActivitiesLPw(null, user);
12576            mSettings.readDefaultPreferredAppsLPw(this, user);
12577            scheduleWritePackageRestrictionsLocked(user);
12578        }
12579    }
12580
12581    @Override
12582    public int getPreferredActivities(List<IntentFilter> outFilters,
12583            List<ComponentName> outActivities, String packageName) {
12584
12585        int num = 0;
12586        final int userId = UserHandle.getCallingUserId();
12587        // reader
12588        synchronized (mPackages) {
12589            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12590            if (pir != null) {
12591                final Iterator<PreferredActivity> it = pir.filterIterator();
12592                while (it.hasNext()) {
12593                    final PreferredActivity pa = it.next();
12594                    if (packageName == null
12595                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
12596                                    && pa.mPref.mAlways)) {
12597                        if (outFilters != null) {
12598                            outFilters.add(new IntentFilter(pa));
12599                        }
12600                        if (outActivities != null) {
12601                            outActivities.add(pa.mPref.mComponent);
12602                        }
12603                    }
12604                }
12605            }
12606        }
12607
12608        return num;
12609    }
12610
12611    @Override
12612    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
12613            int userId) {
12614        int callingUid = Binder.getCallingUid();
12615        if (callingUid != Process.SYSTEM_UID) {
12616            throw new SecurityException(
12617                    "addPersistentPreferredActivity can only be run by the system");
12618        }
12619        if (filter.countActions() == 0) {
12620            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12621            return;
12622        }
12623        synchronized (mPackages) {
12624            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
12625                    " :");
12626            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12627            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
12628                    new PersistentPreferredActivity(filter, activity));
12629            scheduleWritePackageRestrictionsLocked(userId);
12630        }
12631    }
12632
12633    @Override
12634    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
12635        int callingUid = Binder.getCallingUid();
12636        if (callingUid != Process.SYSTEM_UID) {
12637            throw new SecurityException(
12638                    "clearPackagePersistentPreferredActivities can only be run by the system");
12639        }
12640        ArrayList<PersistentPreferredActivity> removed = null;
12641        boolean changed = false;
12642        synchronized (mPackages) {
12643            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
12644                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
12645                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
12646                        .valueAt(i);
12647                if (userId != thisUserId) {
12648                    continue;
12649                }
12650                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
12651                while (it.hasNext()) {
12652                    PersistentPreferredActivity ppa = it.next();
12653                    // Mark entry for removal only if it matches the package name.
12654                    if (ppa.mComponent.getPackageName().equals(packageName)) {
12655                        if (removed == null) {
12656                            removed = new ArrayList<PersistentPreferredActivity>();
12657                        }
12658                        removed.add(ppa);
12659                    }
12660                }
12661                if (removed != null) {
12662                    for (int j=0; j<removed.size(); j++) {
12663                        PersistentPreferredActivity ppa = removed.get(j);
12664                        ppir.removeFilter(ppa);
12665                    }
12666                    changed = true;
12667                }
12668            }
12669
12670            if (changed) {
12671                scheduleWritePackageRestrictionsLocked(userId);
12672            }
12673        }
12674    }
12675
12676    /**
12677     * Non-Binder method, support for the backup/restore mechanism: write the
12678     * full set of preferred activities in its canonical XML format.  Returns true
12679     * on success; false otherwise.
12680     */
12681    @Override
12682    public byte[] getPreferredActivityBackup(int userId) {
12683        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
12684            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
12685        }
12686
12687        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
12688        try {
12689            final XmlSerializer serializer = new FastXmlSerializer();
12690            serializer.setOutput(dataStream, "utf-8");
12691            serializer.startDocument(null, true);
12692            serializer.startTag(null, TAG_PREFERRED_BACKUP);
12693
12694            synchronized (mPackages) {
12695                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
12696            }
12697
12698            serializer.endTag(null, TAG_PREFERRED_BACKUP);
12699            serializer.endDocument();
12700            serializer.flush();
12701        } catch (Exception e) {
12702            if (DEBUG_BACKUP) {
12703                Slog.e(TAG, "Unable to write preferred activities for backup", e);
12704            }
12705            return null;
12706        }
12707
12708        return dataStream.toByteArray();
12709    }
12710
12711    @Override
12712    public void restorePreferredActivities(byte[] backup, int userId) {
12713        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
12714            throw new SecurityException("Only the system may call restorePreferredActivities()");
12715        }
12716
12717        try {
12718            final XmlPullParser parser = Xml.newPullParser();
12719            parser.setInput(new ByteArrayInputStream(backup), null);
12720
12721            int type;
12722            while ((type = parser.next()) != XmlPullParser.START_TAG
12723                    && type != XmlPullParser.END_DOCUMENT) {
12724            }
12725            if (type != XmlPullParser.START_TAG) {
12726                // oops didn't find a start tag?!
12727                if (DEBUG_BACKUP) {
12728                    Slog.e(TAG, "Didn't find start tag during restore");
12729                }
12730                return;
12731            }
12732
12733            // this is supposed to be TAG_PREFERRED_BACKUP
12734            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
12735                if (DEBUG_BACKUP) {
12736                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
12737                }
12738                return;
12739            }
12740
12741            // skip interfering stuff, then we're aligned with the backing implementation
12742            while ((type = parser.next()) == XmlPullParser.TEXT) { }
12743            synchronized (mPackages) {
12744                mSettings.readPreferredActivitiesLPw(parser, userId);
12745            }
12746        } catch (Exception e) {
12747            if (DEBUG_BACKUP) {
12748                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
12749            }
12750        }
12751    }
12752
12753    @Override
12754    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
12755            int sourceUserId, int targetUserId, int flags) {
12756        mContext.enforceCallingOrSelfPermission(
12757                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12758        int callingUid = Binder.getCallingUid();
12759        enforceOwnerRights(ownerPackage, callingUid);
12760        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12761        if (intentFilter.countActions() == 0) {
12762            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
12763            return;
12764        }
12765        synchronized (mPackages) {
12766            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
12767                    ownerPackage, targetUserId, flags);
12768            CrossProfileIntentResolver resolver =
12769                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12770            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
12771            // We have all those whose filter is equal. Now checking if the rest is equal as well.
12772            if (existing != null) {
12773                int size = existing.size();
12774                for (int i = 0; i < size; i++) {
12775                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
12776                        return;
12777                    }
12778                }
12779            }
12780            resolver.addFilter(newFilter);
12781            scheduleWritePackageRestrictionsLocked(sourceUserId);
12782        }
12783    }
12784
12785    @Override
12786    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
12787        mContext.enforceCallingOrSelfPermission(
12788                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12789        int callingUid = Binder.getCallingUid();
12790        enforceOwnerRights(ownerPackage, callingUid);
12791        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12792        synchronized (mPackages) {
12793            CrossProfileIntentResolver resolver =
12794                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12795            ArraySet<CrossProfileIntentFilter> set =
12796                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
12797            for (CrossProfileIntentFilter filter : set) {
12798                if (filter.getOwnerPackage().equals(ownerPackage)) {
12799                    resolver.removeFilter(filter);
12800                }
12801            }
12802            scheduleWritePackageRestrictionsLocked(sourceUserId);
12803        }
12804    }
12805
12806    // Enforcing that callingUid is owning pkg on userId
12807    private void enforceOwnerRights(String pkg, int callingUid) {
12808        // The system owns everything.
12809        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
12810            return;
12811        }
12812        int callingUserId = UserHandle.getUserId(callingUid);
12813        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
12814        if (pi == null) {
12815            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
12816                    + callingUserId);
12817        }
12818        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
12819            throw new SecurityException("Calling uid " + callingUid
12820                    + " does not own package " + pkg);
12821        }
12822    }
12823
12824    @Override
12825    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
12826        Intent intent = new Intent(Intent.ACTION_MAIN);
12827        intent.addCategory(Intent.CATEGORY_HOME);
12828
12829        final int callingUserId = UserHandle.getCallingUserId();
12830        List<ResolveInfo> list = queryIntentActivities(intent, null,
12831                PackageManager.GET_META_DATA, callingUserId);
12832        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
12833                true, false, false, callingUserId);
12834
12835        allHomeCandidates.clear();
12836        if (list != null) {
12837            for (ResolveInfo ri : list) {
12838                allHomeCandidates.add(ri);
12839            }
12840        }
12841        return (preferred == null || preferred.activityInfo == null)
12842                ? null
12843                : new ComponentName(preferred.activityInfo.packageName,
12844                        preferred.activityInfo.name);
12845    }
12846
12847    @Override
12848    public void setApplicationEnabledSetting(String appPackageName,
12849            int newState, int flags, int userId, String callingPackage) {
12850        if (!sUserManager.exists(userId)) return;
12851        if (callingPackage == null) {
12852            callingPackage = Integer.toString(Binder.getCallingUid());
12853        }
12854        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
12855    }
12856
12857    @Override
12858    public void setComponentEnabledSetting(ComponentName componentName,
12859            int newState, int flags, int userId) {
12860        if (!sUserManager.exists(userId)) return;
12861        setEnabledSetting(componentName.getPackageName(),
12862                componentName.getClassName(), newState, flags, userId, null);
12863    }
12864
12865    private void setEnabledSetting(final String packageName, String className, int newState,
12866            final int flags, int userId, String callingPackage) {
12867        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
12868              || newState == COMPONENT_ENABLED_STATE_ENABLED
12869              || newState == COMPONENT_ENABLED_STATE_DISABLED
12870              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
12871              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
12872            throw new IllegalArgumentException("Invalid new component state: "
12873                    + newState);
12874        }
12875        PackageSetting pkgSetting;
12876        final int uid = Binder.getCallingUid();
12877        final int permission = mContext.checkCallingOrSelfPermission(
12878                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12879        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
12880        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12881        boolean sendNow = false;
12882        boolean isApp = (className == null);
12883        String componentName = isApp ? packageName : className;
12884        int packageUid = -1;
12885        ArrayList<String> components;
12886
12887        // writer
12888        synchronized (mPackages) {
12889            pkgSetting = mSettings.mPackages.get(packageName);
12890            if (pkgSetting == null) {
12891                if (className == null) {
12892                    throw new IllegalArgumentException(
12893                            "Unknown package: " + packageName);
12894                }
12895                throw new IllegalArgumentException(
12896                        "Unknown component: " + packageName
12897                        + "/" + className);
12898            }
12899            // Allow root and verify that userId is not being specified by a different user
12900            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
12901                throw new SecurityException(
12902                        "Permission Denial: attempt to change component state from pid="
12903                        + Binder.getCallingPid()
12904                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
12905            }
12906            if (className == null) {
12907                // We're dealing with an application/package level state change
12908                if (pkgSetting.getEnabled(userId) == newState) {
12909                    // Nothing to do
12910                    return;
12911                }
12912                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
12913                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
12914                    // Don't care about who enables an app.
12915                    callingPackage = null;
12916                }
12917                pkgSetting.setEnabled(newState, userId, callingPackage);
12918                // pkgSetting.pkg.mSetEnabled = newState;
12919            } else {
12920                // We're dealing with a component level state change
12921                // First, verify that this is a valid class name.
12922                PackageParser.Package pkg = pkgSetting.pkg;
12923                if (pkg == null || !pkg.hasComponentClassName(className)) {
12924                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
12925                        throw new IllegalArgumentException("Component class " + className
12926                                + " does not exist in " + packageName);
12927                    } else {
12928                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
12929                                + className + " does not exist in " + packageName);
12930                    }
12931                }
12932                switch (newState) {
12933                case COMPONENT_ENABLED_STATE_ENABLED:
12934                    if (!pkgSetting.enableComponentLPw(className, userId)) {
12935                        return;
12936                    }
12937                    break;
12938                case COMPONENT_ENABLED_STATE_DISABLED:
12939                    if (!pkgSetting.disableComponentLPw(className, userId)) {
12940                        return;
12941                    }
12942                    break;
12943                case COMPONENT_ENABLED_STATE_DEFAULT:
12944                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
12945                        return;
12946                    }
12947                    break;
12948                default:
12949                    Slog.e(TAG, "Invalid new component state: " + newState);
12950                    return;
12951                }
12952            }
12953            scheduleWritePackageRestrictionsLocked(userId);
12954            components = mPendingBroadcasts.get(userId, packageName);
12955            final boolean newPackage = components == null;
12956            if (newPackage) {
12957                components = new ArrayList<String>();
12958            }
12959            if (!components.contains(componentName)) {
12960                components.add(componentName);
12961            }
12962            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12963                sendNow = true;
12964                // Purge entry from pending broadcast list if another one exists already
12965                // since we are sending one right away.
12966                mPendingBroadcasts.remove(userId, packageName);
12967            } else {
12968                if (newPackage) {
12969                    mPendingBroadcasts.put(userId, packageName, components);
12970                }
12971                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12972                    // Schedule a message
12973                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12974                }
12975            }
12976        }
12977
12978        long callingId = Binder.clearCallingIdentity();
12979        try {
12980            if (sendNow) {
12981                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12982                sendPackageChangedBroadcast(packageName,
12983                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12984            }
12985        } finally {
12986            Binder.restoreCallingIdentity(callingId);
12987        }
12988    }
12989
12990    private void sendPackageChangedBroadcast(String packageName,
12991            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12992        if (DEBUG_INSTALL)
12993            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12994                    + componentNames);
12995        Bundle extras = new Bundle(4);
12996        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12997        String nameList[] = new String[componentNames.size()];
12998        componentNames.toArray(nameList);
12999        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13000        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13001        extras.putInt(Intent.EXTRA_UID, packageUid);
13002        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13003                new int[] {UserHandle.getUserId(packageUid)});
13004    }
13005
13006    @Override
13007    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13008        if (!sUserManager.exists(userId)) return;
13009        final int uid = Binder.getCallingUid();
13010        final int permission = mContext.checkCallingOrSelfPermission(
13011                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13012        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13013        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13014        // writer
13015        synchronized (mPackages) {
13016            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
13017                    uid, userId)) {
13018                scheduleWritePackageRestrictionsLocked(userId);
13019            }
13020        }
13021    }
13022
13023    @Override
13024    public String getInstallerPackageName(String packageName) {
13025        // reader
13026        synchronized (mPackages) {
13027            return mSettings.getInstallerPackageNameLPr(packageName);
13028        }
13029    }
13030
13031    @Override
13032    public int getApplicationEnabledSetting(String packageName, int userId) {
13033        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13034        int uid = Binder.getCallingUid();
13035        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13036        // reader
13037        synchronized (mPackages) {
13038            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13039        }
13040    }
13041
13042    @Override
13043    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13044        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13045        int uid = Binder.getCallingUid();
13046        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13047        // reader
13048        synchronized (mPackages) {
13049            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13050        }
13051    }
13052
13053    @Override
13054    public void enterSafeMode() {
13055        enforceSystemOrRoot("Only the system can request entering safe mode");
13056
13057        if (!mSystemReady) {
13058            mSafeMode = true;
13059        }
13060    }
13061
13062    @Override
13063    public void systemReady() {
13064        mSystemReady = true;
13065
13066        // Read the compatibilty setting when the system is ready.
13067        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13068                mContext.getContentResolver(),
13069                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13070        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13071        if (DEBUG_SETTINGS) {
13072            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13073        }
13074
13075        synchronized (mPackages) {
13076            // Verify that all of the preferred activity components actually
13077            // exist.  It is possible for applications to be updated and at
13078            // that point remove a previously declared activity component that
13079            // had been set as a preferred activity.  We try to clean this up
13080            // the next time we encounter that preferred activity, but it is
13081            // possible for the user flow to never be able to return to that
13082            // situation so here we do a sanity check to make sure we haven't
13083            // left any junk around.
13084            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13085            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13086                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13087                removed.clear();
13088                for (PreferredActivity pa : pir.filterSet()) {
13089                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13090                        removed.add(pa);
13091                    }
13092                }
13093                if (removed.size() > 0) {
13094                    for (int r=0; r<removed.size(); r++) {
13095                        PreferredActivity pa = removed.get(r);
13096                        Slog.w(TAG, "Removing dangling preferred activity: "
13097                                + pa.mPref.mComponent);
13098                        pir.removeFilter(pa);
13099                    }
13100                    mSettings.writePackageRestrictionsLPr(
13101                            mSettings.mPreferredActivities.keyAt(i));
13102                }
13103            }
13104        }
13105        sUserManager.systemReady();
13106
13107        // Kick off any messages waiting for system ready
13108        if (mPostSystemReadyMessages != null) {
13109            for (Message msg : mPostSystemReadyMessages) {
13110                msg.sendToTarget();
13111            }
13112            mPostSystemReadyMessages = null;
13113        }
13114
13115        // Watch for external volumes that come and go over time
13116        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13117        storage.registerListener(mStorageListener);
13118
13119        mInstallerService.systemReady();
13120    }
13121
13122    @Override
13123    public boolean isSafeMode() {
13124        return mSafeMode;
13125    }
13126
13127    @Override
13128    public boolean hasSystemUidErrors() {
13129        return mHasSystemUidErrors;
13130    }
13131
13132    static String arrayToString(int[] array) {
13133        StringBuffer buf = new StringBuffer(128);
13134        buf.append('[');
13135        if (array != null) {
13136            for (int i=0; i<array.length; i++) {
13137                if (i > 0) buf.append(", ");
13138                buf.append(array[i]);
13139            }
13140        }
13141        buf.append(']');
13142        return buf.toString();
13143    }
13144
13145    static class DumpState {
13146        public static final int DUMP_LIBS = 1 << 0;
13147        public static final int DUMP_FEATURES = 1 << 1;
13148        public static final int DUMP_RESOLVERS = 1 << 2;
13149        public static final int DUMP_PERMISSIONS = 1 << 3;
13150        public static final int DUMP_PACKAGES = 1 << 4;
13151        public static final int DUMP_SHARED_USERS = 1 << 5;
13152        public static final int DUMP_MESSAGES = 1 << 6;
13153        public static final int DUMP_PROVIDERS = 1 << 7;
13154        public static final int DUMP_VERIFIERS = 1 << 8;
13155        public static final int DUMP_PREFERRED = 1 << 9;
13156        public static final int DUMP_PREFERRED_XML = 1 << 10;
13157        public static final int DUMP_KEYSETS = 1 << 11;
13158        public static final int DUMP_VERSION = 1 << 12;
13159        public static final int DUMP_INSTALLS = 1 << 13;
13160        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13161        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13162
13163        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13164
13165        private int mTypes;
13166
13167        private int mOptions;
13168
13169        private boolean mTitlePrinted;
13170
13171        private SharedUserSetting mSharedUser;
13172
13173        public boolean isDumping(int type) {
13174            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13175                return true;
13176            }
13177
13178            return (mTypes & type) != 0;
13179        }
13180
13181        public void setDump(int type) {
13182            mTypes |= type;
13183        }
13184
13185        public boolean isOptionEnabled(int option) {
13186            return (mOptions & option) != 0;
13187        }
13188
13189        public void setOptionEnabled(int option) {
13190            mOptions |= option;
13191        }
13192
13193        public boolean onTitlePrinted() {
13194            final boolean printed = mTitlePrinted;
13195            mTitlePrinted = true;
13196            return printed;
13197        }
13198
13199        public boolean getTitlePrinted() {
13200            return mTitlePrinted;
13201        }
13202
13203        public void setTitlePrinted(boolean enabled) {
13204            mTitlePrinted = enabled;
13205        }
13206
13207        public SharedUserSetting getSharedUser() {
13208            return mSharedUser;
13209        }
13210
13211        public void setSharedUser(SharedUserSetting user) {
13212            mSharedUser = user;
13213        }
13214    }
13215
13216    @Override
13217    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13218        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13219                != PackageManager.PERMISSION_GRANTED) {
13220            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13221                    + Binder.getCallingPid()
13222                    + ", uid=" + Binder.getCallingUid()
13223                    + " without permission "
13224                    + android.Manifest.permission.DUMP);
13225            return;
13226        }
13227
13228        DumpState dumpState = new DumpState();
13229        boolean fullPreferred = false;
13230        boolean checkin = false;
13231
13232        String packageName = null;
13233
13234        int opti = 0;
13235        while (opti < args.length) {
13236            String opt = args[opti];
13237            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13238                break;
13239            }
13240            opti++;
13241
13242            if ("-a".equals(opt)) {
13243                // Right now we only know how to print all.
13244            } else if ("-h".equals(opt)) {
13245                pw.println("Package manager dump options:");
13246                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13247                pw.println("    --checkin: dump for a checkin");
13248                pw.println("    -f: print details of intent filters");
13249                pw.println("    -h: print this help");
13250                pw.println("  cmd may be one of:");
13251                pw.println("    l[ibraries]: list known shared libraries");
13252                pw.println("    f[ibraries]: list device features");
13253                pw.println("    k[eysets]: print known keysets");
13254                pw.println("    r[esolvers]: dump intent resolvers");
13255                pw.println("    perm[issions]: dump permissions");
13256                pw.println("    pref[erred]: print preferred package settings");
13257                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13258                pw.println("    prov[iders]: dump content providers");
13259                pw.println("    p[ackages]: dump installed packages");
13260                pw.println("    s[hared-users]: dump shared user IDs");
13261                pw.println("    m[essages]: print collected runtime messages");
13262                pw.println("    v[erifiers]: print package verifier info");
13263                pw.println("    version: print database version info");
13264                pw.println("    write: write current settings now");
13265                pw.println("    <package.name>: info about given package");
13266                pw.println("    installs: details about install sessions");
13267                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13268                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13269                return;
13270            } else if ("--checkin".equals(opt)) {
13271                checkin = true;
13272            } else if ("-f".equals(opt)) {
13273                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13274            } else {
13275                pw.println("Unknown argument: " + opt + "; use -h for help");
13276            }
13277        }
13278
13279        // Is the caller requesting to dump a particular piece of data?
13280        if (opti < args.length) {
13281            String cmd = args[opti];
13282            opti++;
13283            // Is this a package name?
13284            if ("android".equals(cmd) || cmd.contains(".")) {
13285                packageName = cmd;
13286                // When dumping a single package, we always dump all of its
13287                // filter information since the amount of data will be reasonable.
13288                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13289            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13290                dumpState.setDump(DumpState.DUMP_LIBS);
13291            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13292                dumpState.setDump(DumpState.DUMP_FEATURES);
13293            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13294                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13295            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13296                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13297            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13298                dumpState.setDump(DumpState.DUMP_PREFERRED);
13299            } else if ("preferred-xml".equals(cmd)) {
13300                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13301                if (opti < args.length && "--full".equals(args[opti])) {
13302                    fullPreferred = true;
13303                    opti++;
13304                }
13305            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13306                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13307            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13308                dumpState.setDump(DumpState.DUMP_PACKAGES);
13309            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13310                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13311            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13312                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13313            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13314                dumpState.setDump(DumpState.DUMP_MESSAGES);
13315            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13316                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13317            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13318                    || "intent-filter-verifiers".equals(cmd)) {
13319                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13320            } else if ("version".equals(cmd)) {
13321                dumpState.setDump(DumpState.DUMP_VERSION);
13322            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13323                dumpState.setDump(DumpState.DUMP_KEYSETS);
13324            } else if ("installs".equals(cmd)) {
13325                dumpState.setDump(DumpState.DUMP_INSTALLS);
13326            } else if ("write".equals(cmd)) {
13327                synchronized (mPackages) {
13328                    mSettings.writeLPr();
13329                    pw.println("Settings written.");
13330                    return;
13331                }
13332            }
13333        }
13334
13335        if (checkin) {
13336            pw.println("vers,1");
13337        }
13338
13339        // reader
13340        synchronized (mPackages) {
13341            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13342                if (!checkin) {
13343                    if (dumpState.onTitlePrinted())
13344                        pw.println();
13345                    pw.println("Database versions:");
13346                    pw.print("  SDK Version:");
13347                    pw.print(" internal=");
13348                    pw.print(mSettings.mInternalSdkPlatform);
13349                    pw.print(" external=");
13350                    pw.println(mSettings.mExternalSdkPlatform);
13351                    pw.print("  DB Version:");
13352                    pw.print(" internal=");
13353                    pw.print(mSettings.mInternalDatabaseVersion);
13354                    pw.print(" external=");
13355                    pw.println(mSettings.mExternalDatabaseVersion);
13356                }
13357            }
13358
13359            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13360                if (!checkin) {
13361                    if (dumpState.onTitlePrinted())
13362                        pw.println();
13363                    pw.println("Verifiers:");
13364                    pw.print("  Required: ");
13365                    pw.print(mRequiredVerifierPackage);
13366                    pw.print(" (uid=");
13367                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13368                    pw.println(")");
13369                } else if (mRequiredVerifierPackage != null) {
13370                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13371                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13372                }
13373            }
13374
13375            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13376                    packageName == null) {
13377                if (mIntentFilterVerifierComponent != null) {
13378                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13379                    if (!checkin) {
13380                        if (dumpState.onTitlePrinted())
13381                            pw.println();
13382                        pw.println("Intent Filter Verifier:");
13383                        pw.print("  Using: ");
13384                        pw.print(verifierPackageName);
13385                        pw.print(" (uid=");
13386                        pw.print(getPackageUid(verifierPackageName, 0));
13387                        pw.println(")");
13388                    } else if (verifierPackageName != null) {
13389                        pw.print("ifv,"); pw.print(verifierPackageName);
13390                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13391                    }
13392                } else {
13393                    pw.println();
13394                    pw.println("No Intent Filter Verifier available!");
13395                }
13396            }
13397
13398            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13399                boolean printedHeader = false;
13400                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13401                while (it.hasNext()) {
13402                    String name = it.next();
13403                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13404                    if (!checkin) {
13405                        if (!printedHeader) {
13406                            if (dumpState.onTitlePrinted())
13407                                pw.println();
13408                            pw.println("Libraries:");
13409                            printedHeader = true;
13410                        }
13411                        pw.print("  ");
13412                    } else {
13413                        pw.print("lib,");
13414                    }
13415                    pw.print(name);
13416                    if (!checkin) {
13417                        pw.print(" -> ");
13418                    }
13419                    if (ent.path != null) {
13420                        if (!checkin) {
13421                            pw.print("(jar) ");
13422                            pw.print(ent.path);
13423                        } else {
13424                            pw.print(",jar,");
13425                            pw.print(ent.path);
13426                        }
13427                    } else {
13428                        if (!checkin) {
13429                            pw.print("(apk) ");
13430                            pw.print(ent.apk);
13431                        } else {
13432                            pw.print(",apk,");
13433                            pw.print(ent.apk);
13434                        }
13435                    }
13436                    pw.println();
13437                }
13438            }
13439
13440            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
13441                if (dumpState.onTitlePrinted())
13442                    pw.println();
13443                if (!checkin) {
13444                    pw.println("Features:");
13445                }
13446                Iterator<String> it = mAvailableFeatures.keySet().iterator();
13447                while (it.hasNext()) {
13448                    String name = it.next();
13449                    if (!checkin) {
13450                        pw.print("  ");
13451                    } else {
13452                        pw.print("feat,");
13453                    }
13454                    pw.println(name);
13455                }
13456            }
13457
13458            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
13459                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
13460                        : "Activity Resolver Table:", "  ", packageName,
13461                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13462                    dumpState.setTitlePrinted(true);
13463                }
13464                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
13465                        : "Receiver Resolver Table:", "  ", packageName,
13466                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13467                    dumpState.setTitlePrinted(true);
13468                }
13469                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
13470                        : "Service Resolver Table:", "  ", packageName,
13471                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13472                    dumpState.setTitlePrinted(true);
13473                }
13474                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
13475                        : "Provider Resolver Table:", "  ", packageName,
13476                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13477                    dumpState.setTitlePrinted(true);
13478                }
13479            }
13480
13481            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
13482                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13483                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13484                    int user = mSettings.mPreferredActivities.keyAt(i);
13485                    if (pir.dump(pw,
13486                            dumpState.getTitlePrinted()
13487                                ? "\nPreferred Activities User " + user + ":"
13488                                : "Preferred Activities User " + user + ":", "  ",
13489                            packageName, true, false)) {
13490                        dumpState.setTitlePrinted(true);
13491                    }
13492                }
13493            }
13494
13495            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
13496                pw.flush();
13497                FileOutputStream fout = new FileOutputStream(fd);
13498                BufferedOutputStream str = new BufferedOutputStream(fout);
13499                XmlSerializer serializer = new FastXmlSerializer();
13500                try {
13501                    serializer.setOutput(str, "utf-8");
13502                    serializer.startDocument(null, true);
13503                    serializer.setFeature(
13504                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
13505                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
13506                    serializer.endDocument();
13507                    serializer.flush();
13508                } catch (IllegalArgumentException e) {
13509                    pw.println("Failed writing: " + e);
13510                } catch (IllegalStateException e) {
13511                    pw.println("Failed writing: " + e);
13512                } catch (IOException e) {
13513                    pw.println("Failed writing: " + e);
13514                }
13515            }
13516
13517            if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) {
13518                pw.println();
13519                int count = mSettings.mPackages.size();
13520                if (count == 0) {
13521                    pw.println("No domain preferred apps!");
13522                    pw.println();
13523                } else {
13524                    final String prefix = "  ";
13525                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
13526                    if (allPackageSettings.size() == 0) {
13527                        pw.println("No domain preferred apps!");
13528                        pw.println();
13529                    } else {
13530                        pw.println("Domain preferred apps status:");
13531                        pw.println();
13532                        count = 0;
13533                        for (PackageSetting ps : allPackageSettings) {
13534                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13535                            if (ivi == null || ivi.getPackageName() == null) continue;
13536                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
13537                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
13538                            pw.println(prefix + "Status: " + ivi.getStatusString());
13539                            pw.println();
13540                            count++;
13541                        }
13542                        if (count == 0) {
13543                            pw.println(prefix + "No domain preferred app status!");
13544                            pw.println();
13545                        }
13546                        for (int userId : sUserManager.getUserIds()) {
13547                            pw.println("Domain preferred apps for User " + userId + ":");
13548                            pw.println();
13549                            count = 0;
13550                            for (PackageSetting ps : allPackageSettings) {
13551                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13552                                if (ivi == null || ivi.getPackageName() == null) {
13553                                    continue;
13554                                }
13555                                final int status = ps.getDomainVerificationStatusForUser(userId);
13556                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
13557                                    continue;
13558                                }
13559                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
13560                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
13561                                String statusStr = IntentFilterVerificationInfo.
13562                                        getStatusStringFromValue(status);
13563                                pw.println(prefix + "Status: " + statusStr);
13564                                pw.println();
13565                                count++;
13566                            }
13567                            if (count == 0) {
13568                                pw.println(prefix + "No domain preferred apps!");
13569                                pw.println();
13570                            }
13571                        }
13572                    }
13573                }
13574            }
13575
13576            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
13577                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
13578                if (packageName == null) {
13579                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
13580                        if (iperm == 0) {
13581                            if (dumpState.onTitlePrinted())
13582                                pw.println();
13583                            pw.println("AppOp Permissions:");
13584                        }
13585                        pw.print("  AppOp Permission ");
13586                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
13587                        pw.println(":");
13588                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
13589                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
13590                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
13591                        }
13592                    }
13593                }
13594            }
13595
13596            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
13597                boolean printedSomething = false;
13598                for (PackageParser.Provider p : mProviders.mProviders.values()) {
13599                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13600                        continue;
13601                    }
13602                    if (!printedSomething) {
13603                        if (dumpState.onTitlePrinted())
13604                            pw.println();
13605                        pw.println("Registered ContentProviders:");
13606                        printedSomething = true;
13607                    }
13608                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
13609                    pw.print("    "); pw.println(p.toString());
13610                }
13611                printedSomething = false;
13612                for (Map.Entry<String, PackageParser.Provider> entry :
13613                        mProvidersByAuthority.entrySet()) {
13614                    PackageParser.Provider p = entry.getValue();
13615                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13616                        continue;
13617                    }
13618                    if (!printedSomething) {
13619                        if (dumpState.onTitlePrinted())
13620                            pw.println();
13621                        pw.println("ContentProvider Authorities:");
13622                        printedSomething = true;
13623                    }
13624                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
13625                    pw.print("    "); pw.println(p.toString());
13626                    if (p.info != null && p.info.applicationInfo != null) {
13627                        final String appInfo = p.info.applicationInfo.toString();
13628                        pw.print("      applicationInfo="); pw.println(appInfo);
13629                    }
13630                }
13631            }
13632
13633            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
13634                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
13635            }
13636
13637            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
13638                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
13639            }
13640
13641            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
13642                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
13643            }
13644
13645            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
13646                // XXX should handle packageName != null by dumping only install data that
13647                // the given package is involved with.
13648                if (dumpState.onTitlePrinted()) pw.println();
13649                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
13650            }
13651
13652            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
13653                if (dumpState.onTitlePrinted()) pw.println();
13654                mSettings.dumpReadMessagesLPr(pw, dumpState);
13655
13656                pw.println();
13657                pw.println("Package warning messages:");
13658                BufferedReader in = null;
13659                String line = null;
13660                try {
13661                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
13662                    while ((line = in.readLine()) != null) {
13663                        if (line.contains("ignored: updated version")) continue;
13664                        pw.println(line);
13665                    }
13666                } catch (IOException ignored) {
13667                } finally {
13668                    IoUtils.closeQuietly(in);
13669                }
13670            }
13671
13672            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
13673                BufferedReader in = null;
13674                String line = null;
13675                try {
13676                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
13677                    while ((line = in.readLine()) != null) {
13678                        if (line.contains("ignored: updated version")) continue;
13679                        pw.print("msg,");
13680                        pw.println(line);
13681                    }
13682                } catch (IOException ignored) {
13683                } finally {
13684                    IoUtils.closeQuietly(in);
13685                }
13686            }
13687        }
13688    }
13689
13690    // ------- apps on sdcard specific code -------
13691    static final boolean DEBUG_SD_INSTALL = false;
13692
13693    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
13694
13695    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
13696
13697    private boolean mMediaMounted = false;
13698
13699    static String getEncryptKey() {
13700        try {
13701            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
13702                    SD_ENCRYPTION_KEYSTORE_NAME);
13703            if (sdEncKey == null) {
13704                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
13705                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
13706                if (sdEncKey == null) {
13707                    Slog.e(TAG, "Failed to create encryption keys");
13708                    return null;
13709                }
13710            }
13711            return sdEncKey;
13712        } catch (NoSuchAlgorithmException nsae) {
13713            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
13714            return null;
13715        } catch (IOException ioe) {
13716            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
13717            return null;
13718        }
13719    }
13720
13721    /*
13722     * Update media status on PackageManager.
13723     */
13724    @Override
13725    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
13726        int callingUid = Binder.getCallingUid();
13727        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
13728            throw new SecurityException("Media status can only be updated by the system");
13729        }
13730        // reader; this apparently protects mMediaMounted, but should probably
13731        // be a different lock in that case.
13732        synchronized (mPackages) {
13733            Log.i(TAG, "Updating external media status from "
13734                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
13735                    + (mediaStatus ? "mounted" : "unmounted"));
13736            if (DEBUG_SD_INSTALL)
13737                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
13738                        + ", mMediaMounted=" + mMediaMounted);
13739            if (mediaStatus == mMediaMounted) {
13740                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
13741                        : 0, -1);
13742                mHandler.sendMessage(msg);
13743                return;
13744            }
13745            mMediaMounted = mediaStatus;
13746        }
13747        // Queue up an async operation since the package installation may take a
13748        // little while.
13749        mHandler.post(new Runnable() {
13750            public void run() {
13751                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
13752            }
13753        });
13754    }
13755
13756    /**
13757     * Called by MountService when the initial ASECs to scan are available.
13758     * Should block until all the ASEC containers are finished being scanned.
13759     */
13760    public void scanAvailableAsecs() {
13761        updateExternalMediaStatusInner(true, false, false);
13762        if (mShouldRestoreconData) {
13763            SELinuxMMAC.setRestoreconDone();
13764            mShouldRestoreconData = false;
13765        }
13766    }
13767
13768    /*
13769     * Collect information of applications on external media, map them against
13770     * existing containers and update information based on current mount status.
13771     * Please note that we always have to report status if reportStatus has been
13772     * set to true especially when unloading packages.
13773     */
13774    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
13775            boolean externalStorage) {
13776        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
13777        int[] uidArr = EmptyArray.INT;
13778
13779        final String[] list = PackageHelper.getSecureContainerList();
13780        if (ArrayUtils.isEmpty(list)) {
13781            Log.i(TAG, "No secure containers found");
13782        } else {
13783            // Process list of secure containers and categorize them
13784            // as active or stale based on their package internal state.
13785
13786            // reader
13787            synchronized (mPackages) {
13788                for (String cid : list) {
13789                    // Leave stages untouched for now; installer service owns them
13790                    if (PackageInstallerService.isStageName(cid)) continue;
13791
13792                    if (DEBUG_SD_INSTALL)
13793                        Log.i(TAG, "Processing container " + cid);
13794                    String pkgName = getAsecPackageName(cid);
13795                    if (pkgName == null) {
13796                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
13797                        continue;
13798                    }
13799                    if (DEBUG_SD_INSTALL)
13800                        Log.i(TAG, "Looking for pkg : " + pkgName);
13801
13802                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
13803                    if (ps == null) {
13804                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
13805                        continue;
13806                    }
13807
13808                    /*
13809                     * Skip packages that are not external if we're unmounting
13810                     * external storage.
13811                     */
13812                    if (externalStorage && !isMounted && !isExternal(ps)) {
13813                        continue;
13814                    }
13815
13816                    final AsecInstallArgs args = new AsecInstallArgs(cid,
13817                            getAppDexInstructionSets(ps), ps.isForwardLocked());
13818                    // The package status is changed only if the code path
13819                    // matches between settings and the container id.
13820                    if (ps.codePathString != null
13821                            && ps.codePathString.startsWith(args.getCodePath())) {
13822                        if (DEBUG_SD_INSTALL) {
13823                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
13824                                    + " at code path: " + ps.codePathString);
13825                        }
13826
13827                        // We do have a valid package installed on sdcard
13828                        processCids.put(args, ps.codePathString);
13829                        final int uid = ps.appId;
13830                        if (uid != -1) {
13831                            uidArr = ArrayUtils.appendInt(uidArr, uid);
13832                        }
13833                    } else {
13834                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
13835                                + ps.codePathString);
13836                    }
13837                }
13838            }
13839
13840            Arrays.sort(uidArr);
13841        }
13842
13843        // Process packages with valid entries.
13844        if (isMounted) {
13845            if (DEBUG_SD_INSTALL)
13846                Log.i(TAG, "Loading packages");
13847            loadMediaPackages(processCids, uidArr);
13848            startCleaningPackages();
13849            mInstallerService.onSecureContainersAvailable();
13850        } else {
13851            if (DEBUG_SD_INSTALL)
13852                Log.i(TAG, "Unloading packages");
13853            unloadMediaPackages(processCids, uidArr, reportStatus);
13854        }
13855    }
13856
13857    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13858            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
13859        final int size = infos.size();
13860        final String[] packageNames = new String[size];
13861        final int[] packageUids = new int[size];
13862        for (int i = 0; i < size; i++) {
13863            final ApplicationInfo info = infos.get(i);
13864            packageNames[i] = info.packageName;
13865            packageUids[i] = info.uid;
13866        }
13867        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
13868                finishedReceiver);
13869    }
13870
13871    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13872            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
13873        sendResourcesChangedBroadcast(mediaStatus, replacing,
13874                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
13875    }
13876
13877    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13878            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
13879        int size = pkgList.length;
13880        if (size > 0) {
13881            // Send broadcasts here
13882            Bundle extras = new Bundle();
13883            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13884            if (uidArr != null) {
13885                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
13886            }
13887            if (replacing) {
13888                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
13889            }
13890            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
13891                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
13892            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
13893        }
13894    }
13895
13896   /*
13897     * Look at potentially valid container ids from processCids If package
13898     * information doesn't match the one on record or package scanning fails,
13899     * the cid is added to list of removeCids. We currently don't delete stale
13900     * containers.
13901     */
13902    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
13903        ArrayList<String> pkgList = new ArrayList<String>();
13904        Set<AsecInstallArgs> keys = processCids.keySet();
13905
13906        for (AsecInstallArgs args : keys) {
13907            String codePath = processCids.get(args);
13908            if (DEBUG_SD_INSTALL)
13909                Log.i(TAG, "Loading container : " + args.cid);
13910            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13911            try {
13912                // Make sure there are no container errors first.
13913                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
13914                    Slog.e(TAG, "Failed to mount cid : " + args.cid
13915                            + " when installing from sdcard");
13916                    continue;
13917                }
13918                // Check code path here.
13919                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
13920                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
13921                            + " does not match one in settings " + codePath);
13922                    continue;
13923                }
13924                // Parse package
13925                int parseFlags = mDefParseFlags;
13926                if (args.isExternalAsec()) {
13927                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
13928                }
13929                if (args.isFwdLocked()) {
13930                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
13931                }
13932
13933                synchronized (mInstallLock) {
13934                    PackageParser.Package pkg = null;
13935                    try {
13936                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
13937                    } catch (PackageManagerException e) {
13938                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
13939                    }
13940                    // Scan the package
13941                    if (pkg != null) {
13942                        /*
13943                         * TODO why is the lock being held? doPostInstall is
13944                         * called in other places without the lock. This needs
13945                         * to be straightened out.
13946                         */
13947                        // writer
13948                        synchronized (mPackages) {
13949                            retCode = PackageManager.INSTALL_SUCCEEDED;
13950                            pkgList.add(pkg.packageName);
13951                            // Post process args
13952                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
13953                                    pkg.applicationInfo.uid);
13954                        }
13955                    } else {
13956                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
13957                    }
13958                }
13959
13960            } finally {
13961                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
13962                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
13963                }
13964            }
13965        }
13966        // writer
13967        synchronized (mPackages) {
13968            // If the platform SDK has changed since the last time we booted,
13969            // we need to re-grant app permission to catch any new ones that
13970            // appear. This is really a hack, and means that apps can in some
13971            // cases get permissions that the user didn't initially explicitly
13972            // allow... it would be nice to have some better way to handle
13973            // this situation.
13974            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
13975            if (regrantPermissions)
13976                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
13977                        + mSdkVersion + "; regranting permissions for external storage");
13978            mSettings.mExternalSdkPlatform = mSdkVersion;
13979
13980            // Make sure group IDs have been assigned, and any permission
13981            // changes in other apps are accounted for
13982            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
13983                    | (regrantPermissions
13984                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
13985                            : 0));
13986
13987            mSettings.updateExternalDatabaseVersion();
13988
13989            // can downgrade to reader
13990            // Persist settings
13991            mSettings.writeLPr();
13992        }
13993        // Send a broadcast to let everyone know we are done processing
13994        if (pkgList.size() > 0) {
13995            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13996        }
13997    }
13998
13999   /*
14000     * Utility method to unload a list of specified containers
14001     */
14002    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14003        // Just unmount all valid containers.
14004        for (AsecInstallArgs arg : cidArgs) {
14005            synchronized (mInstallLock) {
14006                arg.doPostDeleteLI(false);
14007           }
14008       }
14009   }
14010
14011    /*
14012     * Unload packages mounted on external media. This involves deleting package
14013     * data from internal structures, sending broadcasts about diabled packages,
14014     * gc'ing to free up references, unmounting all secure containers
14015     * corresponding to packages on external media, and posting a
14016     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14017     * that we always have to post this message if status has been requested no
14018     * matter what.
14019     */
14020    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14021            final boolean reportStatus) {
14022        if (DEBUG_SD_INSTALL)
14023            Log.i(TAG, "unloading media packages");
14024        ArrayList<String> pkgList = new ArrayList<String>();
14025        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14026        final Set<AsecInstallArgs> keys = processCids.keySet();
14027        for (AsecInstallArgs args : keys) {
14028            String pkgName = args.getPackageName();
14029            if (DEBUG_SD_INSTALL)
14030                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14031            // Delete package internally
14032            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14033            synchronized (mInstallLock) {
14034                boolean res = deletePackageLI(pkgName, null, false, null, null,
14035                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14036                if (res) {
14037                    pkgList.add(pkgName);
14038                } else {
14039                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14040                    failedList.add(args);
14041                }
14042            }
14043        }
14044
14045        // reader
14046        synchronized (mPackages) {
14047            // We didn't update the settings after removing each package;
14048            // write them now for all packages.
14049            mSettings.writeLPr();
14050        }
14051
14052        // We have to absolutely send UPDATED_MEDIA_STATUS only
14053        // after confirming that all the receivers processed the ordered
14054        // broadcast when packages get disabled, force a gc to clean things up.
14055        // and unload all the containers.
14056        if (pkgList.size() > 0) {
14057            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14058                    new IIntentReceiver.Stub() {
14059                public void performReceive(Intent intent, int resultCode, String data,
14060                        Bundle extras, boolean ordered, boolean sticky,
14061                        int sendingUser) throws RemoteException {
14062                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14063                            reportStatus ? 1 : 0, 1, keys);
14064                    mHandler.sendMessage(msg);
14065                }
14066            });
14067        } else {
14068            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14069                    keys);
14070            mHandler.sendMessage(msg);
14071        }
14072    }
14073
14074    private void loadPrivatePackages(VolumeInfo vol) {
14075        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14076        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14077        synchronized (mPackages) {
14078            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14079            for (PackageSetting ps : packages) {
14080                synchronized (mInstallLock) {
14081                    final PackageParser.Package pkg;
14082                    try {
14083                        pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14084                        loaded.add(pkg.applicationInfo);
14085                    } catch (PackageManagerException e) {
14086                        Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14087                    }
14088                }
14089            }
14090
14091            // TODO: regrant any permissions that changed based since original install
14092
14093            mSettings.writeLPr();
14094        }
14095
14096        Slog.d(TAG, "Loaded packages " + loaded);
14097        sendResourcesChangedBroadcast(true, false, loaded, null);
14098    }
14099
14100    private void unloadPrivatePackages(VolumeInfo vol) {
14101        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14102        synchronized (mPackages) {
14103            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14104            for (PackageSetting ps : packages) {
14105                if (ps.pkg == null) continue;
14106                synchronized (mInstallLock) {
14107                    final ApplicationInfo info = ps.pkg.applicationInfo;
14108                    final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14109                    if (deletePackageLI(ps.name, null, false, null, null,
14110                            PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14111                        unloaded.add(info);
14112                    } else {
14113                        Slog.w(TAG, "Failed to unload " + ps.codePath);
14114                    }
14115                }
14116            }
14117
14118            mSettings.writeLPr();
14119        }
14120
14121        Slog.d(TAG, "Unloaded packages " + unloaded);
14122        sendResourcesChangedBroadcast(false, false, unloaded, null);
14123    }
14124
14125    @Override
14126    public void movePackage(final String packageName, final IPackageMoveObserver observer,
14127            final int flags) {
14128        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14129
14130        final int installFlags;
14131        if ((flags & MOVE_INTERNAL) != 0) {
14132            installFlags = INSTALL_INTERNAL;
14133        } else if ((flags & MOVE_EXTERNAL_MEDIA) != 0) {
14134            installFlags = INSTALL_EXTERNAL;
14135        } else {
14136            throw new IllegalArgumentException("Unsupported move flags " + flags);
14137        }
14138
14139        try {
14140            movePackageInternal(packageName, null, installFlags, false, observer);
14141        } catch (PackageManagerException e) {
14142            Slog.d(TAG, "Failed to move " + packageName, e);
14143            try {
14144                observer.packageMoved(packageName, e.error);
14145            } catch (RemoteException ignored) {
14146            }
14147        }
14148    }
14149
14150    @Override
14151    public void movePackageAndData(final String packageName, final String volumeUuid,
14152            final IPackageMoveObserver observer) {
14153        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14154        try {
14155            movePackageInternal(packageName, volumeUuid, INSTALL_INTERNAL, true, observer);
14156        } catch (PackageManagerException e) {
14157            Slog.d(TAG, "Failed to move " + packageName, e);
14158            try {
14159                observer.packageMoved(packageName, e.error);
14160            } catch (RemoteException ignored) {
14161            }
14162        }
14163    }
14164
14165    private void movePackageInternal(final String packageName, String volumeUuid, int installFlags,
14166            boolean andData, final IPackageMoveObserver observer) throws PackageManagerException {
14167        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14168
14169        File codeFile = null;
14170        String installerPackageName = null;
14171        String packageAbiOverride = null;
14172
14173        // TOOD: move app private data before installing
14174
14175        // reader
14176        synchronized (mPackages) {
14177            final PackageParser.Package pkg = mPackages.get(packageName);
14178            final PackageSetting ps = mSettings.mPackages.get(packageName);
14179            if (pkg == null || ps == null) {
14180                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14181            }
14182
14183            if (pkg.applicationInfo.isSystemApp()) {
14184                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14185                        "Cannot move system application");
14186            } else if (pkg.mOperationPending) {
14187                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14188                        "Attempt to move package which has pending operations");
14189            }
14190
14191            // TODO: yell if already in desired location
14192
14193            pkg.mOperationPending = true;
14194
14195            codeFile = new File(pkg.codePath);
14196            installerPackageName = ps.installerPackageName;
14197            packageAbiOverride = ps.cpuAbiOverrideString;
14198        }
14199
14200        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14201            @Override
14202            public void onUserActionRequired(Intent intent) throws RemoteException {
14203                throw new IllegalStateException();
14204            }
14205
14206            @Override
14207            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14208                    Bundle extras) throws RemoteException {
14209                Slog.d(TAG, "Install result for move: "
14210                        + PackageManager.installStatusToString(returnCode, msg));
14211
14212                // We usually have a new package now after the install, but if
14213                // we failed we need to clear the pending flag on the original
14214                // package object.
14215                synchronized (mPackages) {
14216                    final PackageParser.Package pkg = mPackages.get(packageName);
14217                    if (pkg != null) {
14218                        pkg.mOperationPending = false;
14219                    }
14220                }
14221
14222                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14223                switch (status) {
14224                    case PackageInstaller.STATUS_SUCCESS:
14225                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
14226                        break;
14227                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14228                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14229                        break;
14230                    default:
14231                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14232                        break;
14233                }
14234            }
14235        };
14236
14237        // Treat a move like reinstalling an existing app, which ensures that we
14238        // process everythign uniformly, like unpacking native libraries.
14239        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14240
14241        final Message msg = mHandler.obtainMessage(INIT_COPY);
14242        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14243        msg.obj = new InstallParams(origin, installObserver, installFlags,
14244                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14245        mHandler.sendMessage(msg);
14246    }
14247
14248    @Override
14249    public boolean setInstallLocation(int loc) {
14250        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14251                null);
14252        if (getInstallLocation() == loc) {
14253            return true;
14254        }
14255        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14256                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14257            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14258                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14259            return true;
14260        }
14261        return false;
14262   }
14263
14264    @Override
14265    public int getInstallLocation() {
14266        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14267                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14268                PackageHelper.APP_INSTALL_AUTO);
14269    }
14270
14271    /** Called by UserManagerService */
14272    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14273        mDirtyUsers.remove(userHandle);
14274        mSettings.removeUserLPw(userHandle);
14275        mPendingBroadcasts.remove(userHandle);
14276        if (mInstaller != null) {
14277            // Technically, we shouldn't be doing this with the package lock
14278            // held.  However, this is very rare, and there is already so much
14279            // other disk I/O going on, that we'll let it slide for now.
14280            mInstaller.removeUserDataDirs(userHandle);
14281        }
14282        mUserNeedsBadging.delete(userHandle);
14283        removeUnusedPackagesLILPw(userManager, userHandle);
14284    }
14285
14286    /**
14287     * We're removing userHandle and would like to remove any downloaded packages
14288     * that are no longer in use by any other user.
14289     * @param userHandle the user being removed
14290     */
14291    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
14292        final boolean DEBUG_CLEAN_APKS = false;
14293        int [] users = userManager.getUserIdsLPr();
14294        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
14295        while (psit.hasNext()) {
14296            PackageSetting ps = psit.next();
14297            if (ps.pkg == null) {
14298                continue;
14299            }
14300            final String packageName = ps.pkg.packageName;
14301            // Skip over if system app
14302            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14303                continue;
14304            }
14305            if (DEBUG_CLEAN_APKS) {
14306                Slog.i(TAG, "Checking package " + packageName);
14307            }
14308            boolean keep = false;
14309            for (int i = 0; i < users.length; i++) {
14310                if (users[i] != userHandle && ps.getInstalled(users[i])) {
14311                    keep = true;
14312                    if (DEBUG_CLEAN_APKS) {
14313                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
14314                                + users[i]);
14315                    }
14316                    break;
14317                }
14318            }
14319            if (!keep) {
14320                if (DEBUG_CLEAN_APKS) {
14321                    Slog.i(TAG, "  Removing package " + packageName);
14322                }
14323                mHandler.post(new Runnable() {
14324                    public void run() {
14325                        deletePackageX(packageName, userHandle, 0);
14326                    } //end run
14327                });
14328            }
14329        }
14330    }
14331
14332    /** Called by UserManagerService */
14333    void createNewUserLILPw(int userHandle, File path) {
14334        if (mInstaller != null) {
14335            mInstaller.createUserConfig(userHandle);
14336            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
14337        }
14338    }
14339
14340    void newUserCreatedLILPw(int userHandle) {
14341        // Adding a user requires updating runtime permissions for system apps.
14342        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
14343    }
14344
14345    @Override
14346    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
14347        mContext.enforceCallingOrSelfPermission(
14348                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14349                "Only package verification agents can read the verifier device identity");
14350
14351        synchronized (mPackages) {
14352            return mSettings.getVerifierDeviceIdentityLPw();
14353        }
14354    }
14355
14356    @Override
14357    public void setPermissionEnforced(String permission, boolean enforced) {
14358        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
14359        if (READ_EXTERNAL_STORAGE.equals(permission)) {
14360            synchronized (mPackages) {
14361                if (mSettings.mReadExternalStorageEnforced == null
14362                        || mSettings.mReadExternalStorageEnforced != enforced) {
14363                    mSettings.mReadExternalStorageEnforced = enforced;
14364                    mSettings.writeLPr();
14365                }
14366            }
14367            // kill any non-foreground processes so we restart them and
14368            // grant/revoke the GID.
14369            final IActivityManager am = ActivityManagerNative.getDefault();
14370            if (am != null) {
14371                final long token = Binder.clearCallingIdentity();
14372                try {
14373                    am.killProcessesBelowForeground("setPermissionEnforcement");
14374                } catch (RemoteException e) {
14375                } finally {
14376                    Binder.restoreCallingIdentity(token);
14377                }
14378            }
14379        } else {
14380            throw new IllegalArgumentException("No selective enforcement for " + permission);
14381        }
14382    }
14383
14384    @Override
14385    @Deprecated
14386    public boolean isPermissionEnforced(String permission) {
14387        return true;
14388    }
14389
14390    @Override
14391    public boolean isStorageLow() {
14392        final long token = Binder.clearCallingIdentity();
14393        try {
14394            final DeviceStorageMonitorInternal
14395                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14396            if (dsm != null) {
14397                return dsm.isMemoryLow();
14398            } else {
14399                return false;
14400            }
14401        } finally {
14402            Binder.restoreCallingIdentity(token);
14403        }
14404    }
14405
14406    @Override
14407    public IPackageInstaller getPackageInstaller() {
14408        return mInstallerService;
14409    }
14410
14411    private boolean userNeedsBadging(int userId) {
14412        int index = mUserNeedsBadging.indexOfKey(userId);
14413        if (index < 0) {
14414            final UserInfo userInfo;
14415            final long token = Binder.clearCallingIdentity();
14416            try {
14417                userInfo = sUserManager.getUserInfo(userId);
14418            } finally {
14419                Binder.restoreCallingIdentity(token);
14420            }
14421            final boolean b;
14422            if (userInfo != null && userInfo.isManagedProfile()) {
14423                b = true;
14424            } else {
14425                b = false;
14426            }
14427            mUserNeedsBadging.put(userId, b);
14428            return b;
14429        }
14430        return mUserNeedsBadging.valueAt(index);
14431    }
14432
14433    @Override
14434    public KeySet getKeySetByAlias(String packageName, String alias) {
14435        if (packageName == null || alias == null) {
14436            return null;
14437        }
14438        synchronized(mPackages) {
14439            final PackageParser.Package pkg = mPackages.get(packageName);
14440            if (pkg == null) {
14441                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14442                throw new IllegalArgumentException("Unknown package: " + packageName);
14443            }
14444            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14445            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
14446        }
14447    }
14448
14449    @Override
14450    public KeySet getSigningKeySet(String packageName) {
14451        if (packageName == null) {
14452            return null;
14453        }
14454        synchronized(mPackages) {
14455            final PackageParser.Package pkg = mPackages.get(packageName);
14456            if (pkg == null) {
14457                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14458                throw new IllegalArgumentException("Unknown package: " + packageName);
14459            }
14460            if (pkg.applicationInfo.uid != Binder.getCallingUid()
14461                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
14462                throw new SecurityException("May not access signing KeySet of other apps.");
14463            }
14464            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14465            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
14466        }
14467    }
14468
14469    @Override
14470    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
14471        if (packageName == null || ks == null) {
14472            return false;
14473        }
14474        synchronized(mPackages) {
14475            final PackageParser.Package pkg = mPackages.get(packageName);
14476            if (pkg == null) {
14477                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14478                throw new IllegalArgumentException("Unknown package: " + packageName);
14479            }
14480            IBinder ksh = ks.getToken();
14481            if (ksh instanceof KeySetHandle) {
14482                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14483                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
14484            }
14485            return false;
14486        }
14487    }
14488
14489    @Override
14490    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
14491        if (packageName == null || ks == null) {
14492            return false;
14493        }
14494        synchronized(mPackages) {
14495            final PackageParser.Package pkg = mPackages.get(packageName);
14496            if (pkg == null) {
14497                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14498                throw new IllegalArgumentException("Unknown package: " + packageName);
14499            }
14500            IBinder ksh = ks.getToken();
14501            if (ksh instanceof KeySetHandle) {
14502                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14503                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
14504            }
14505            return false;
14506        }
14507    }
14508
14509    public void getUsageStatsIfNoPackageUsageInfo() {
14510        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
14511            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
14512            if (usm == null) {
14513                throw new IllegalStateException("UsageStatsManager must be initialized");
14514            }
14515            long now = System.currentTimeMillis();
14516            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
14517            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
14518                String packageName = entry.getKey();
14519                PackageParser.Package pkg = mPackages.get(packageName);
14520                if (pkg == null) {
14521                    continue;
14522                }
14523                UsageStats usage = entry.getValue();
14524                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
14525                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
14526            }
14527        }
14528    }
14529
14530    /**
14531     * Check and throw if the given before/after packages would be considered a
14532     * downgrade.
14533     */
14534    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
14535            throws PackageManagerException {
14536        if (after.versionCode < before.mVersionCode) {
14537            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14538                    "Update version code " + after.versionCode + " is older than current "
14539                    + before.mVersionCode);
14540        } else if (after.versionCode == before.mVersionCode) {
14541            if (after.baseRevisionCode < before.baseRevisionCode) {
14542                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14543                        "Update base revision code " + after.baseRevisionCode
14544                        + " is older than current " + before.baseRevisionCode);
14545            }
14546
14547            if (!ArrayUtils.isEmpty(after.splitNames)) {
14548                for (int i = 0; i < after.splitNames.length; i++) {
14549                    final String splitName = after.splitNames[i];
14550                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
14551                    if (j != -1) {
14552                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
14553                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14554                                    "Update split " + splitName + " revision code "
14555                                    + after.splitRevisionCodes[i] + " is older than current "
14556                                    + before.splitRevisionCodes[j]);
14557                        }
14558                    }
14559                }
14560            }
14561        }
14562    }
14563}
14564